<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-tree
        :key="refreshKey"
        ref="orgTree"
        :checkable="false"
        :draggable="true"
        :is-search="true"
        :show-line="true"
        :top-node-text="topNodeText"
        :treeparams="{
          formId: 'IAM_ORG',
          idColumnId: 'id',
          nameColumnId: 'org_name',
          parentColumnId: 'parent_id',
          otherColumnId: ['org_id', 'creation_time'],
          configId: '11',
          type: this.type,
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="false"
        manager-type="view"
        @treeSelect="treeSelect"
      ></audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <div :class="[$style.btns]">
            <audit-advanced-export
              ref="orgexport"
              :class-style="[$style.buttonSpacing]"
              :expressions="SJJGKTableExpressions"
              :exclebxh="true"
              table-id="iamOrgTable"
              :config-id="1"
              :v-if="false"
            />
          </div>
          <sd-oa-table
            :key="refreshKey"
            ref="iamOrgTable"
            :editnode="editnode"
            :form-id="formId"
            page-id="core/org/iamOrg"
            :filter-expressions="SJJGKTableExpressions"
            :columns="columns"
            :actions="actions"
            show-selection
            :search-fields="['orgName', 'address', 'maintainPerson']"
            :show-advance-query="true"
            :custom-delete-fun="deleteFun"
            @searchbtnClick="searchbtnClick"
            @recordsDeleted="onRecordsDeleted"
          >
            <div slot="islink" slot-scope="text, record">
              <a :title="text" @click="rowClick(record)">{{ text }}</a>
            </div>
          </sd-oa-table>
          <audit-advanced-query
            :expand="expand"
            :search-data="SJJGKFormData"
            :ref-name="searchform"
            :search-style="{ height: '125px', left: '20px', top: '60px' }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-col :span="12">
                <a-form-model-item :label="'机构名称'" prop="orgName">
                  <a-input v-model="SJJGKFormData.orgName" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="'机构编号'" prop="orgId">
                  <a-input v-model="SJJGKFormData.orgId" allow-clear />
                </a-form-model-item>
              </a-col>
            </template>
          </audit-advanced-query>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { message, Modal } from 'ant-design-vue'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditTree from '../../components/audit-tree.vue'
import auditAdvancedExport from '../../components/audit-advanced-export.vue'
import auditTreeService from '../../components/audit-tree-service'
import components from './_import-components/iam-audit-auditsource-org-list-import'
import errorUtil from '@/common/services/error-util'
import { getUserInfo } from '@/common/store-mixin'
import TableColumnTypes from '@/common/services/table-column-types'
import TableActionTypes from '@/common/services/table-action-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import axios from '@/common/services/axios-instance'
const columns = [
  {
    title: '序号',
    dataIndex: 'sortNumber',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  {
    dataIndex: 'parentId',
    sdHidden: true,
  },
  {
    title: '机构名称',
    dataIndex: 'orgName',
    // sdClickable: true, // 列内容是否可点击
    scopedSlots: { customRender: 'islink' },
    width: '20%',
  },
  {
    title: '机构编号',
    dataIndex: 'orgId',
  },
  {
    title: '编制人数',
    dataIndex: 'personNumber',
  },
  {
    title: '实有人数',
    dataIndex: 'realNumber',
  },
  {
    title: '地址',
    dataIndex: 'address',
  },
  {
    title: '是否设立总审计师',
    dataIndex: 'whetherEstablishAuditor',
    sdHidden: true,
  },
  {
    title: '是否设立审计中心',
    dataIndex: 'whetherEstablishAuditCenter',
    sdHidden: true,
  },
  {
    title: '维护人员',
    dataIndex: 'maintainPerson',
  },
  {
    title: '维护日期',
    dataIndex: 'maintainTime',
    sdRender: TableColumnTypes.date,
    // sorter: true,
    // defaultSortOrder: 'descend',
  },
  {
    title: '排序号',
    dataIndex: 'reservelong1',
    sdHidden: true,
    sorter: false,
    defaultSortOrder: 'asc',
    width: '80px',
  },
]
export default {
  name: 'IamAuditAuditsourceOrgList',
  metaInfo: {
    title: '审计机构库',
  },

  components: {
    ...components,
    auditAdvancedQuery,
    auditTree,
    auditAdvancedExport,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      type: 'SJ',
      editnode: true,
      editNodes: [], // 分级授权授予的编辑节点
      viewNodes: [], // 分级授权授予的查看节点
      childNodes: [], // 分级授权授予的编辑节点(字节点)
      formIdType: '',
      columns,
      searchform: 'searchform',
      formId: 'iamOrg',
      nodeIsRoot: true, // 当前选中的树节点是否为根节点
      SJJGKFormData: {
        orgName: '',
        orgId: '',
      },
      refreshKey: 0,
      parentId: ['0'],
      // 列表默认使用的
      SJJGKTableExpressions: [
        // {
        //   dataType: 'str',
        //   name: 'parentId',
        //   op: 'eq',
        //   stringValue: 0,
        // },
        {
          dataType: 'str',
          name: 'orgLibraryCategory',
          op: 'eq',
          stringValue: this.$route.query.type ? this.$route.query.type : 'SJ',
        },
      ],
      // 树控件列表加载使用这个
      SJJGKSelectTableExpressions: [
        {
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: 0,
        },
        {
          dataType: 'str',
          name: 'orgLibraryCategory',
          op: 'eq',
          stringValue: this.$route.query.type ? this.$route.query.type : 'SJ',
        },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          // type: TableActionTypes.ex.create,
          permission: 'create',
          type: TableActionTypes.primary,
          callback: () => {
            var parentId = this.parentId
            const url =
              '/iam-audit-auditsource-org-form?parentId=' + parentId + '&type=' + this.type // 新页面要打开的路由地址
            crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
              if (refreshFlag) {
                // 这里写或者调刷新的方法
                this.refresh()
              }
            })
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
          permission: null,
        },
        {
          label: '导出',
          permission: null, // 纯前端操作，不需要权限控制
          callback: this.export,
        },
      ],
    }
  },
  computed: {
    topNodeText() {
      let title = '机构库'
      switch (this.type) {
        case 'SJ':
          title = '审计机构库'
          break
        case 'FK':
          title = '风控机构库'
          break
        default:
          break
      }
      return title
    },
  },
  created() {
    if (this.$route.query.type !== undefined) {
      this.type = this.$route.query.type
    }
    // 查找当前用户角色，如果不是管理员，则不显示根节点新建按钮
    this.checkRootNodeEdit()

    // 获取当前用户分级授权的维护节点和查看节点
    let formId = 'iamOrg'
    if (this.type === 'FK') {
      formId = 'iamOrg2'
    }
    const that = this

    auditTreeService.getManagedHierarchyOrg(formId).then((res) => {
      res.data.editNodes.forEach((item) => {
        that.editNodes.push(item.id)
      })
      res.data.viewNodes.forEach((item) => {
        that.viewNodes.push(item.id)
      })
    })

    this.formIdType = formId
    this.getChildPermissionOrg(formId)
  },
  methods: {
    getChildPermissionOrg(formId) {
      auditTreeService.getChildPermissionOrg(formId).then((res) => {
        res.data.forEach((item) => {
          this.childNodes.push(item)
        })
      })
    },
    deleteFun() {
      const selectedRowKeys = this.$refs.iamOrgTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      return new Promise((resolve) => {
        // 判断所选机构下是否维护了审计人员，返回false代表机构下有人员，true就没有
        axios({
          url: `api/xcoa-mobile/v1/iamorg/validate?ids=${selectedRowKeys}`,
          method: 'get',
        })
          .then((res) => {
            if (!res.data) {
              Modal.warning({
                title:
                  '您所选择的机构下维护了审计人员，请先删除对应机构的审计人员之后，再进行机构的删除操作。',
              })
            } else {
              // 删除机构
              Modal.confirm({
                title: '您确定删除这项内容吗？',
                content: '删除这条数据后，该机构的下级机构也会删除，就无法恢复初始的状态。',
                okText: '删除',
                okType: 'danger',
                onOk: () => {
                  axios({
                    url: `api/xcoa-mobile/v1/iamorg/deleteModule`,
                    method: 'delete',
                    params: {
                      ids: selectedRowKeys.join(','),
                    },
                  })
                    .then(() => {
                      this.clearSelection()
                      this.refresh()
                      message.success('删除成功')
                      /**
                       * 数据删除成功后触发
                       * @property {Array} rowKeys 已删除的记录ids
                       */
                      this.$emit('recordsDeleted', selectedRowKeys)
                    })
                    .catch((err) => {
                      const msg = errorUtil.getMessage(err) || '删除失败'
                      message.error(msg)
                    })
                    .finally(resolve)
                },
                onCancel: () => {
                  resolve()
                },
              })
            }
          })
          .catch((err) => {
            const msg = errorUtil.getMessage(err) || '出错了，请联系管理员'
            message.error(msg)
          })
          .finally(resolve)
      })
    },
    clearSelection() {
      this.$refs.iamOrgTable.clearSelection()
    },
    export() {
      const selectedRowKeys = this.$refs.iamOrgTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        this.$refs.orgexport.exportdata1()
      } else {
        // const ids = selectedRowKeys.join(',')
        this.$refs.orgexport.exportdata()
      }
      // this.$refs.orgexport.exportdata()
    },
    // 检查根节点属性
    checkRootNodeEdit() {
      const adminRole = getUserInfo().roles.find((item) => {
        return item.code === 'ADMINISTRATOR'
      })
      if (!adminRole) {
        this.editnode = false
      } else {
        this.editnode = true
      }
    },
    // 点击树
    treeSelect(selectedKeys, info) {
      this.nodeIsRoot = info.selectedNodes[0].data.props.props.isroot // 是否为根节点
      this.parentId = info.selectedNodes[0].data.props.id // 父级id
      this.parentName = info.selectedNodes[0].data.props.text // 父级名称
      this.selectedKeys = selectedKeys
      this.SJJGKSelectTableExpressions.forEach((item) => {
        if (item.name === 'parentId') {
          item.stringValue = Number(info.selectedNodes[0].data.props.id)
        }
      })
      // 不是根节点，就添加parentId过滤条件
      if (!this.nodeIsRoot) {
        this.SJJGKTableExpressions = [...this.SJJGKSelectTableExpressions]
      } else {
        this.SJJGKTableExpressions = []
        var orgLibraryCategoryItem = {
          dataType: 'str',
          name: 'orgLibraryCategory',
          op: 'eq',
          stringValue: this.type,
        }
        this.SJJGKTableExpressions.push(orgLibraryCategoryItem)
      }

      this.selectedKeys = selectedKeys
      this.parentId = Number(info.selectedNodes[0].data.props.id)
      // 如果点击的是根节点，则检查权限
      if (info.selectedNodes[0].data.props.props.isroot) {
        this.checkRootNodeEdit()
      } else {
        // this.editnode = info.selectedNodes[0].data.props.edit
        // 为所有审计人员开放查看权限，但需要对每个节点都检查权限
        const selectId = info.selectedNodes[0].data.props.id
        if (this.editNodes && this.editNodes.includes(selectId)) {
          this.editnode = true
        } else {
          this.editnode = false
        }
      }
    },
    rowClick(record) {
      // let selectKeys = this.selectedKeys
      // if (!selectKeys || selectKeys === '0') {
      //   selectKeys = 1
      // }
      debugger
      if (
        this.viewNodes &&
        (this.viewNodes.includes(Number(record.id)) || this.childNodes.includes(Number(record.id)))
      ) {
        if (
          this.editNodes.includes(Number(record.id)) ||
          this.childNodes.includes(Number(record.id))
        ) {
          const url = '/iam-audit-auditsource-org-form?record=' + record.id + '&type=' + this.type // 新页面要打开的路由地址
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              this.refresh()
            }
          })
        } else {
          const url =
            '/iam-audit-auditsource-org-form?record=' +
            record.id +
            '&mode=' +
            'VIEW' +
            '&type=' +
            this.type
          crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
            if (refreshFlag) {
              this.refresh()
            }
          })
        }
      } else {
        Modal.warning({
          title: '提示',
          content: '你没有权限打开该页面!',
        })
      }
      // const url = '/iam-audit-auditsource-org-form?record=' + record.id // 新页面要打开的路由地址
      // crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
      //   if (refreshFlag) {
      //     this.refresh()
      //   }
      // })
    },

    refresh(toFirstPage) {
      // this.refreshKey = this.refreshKey + 1
      this.$refs.iamOrgTable.refresh(toFirstPage)
      this.$refs.orgTree.refreshNode(this.parentId)
      this.getChildPermissionOrg(this.formIdType)
      // 重新获取有权限的节点信息
      let formId = 'iamOrg'
      if (this.type === 'FK') {
        formId = 'iamOrg2'
      }
      this.editNodes = []
      this.viewNodes = []
      auditTreeService.getManagedHierarchyOrg(formId).then((res) => {
        res.data.editNodes.forEach((item) => {
          this.editNodes.push(item.id)
        })
        res.data.viewNodes.forEach((item) => {
          this.viewNodes.push(item.id)
        })
      })
    },
    // 删除监听
    onRecordsDeleted() {
      this.$refs.orgTree.refreshNode(this.parentId)
    },
    handleSearch() {
      if (!this.nodeIsRoot) {
        this.SJJGKTableExpressions = [
          {
            dataType: 'str',
            name: 'parentId',
            op: 'eq',
            stringValue: this.parentId,
          },
        ]
      } else {
        this.SJJGKTableExpressions = []
        var orgLibraryCategoryItem = {
          dataType: 'str',
          name: 'orgLibraryCategory',
          op: 'eq',
          stringValue: this.type,
        }
        this.SJJGKTableExpressions.push(orgLibraryCategoryItem)
      }

      // 项目名称
      if (this.SJJGKFormData.orgName) {
        this.SJJGKTableExpressions.push({
          dataType: 'str',
          name: 'orgName',
          op: 'like',
          stringValue: `%${this.SJJGKFormData.orgName}%`,
        })
      }
      // 项目编号
      if (this.SJJGKFormData.orgId) {
        this.SJJGKTableExpressions.push({
          dataType: 'str',
          name: 'orgId',
          op: 'like',
          stringValue: `%${this.SJJGKFormData.orgId}%`,
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.btns {
  position: absolute;
  top: 24px;
  right: 99.5px;
  z-index: 100;
}
.buttonSpacing {
  margin-left: 5px;
}
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
</style>
