<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-tree
        ref="problemTree"
        :checkable="false"
        :draggable="false"
        :is-search="false"
        :show-line="true"
        :top-node-text="'审计案例'"
        :treeparams="{
          configId: 111,
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="true"
        manager-type="view"
        @treeSelect="treeSelectd"
      >
      </audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <div :class="$style.wrapper">
            <div :class="[$style.btns]">
              <audit-advanced-import
                ref="import"
                :config-id="'161'"
                :table-id="'oaTable'"
                :relevant-column="importTreeId"
                :v-if="false"
              >
              </audit-advanced-import>
            </div>

            <audit-advanced-query
              :expand="expand"
              :search-data="formData"
              :ref-name="'searchform'"
              :search-style="{ height: '125px', left: '20px', top: '64px', width: '100%' }"
              :search-fun="handleSearch"
              @searchedClick="searchedClick"
            >
              <template>
                <a-col :span="8">
                  <a-form-model-item :label="'案例名称'" prop="title">
                    <a-input v-model="formData.title" allow-clear />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item :label="'状态'" prop="state">
                    <sd-select
                      v-model="formData.state"
                      :allow-clear="true"
                      :options="stateOptions"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="8">
                  <a-form-model-item :label="'维护人员'" prop="cUser">
                    <a-input v-model="formData.cUser" allow-clear />
                  </a-form-model-item>
                </a-col>
              </template>
            </audit-advanced-query>
            <sd-data-table-ex
              ref="oaTable"
              :editnode="editnode"
              :form-id="formId"
              :columns="columns"
              :actions="this.isShowAction === true ? adminActions : auditActions"
              :filter-expressions="expressions"
              :show-selection="true"
              :data-url="dataUrl"
              :show-advance-query="true"
              :search-fields="['docTitle']"
              :row-selection="{ type: 'radio' }"
              @recordsDeleted="onRecordsDeleted"
              @searchbtnClick="searchbtnClick"
            >
              <a
                slot="fldSubject"
                slot-scope="text, record"
                :title="text"
                @click="fnReadDoc(record)"
                >{{ text }}</a
              >

              <a slot="opt" slot-scope="text, record" @click="fnEditDoc(record)">编辑</a>
            </sd-data-table-ex>
            <!-- 选择审计问题 -->
            <a-modal
              title="请选择审计问题"
              width="1200px"
              :visible="showFindVisible"
              :confirm-loading="findConfirmLoading"
              destroy-on-close
              @ok="handleOk"
              @cancel="
                () => {
                  showFindVisible = false
                }
              "
            >
              <sd-data-table-ex
                ref="findTable"
                data-url="api/xcoa-mobile/v1/spicproblem/findQuestionList"
                form-id="iamAuditReportFind"
                :columns="findListColumns"
                :row-key="'findTitle'"
                :filter-expressions="findExpressions"
                :search-fields="['findTitle', 'findCode']"
                show-selection
              >
                <template slot="findType" slot-scope="text">
                  {{ JSON.parse(text).text }}
                </template>
              </sd-data-table-ex>
            </a-modal>
            <!-- 导入弹窗 -->
            <xm-spic-problem-import-modal
              :parent-id="typeId + ''"
              :visible="importVisible"
            ></xm-spic-problem-import-modal>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import PageService from '@/common/services/page-service'
import { getUserInfo, getUserPerms } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import openAsTrustId from '@/common/services/open-as-trust-id'
import download from '@/common/services/download'
import auditAdvancedImport from '@product/iam/components/audit-advanced-import.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditTree from '@product/iam/components/audit-tree.vue'
import xmSpicProblemImportModal from './xm-spic-problem-import-modal.vue'
import problemService from './xm-spic-problem-service.js'
import components from './_import-components/xm-spic-problem-list-import'

export default {
  name: 'XmSpicProblemList',
  metaInfo: {
    title: '审计案例',
  },
  components: {
    auditTree,
    auditAdvancedQuery,
    auditAdvancedImport,
    xmSpicProblemImportModal,
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],

  props: {
    // 是不是用于选择知识
    isSelectd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showFindVisible: false,
      findConfirmLoading: false,
      stateOptions: [
        {
          id: '暂存',
          name: '暂存',
        },
        {
          id: '已发布',
          name: '已发布',
        },
      ],
      importVisible: false, // 导入弹窗
      editnode: true,
      formData: {
        title: '',
        label: '',
        state: '',
        cUser: '',
      },
      dataUrl: 'api/xcoa-mobile/v1/spicproblem/all-list',
      expand: false,
      // 左侧树用，用于创建对应分类数据
      parentId: 0,
      importTreeId: 0,
      categorys: [],
      activeKey: 'textlist',
      isKmAdmin: false,
      expressions: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          title: '案例名称',
          dataIndex: 'docTitle',
          scopedSlots: { customRender: 'fldSubject' },
          width: '30%',
        },
        {
          title: '案例编号',
          dataIndex: 'problemNumber',
          // defaultSortOrder: 'asc',
        },
        {
          title: '状态',
          dataIndex: 'state',
        },
        {
          title: '维护人员',
          dataIndex: 'creatorName',
        },
        {
          title: '维护人员账号',
          sdHidden: true,
          dataIndex: 'creatorAccount',
        },

        {
          title: '维护日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          defaultSortOrder: 'desc',
        },
      ],

      findListColumns: [
        {
          title: '序号',
          dataIndex: 'sortNumber',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '问题Id',
          dataIndex: 'id',
          width: '80px',
          sdHidden: true,
        },
        { dataIndex: 'findTitle', title: '问题名称', width: '40%' },
        { dataIndex: 'findCode', title: '问题编号' },
        {
          dataIndex: 'auditedUnitNames',
          title: '被审计单位',
          scopedSlots: { customRender: 'auditedUnitNames' },
        },
      ],
      findExpressions: [
        // {
        //   dataType: 'long',
        //   name: 'projectId',
        //   op: 'eq',
        //   longValue: this.$root.$route.query.projectId,
        // },
      ],
      auditActions: [
        {
          label: '选择',
          permission: null,
          id: 'find',
          type: null,
          callback: () => {
            this.showFindVisible = true
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null, // 纯前端操作，不需要权限控制
          // type: TableActionTypes.batch,
          // type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
          // callback: this.deleteRows,
          callback: () => {
            this.deleteRows()
          },
        },
        {
          label: '新建',
          id: 'create', // 没写type，一般按钮
          permission: null, // 纯前端操作，不需要权限控制
          type: TableActionTypes.primary,
          callback: () => {
            this.fnCreatDoc()
          },
        },
        {
          label: '导出',
          id: 'exportProblem',
          permission: null,
          callback: this.exportProblem, // 纯前端操作，不需要权限控制
        },
      ],

      adminActions: [
        {
          label: '选择',
          permission: null,
          id: 'find',
          type: null,
          callback: () => {
            this.showFindVisible = true
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: null, // 纯前端操作，不需要权限控制
          callback: () => {
            this.deleteRows()
          },
        },
        {
          label: '新建',
          id: 'create', // 没写type，一般按钮
          permission: null, // 纯前端操作，不需要权限控制
          type: TableActionTypes.primary,
          callback: () => {
            this.fnCreatDoc()
          },
        },
        {
          label: '分类配置',
          id: 'auditMattersCatalog',
          permission: null,
          callback: () => {
            const url = '/sd-frame/xm-spic-problem-category' // 新页面要打开的路由地址
            openAsTrustId(url, null)
          },
        },
        {
          label: '导出',
          id: 'exportProblem',
          permission: null,
          callback: this.exportProblem, // 纯前端操作，不需要权限控制
        },
      ],
      businessTypeId: null,
      typeId: null,
      typeName: '',
      isApplicationAdmin: false,
      isShowAction: false,
      formId: 'spicProblem',
      // 图文列表参数
      showCreateBtn: false,
      showDeleteBtn: false,
      pictureData: [],
      pagination: {
        onChange: (page) => {
          this.paginationChange(page)
        },
        current: 1,
        pageSize: 8,
        showTotal(total) {
          return `共${total}条`
        },
      },
      loading: false, // 图文列表数据的loading
      orderType: 'creationTime',
      creationTimeDesc: true,
      pictureRowSelection: [],
      searchText: '',
      picList: '',
    }
  },
  // 图文列表参数变化更新数据
  watch: {
    orderType() {
      this.pictureListRefresh()
    },
    creationTimeDesc() {
      this.pictureListRefresh()
    },
  },
  created() {
    if (getUserInfo().roles.findIndex((item) => item.code === 'KM_ADMIN') !== -1) {
      this.isKmAdmin = true
    }
    // 图文列表获取数据
    this.treeSelectd({}, { id: 0 })
  },
  mounted() {
    // 初始化权限
    this.initJurisdiction()
  },
  methods: {
    // 初始化权限
    initJurisdiction() {
      // debugger
      // 校验权限查询当前用户是否是审计案例库管理员角色（是否为模块管理员）
      problemService.checkSpicProblemPermission().then((res) => {
        this.isApplicationAdmin = res.data.isHasPermission
      })

      // 判断是否是模块管理员 或者 是否是审计人员（角色）
      problemService.checkSpicAuditPermission().then((res) => {
        this.isShowAction = res.data.isHasPermission
        console.log(this.isShowAction, '----------------')
      })
    },
    // 显示导入弹窗
    showImportModal() {
      this.importVisible = !this.importVisible
    },
    searchedClick() {
      this.expand = false
    },
    // 查询
    handleSearch() {
      this.expressions = [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: this.typeId,
        },
      ]

      // 资料名称
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'docTitle',
          op: 'like',
          stringValue: `%${this.formData.title}%`,
        })
      }
      // 状态
      if (this.formData.state[0]) {
        this.expressions.push({
          dataType: 'str',
          name: 'state',
          op: 'like',
          stringValue: `%${this.formData.state[0].id}%`,
        })
      }
      if (this.formData.cUser) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'like',
          stringValue: `%${this.formData.cUser}%`,
        })
      }
    },

    // 树选择节点后获取列表数据
    treeSelectd(key, item) {
      if (item.selectedNodes?.length > 0) {
        let parentId = ''
        let parentName = ''
        if (item.id !== undefined) {
          parentId = item.id
          parentName = item.text
        } else {
          parentId = item.selectedNodes[0].data.props.id
          parentName = item.selectedNodes[0].data.props.text
          this.editnode = item.selectedNodes[0].data.props.edit
        }
        this.typeId = parentId
        this.importTreeId = parentId
        this.typeName = parentName

        this.selectdParentName = parentName
        const filter = [
          {
            dataType: 'str',
            name: 'parentId',
            op: 'eq',
            stringValue: this.typeId,
          },
        ]

        this.expressions = filter
      } else {
        const filter = {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: -1,
        }

        this.expressions = [filter]
        this.editnode = false
      }
    },

    // 获取businessTypeId，选中的节点要是没有businessTypeId就向上找，直至找到根节点，如果没有就返回null
    fnGetBusinessTypeId(item) {
      let businessTypeId
      if (item === null) {
        // 如果找到根节点都没找到flowId就返回null
        businessTypeId = null
      } else {
        if (item.selectedNodes && item.selectedNodes[0].data.props.props.businessTypeId) {
          businessTypeId = item.selectedNodes[0].data.props.props.businessTypeId
        } else if (item.props && item.props.businessTypeId) {
          businessTypeId = item.props.businessTypeId
        } else {
          const key = item.id ? item.id : item.selectedNodes[0].data.key
          const parentNode = this.getParentNode(key, this.$refs.tree.treeData)
          businessTypeId = this.fnGetBusinessTypeId(parentNode)
        }
      }
      return businessTypeId
    },

    // 查找父节点
    getParentNode(key, tree) {
      let parentNode = null
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.children) {
          if (node.children.some((item) => item.id === key)) {
            parentNode = node
          } else if (this.getParentNode(key, node.children)) {
            parentNode = this.getParentNode(key, node.children)
          }
        }
      }
      return parentNode
    },

    // 知识投稿
    fnCreatDoc() {
      var url =
        '/xm-spic-problem-form?' +
        '&typeId=' +
        this.typeId +
        '&typeName=' +
        this.typeName +
        '&orgId=' +
        this.$refs.problemTree.depvalue
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          return this.$refs.oaTable.refresh(true)
        }
      })
    },
    fnEditDoc(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
        this.loadData()
      }, 5000)

      var url = `/km-knowledage-form?&typeId=${this.typeId}&typeName=${this.typeName}&record=${record.id}`

      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          return this.$refs.oaTable.refresh(true)
        }
      })
    },
    // 查看知识
    fnReadDoc(record) {
      setTimeout(() => {
        this.$refs.oaTable.refresh()
        this.loadData()
      }, 5000)
      const curuser = getUserInfo().account
      if (record.creatorAccount === curuser && record.state !== '已发布') {
        window.open(`#/xm-spic-problem-form?id=${record.id}&title=${record.docTitle}`, '_blank')
      } else {
        window.open(
          `#/xm-spic-problem-form?id=${record.id}&title=${record.docTitle}&mode=${'VIEW'}`,
          '_blank'
        )
      }
    },

    // 图片列表页面翻页
    paginationChange(page) {
      this.pagination.current = page
      this.loadData()
    },

    pictureListRefresh(toFirstPage) {
      if (toFirstPage) this.pagination.current = 1
      if (!this.isSelectd) {
        return this.loadData()
      }
    },
    // 列表删除数据时刷新一下
    onRecordsDeleted() {
      this.$refs.tree.refresh() // 刷新树
    },
    // 列表删除数据
    deleteRows() {
      // debugger
      const selectedRowKeys = this.$refs.oaTable.getSelectedRowKeys()
      const curuser = getUserInfo().account
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      if (selectedRowKeys.length === 0) {
        this.$refs.oaTable.clearSelection()
        this.$refs.oaTable.refresh()
      } else {
        return new Promise((resolve) => {
          let flag = true
          const rows = this.$refs.oaTable.getSelectedRows()
          rows.forEach((r) => {
            if (r.creatorAccount) {
              if (r.creatorAccount !== curuser) {
                flag = false
              }
            }
          })

          if (!flag) {
            Modal.error({
              title: '不允许删除非本人创建的数据',
            })
            resolve()
          } else {
            Modal.confirm({
              title: '您确定删除这项内容吗？',
              content: '删除这条数据后，就无法恢复初始的状态。',
              okText: '删除',
              okType: 'danger',
              onOk: () => {
                this.loading = true
                const params = {
                  ids: selectedRowKeys.join(','),
                }

                PageService.delete(params, this.formId).then((res) => {
                  if (res.status === 200) {
                    this.$refs.oaTable.clearSelection()
                    this.$refs.oaTable.refresh()
                    this.loading = false
                    message.success('删除成功')
                  }
                })
              },
              onCancel: () => {
                resolve()
              },
            })
          }
        })
      }

      // 暂存的数据本人可查看/编辑/修改及删除，本单位模块管理员可修改删除
      // const curuser = getUserInfo().account
      // const isTrue = this.isApplicationAdmin // 判断是不是模块管理员
      // if (!isTrue) {
      //   if (selectedRowKeys.length === 0) {
      //     this.$refs.oaTable.clearSelection()
      //     this.$refs.oaTable.refresh()
      //   } else {
      //     return new Promise((resolve) => {
      //       let flag = true
      //       const rows = this.$refs.oaTable.getSelectedRows()
      //       rows.forEach((r) => {
      //         if (r.creatorAccount) {
      //           if (r.creatorAccount !== curuser) {
      //             flag = false
      //           }
      //         }
      //         if (r.state) {
      //           if (r.state === '已发布') {
      //             flag = false
      //           }
      //         }
      //       })

      //       if (!flag) {
      //         Modal.error({
      //           title: '不允许删除非本人创建或已发布的数据',
      //         })
      //         resolve()
      //       } else {
      //         Modal.confirm({
      //           title: '您确定删除这项内容吗？',
      //           content: '删除这条数据后，就无法恢复初始的状态。',
      //           okText: '删除',
      //           okType: 'danger',
      //           onOk: () => {
      //             this.loading = true
      //             const params = {
      //               ids: selectedRowKeys.join(','),
      //             }

      //             PageService.delete(params, this.formId).then((res) => {
      //               if (res.status === 200) {
      //                 this.$refs.oaTable.clearSelection()
      //                 this.$refs.oaTable.refresh()
      //                 this.loading = false
      //                 message.success('删除成功')
      //               }
      //             })
      //           },
      //           onCancel: () => {
      //             resolve()
      //           },
      //         })
      //       }
      //     })
      //   }
      // } else {
      //   // 是管理员
      //   if (selectedRowKeys.length === 0) {
      //     this.$refs.oaTable.clearSelection()
      //     this.$refs.oaTable.refresh()
      //   } else {
      //     return new Promise((resolve) => {
      //       let flag = true
      //       const rows = this.$refs.oaTable.getSelectedRows()
      //       rows.forEach((r) => {
      //         if (r.state) {
      //           if (r.state === '已发布') {
      //             flag = false
      //           }
      //         }
      //       })

      //       if (!flag) {
      //         Modal.error({
      //           title: '不允许删除已发布的数据',
      //         })
      //         resolve()
      //       } else {
      //         Modal.confirm({
      //           title: '您确定删除这项内容吗？',
      //           content: '删除这条数据后，就无法恢复初始的状态。',
      //           okText: '删除',
      //           okType: 'danger',
      //           onOk: () => {
      //             this.loading = true
      //             const params = {
      //               ids: selectedRowKeys.join(','),
      //             }

      //             PageService.delete(params, this.formId).then((res) => {
      //               if (res.status === 200) {
      //                 this.$refs.oaTable.clearSelection()
      //                 this.$refs.oaTable.refresh()
      //                 this.loading = false
      //                 message.success('删除成功')
      //               }
      //             })
      //           },
      //           onCancel: () => {
      //             resolve()
      //           },
      //         })
      //       }
      //     })
      //   }
      // }
      // Modal.confirm({
      //   title: '你确定删除这项内容吗？',
      //   content: '删除这条数据后，就无法恢复初始的状态。',
      //   okText: '删除',
      //   okType: 'danger',
      //   onOk: () => {
      //     this.loading = true
      //     const params = {
      //       ids: selectedRowKeys.join(','),
      //     }

      //     PageService.delete(params, this.formId).then((res) => {
      //       if (res.status === 200) {
      //         this.$refs.oaTable.clearSelection()
      //         this.$refs.oaTable.refresh()
      //         this.loading = false
      //         message.success('删除成功')
      //       }
      //     })
      //   },
      // })
    },
    handleOk() {
      const selectInfo = this.$refs.findTable.getSelectedRows()
      const parentId = this.typeId
      if (selectInfo.length) {
        const arr = []
        selectInfo.forEach((item) => {
          arr.push(item.id)
        })
        this.findConfirmLoading = true
        axios
          .get(`api/xcoa-mobile/v1/spicproblem/find-save?ids=${arr.join(',')}&parentId=${parentId}`)
          .then((res) => {
            if (res.data.code === 200) {
              this.showFindVisible = false
              this.findConfirmLoading = false
              message.success('添加成功!')
              this.$refs.oaTable.refresh()
            }
          })
      } else {
        message.error('请选择审计问题!')
        return false
      }
    },
    onSearchChange(text) {
      if (this.searchText === text) return
      this.searchText = text.trim()
      const pagination = this.pagination
      pagination.current = 1
      this.localPagination = { ...pagination }
      this.loadData()
    },

    // 导出
    exportProblem() {
      // debugger
      const rootId = this.$refs.problemTree.depvalue
      const id = this.typeId
      // let arrId = this.$refs.oaTable.getSelectedRowKeys()
      let arrId = this.$refs.oaTable.getSelectedRowKeys().join(',')
      if (arrId === undefined || arrId.length === 0) {
        arrId = ''
      }
      problemService.exportProblem(id, rootId, arrId).then((res) => {
        if (res.status === 200) {
          const url = URL.createObjectURL(res.data)
          const filename = res.headers['content-disposition']
          const fname = filename.substring(filename.indexOf('filename=') + 9, filename.length)
          download(url, decodeURI(fname))
        } else {
          Modal.warning({
            title: '提示',
            content: '导出报错，请联系管理员!',
          })
          return false
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}

.sider-content {
  padding: 0 0;
  .sider-title {
    position: relative;
    margin-left: 23px;
    i {
      position: absolute;
      top: 3px;
      left: -27px;
      font-size: 18px;
      color: #1890ff;
    }

    font-weight: bold;
  }
  .sider-li {
    :global(.ant-timeline-item-content) {
      margin: 0 0 0 23px;
    }
    :global(.ant-timeline-item-head-blue) {
      color: #9f9f9f;
      border-color: #9f9f9f;
    }
    :global(.ant-timeline-item-tail) {
      height: calc(100% - -18px);
      border-left: 2px solid #f5f5f5;
    }
  }
  .sider-title-div-first {
    padding: 0 0 10px 20px;
    margin-bottom: 10px;
    border-bottom: 3px solid #e8e8e8;
  }
  .sider-title-div {
    padding: 10px 0 10px 20px;
    margin-bottom: 20px;
    border-top: 3px solid #e8e8e8;
    border-bottom: 3px solid #e8e8e8;
  }
  ul {
    margin-bottom: 30px;
    margin-left: 0;
  }
  .sider-ul-div {
    width: 90%;
    padding: 13px 0 0 5px;
    margin: 10px auto;
    cursor: pointer;
    border-radius: 5px;
    :global(.ant-timeline-item) {
      padding: 0;
      margin-left: 3px;
    }
  }
  :global(.checked) {
    color: #fff;
    background: linear-gradient(to right, #13c2c2, #2db7f5);
    :global(.ant-timeline-item-head-blue) {
      background-color: #13c2c2;
      border-color: #fff !important;
    }
  }
  :global(.ant-timeline-item-last .ant-timeline-item-tail) {
    display: none;
  }
}
</style>
