<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-matters-catalog-tree
        ref="auditMattersCatalogTree"
        :key="key"
        show-line
        top-node-text="指引库"
        :is-select-dep="true"
        manager-type="view"
        @treeSelect="treeSelect"
      ></audit-matters-catalog-tree>

      <div :class="$style.rightcard">
        <a-card>
          <!-- 高级搜索组件 -->
          <audit-advanced-query
            :expand="expand"
            :search-data="formData"
            :ref-name="searchform"
            :search-style="{ height: '150px', left: '20px', top: '57px' }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-col :span="12">
                <a-form-model-item label="审计事项名称" prop="auditMattersName">
                  <a-input v-model="formData.auditMattersName" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="审计事项编号" prop="auditMattersCode">
                  <a-input v-model="formData.auditMattersCode" allow-clear />
                </a-form-model-item>
              </a-col>
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            :key="key"
            ref="auditMattersTable"
            :editnode="editnode"
            form-id="iamAuditMatters"
            page-id="audit/matters/iamAuditMatters"
            :columns="columns"
            :actions="actions"
            show-selection
            :show-advance-query="true"
            :filter-expressions="expressions"
            :search-fields="['auditMattersName']"
            @searchbtnClick="searchbtnClick"
          >
            <div slot="islink" slot-scope="text, record">
              <a :title="text" @click="rowClick(record)">{{ text }}</a>
            </div>
          </sd-data-table-ex>
          <audit-matters-export-modal :visible="visible"></audit-matters-export-modal>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal, message } from 'ant-design-vue'
import errorUtil from '@/common/services/error-util'
import download from '@/common/services/download'
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 auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import auditMattersExportModal from './audit-matters-export-modal'
import auditMattersCatalogTree from './audit-matters-catalog-tree'
import auditMattersService from './audit-matters-service'
import components from './_import-components/audit-matters-list-import'
export default {
  name: 'AuditMattersList',
  metaInfo: {
    title: '审计事项列表',
  },
  components: {
    ...components,
    auditMattersCatalogTree,
    auditAdvancedQuery,
    auditMattersExportModal,
  },
  mixins: [auditAdvancedQueryMixins, auditAdvancedGroupMixins],
  data() {
    return {
      editnode: true, // 列表是否可以新建
      key: 0,
      treeData: [],
      searchform: 'searchform',
      formData: {
        auditMattersName: '',
        auditMattersCode: '',
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '审计事项名称',
          dataIndex: 'auditMattersName',
          scopedSlots: { customRender: 'islink' },
          width: '50%',
        },
        {
          title: '审计事项编号',
          dataIndex: 'auditMattersCode',
        },

        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          defaultSortOrder: 'desc',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: 'iamAuditMatters-create', // 纯前端操作，不需要权限控制
          callback: this.createMatters,
        },

        {
          label: '批量导入',
          id: 'importItem',
          permission: 'iamAuditMatters-import',
          callback: this.importItem, // 纯前端操作，不需要权限控制
        },
        {
          label: '导出',
          id: 'exportItem',
          permission: 'iamAuditMatters-export',
          callback: this.exportItem, // 纯前端操作，不需要权限控制
        },
        {
          label: '分类配置',
          id: 'auditMattersCatalog',
          permission: 'iamAuditMatters-catalog',
          callback: () => {
            const url = '/sd-frame/audit-matters-catalog' // 新页面要打开的路由地址
            openAsTrustId(url, null)
          },
        },
        {
          label: '删除',
          id: 'delete',
          permission: 'iamAuditMatters-delete',
          type: TableActionTypes.batch,
          callback: this.deleteRows,
        },
      ],
      expressions: [
        {
          dataType: 'str',
          name: 'catalogId',
          op: 'eq',
          stringValue: 0,
        },
      ],
      catalogId: null,
      catalogName: '',
      auditMattersPath: '',
      visible: false,
    }
  },
  methods: {
    // 选择上级分类后给对应的域赋值
    fnTreePicker(value) {
      if (value.length > 0) {
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogId', value[0].id)
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogName', value[0].name)
      } else {
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogId', '')
        this.$refs.dataTable.getDetailModal().setFieldValue('catalogName', '')
        this.$refs.dataTable.getDetailModal().setFieldValue('auditMattersPath', '')
      }
    },

    treeSelect(selectedKeys, info) {
      this.auditMattersPath = null
      // 父级id
      if (info != null && info.selectedNodes.length > 0) {
        this.parentId = Number(info.selectedNodes[0].data.props.id)
        this.parentName = info.selectedNodes[0].data.props.text // 父级名称
        this.catalogId = Number(info.selectedNodes[0].data.props.id)
        this.catalogName = info.selectedNodes[0].data.props.text // 父级名称
        this.editnode = info.selectedNodes[0].data.props.edit
        if (info.selectedNodes[0].data.props.props) {
          if (info.selectedNodes[0].data.props.props.catalogPath) {
            this.auditMattersPath =
              info.selectedNodes[0].data.props.props.catalogPath + ',' + this.parentId
          } else {
            this.auditMattersPath = this.parentId
          }
        }
      } else {
        if (selectedKeys.id) {
          this.parentId = Number(selectedKeys.id)
          this.parentName = selectedKeys.text // 父级名称
        }
      }
      const orgId = this.$refs.auditMattersCatalogTree.depvalue
      // 判断当前节点是否为根节点
      if (this.catalogId === orgId) {
        this.expressions.forEach((item) => {
          if (item.name === 'catalogId' || item.name === 'orgId') {
            item.name = 'orgId'
            item.stringValue = orgId + ''
          }
        })
      } else {
        this.expressions.forEach((item) => {
          if (item.name === 'catalogId' || item.name === 'orgId') {
            item.name = 'catalogId'
            item.stringValue = this.catalogId
          }
        })
      }
      this.expressions = [...this.expressions]
    },

    handleSearch() {
      this.expressions = []
      // 审计事项名称
      if (this.formData.auditMattersName) {
        this.expressions.push({
          dataType: 'str',
          name: 'auditMattersName',
          op: 'like',
          stringValue: '%' + this.formData.auditMattersName + '%',
        })
      }
      // 审计事项编号
      if (this.formData.auditMattersCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'auditMattersCode',
          op: 'like',
          stringValue: '%' + this.formData.auditMattersCode + '%',
        })
      }

      this.expressions.push({
        dataType: 'str',
        name: 'catalogId',
        op: 'eq',
        stringValue: this.catalogId,
      })

      const orgId = this.$refs.auditMattersCatalogTree.depvalue
      // 判断当前节点是否为根节点
      if (this.catalogId === orgId) {
        this.expressions.forEach((item) => {
          if (item.name === 'catalogId' || item.name === 'orgId') {
            item.name = 'orgId'
            item.stringValue = orgId + ''
          }
        })
      } else {
        this.expressions.forEach((item) => {
          if (item.name === 'catalogId' || item.name === 'orgId') {
            item.name = 'catalogId'
            item.stringValue = this.catalogId
          }
        })
      }
      this.expressions = [...this.expressions]
    },
    // 新建、详情打开新页面
    rowClick(record) {
      const url =
        '/audit-matters-form?record=' +
        record.id +
        '&orgId=' +
        this.$refs.auditMattersCatalogTree.depvalue // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
      // const res = crossWindowWatcher.waitForChanged(url)
    },
    // 部门下拉框选择事件
    depChanged(value, info) {
      this.orgId = this.$refs.auditMattersCatalogTree.depvalue // 选中的值
    },
    // 新建保存回调刷新树
    onRecordSaved() {
      this.key = this.key + 1
    },
    // 删除回调
    onRecordsDeleted() {
      message.success('删除成功')
      this.key = this.key + 1
      this.refresh()
    },
    deleteRows() {
      const ids = this.$refs.auditMattersTable.getSelectedRowKeys()
      if (ids.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }

      return new Promise((resolve) => {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            auditMattersService
              .deleteIamAuditMatters(ids)
              .then(() => {
                message.success('删除成功')
                this.$refs.auditMattersTable.clearSelection()
                this.refresh()
              })
              .catch((err) => {
                const msg = errorUtil.getMessage(err) || '删除失败'
                message.error(msg)
              })
              .finally(resolve)
          },
          onCancel: () => {
            resolve()
          },
        })
      })
    },

    createMatters() {
      const rootId = this.$refs.auditMattersCatalogTree.depvalue
      if (this.catalogId != null && this.catalogId !== rootId) {
        const url =
          '/audit-matters-form?catalogId=' +
          this.catalogId +
          '&catalogName=' +
          this.catalogName +
          '&auditMattersPath=' +
          this.auditMattersPath +
          '&orgId=' +
          this.$refs.auditMattersCatalogTree.depvalue
        // 新页面要打开的路由地址
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.refresh()
          }
        })
      } else {
        if (this.catalogId === rootId) {
          Modal.confirm({
            title: '注意',
            content: '不能在根节点下新建审计事项',
            okText: '确定',
            okType: 'danger',
          })
        } else {
          Modal.confirm({
            title: '请先选择审计事项分类',
            content: '请先选择审计事项分类。',
            okText: '确定',
            okType: 'danger',
          })
        }
      }
    },
    // 导出
    exportItem() {
      const rootId = this.$refs.auditMattersCatalogTree.depvalue
      const id = this.catalogId

      auditMattersService.exportItem(id, rootId).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
        }
      })
    },
    // 导入
    importItem() {
      // 选择事项分类
      this.visible = true
    },
    refresh() {
      this.$refs.auditMattersTable.refresh()
    },
  },
}
</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%;
    }
  }
}
</style>
