<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <audit-tree
        ref="tree"
        :checkable="false"
        :draggable="false"
        :is-search="true"
        :show-line="true"
        :top-node-text="'内部制度库'"
        :treeparams="{
          formId: 'IAM_ORG',
          idColumnId: 'id',
          nameColumnId: 'org_name',
          parentColumnId: 'parent_id',
          otherColumnId: ['org_id', 'creation_time'],
          configId: '11',
          type: 'SJ',
        }"
        :default-expanded-keys="['0']"
        :is-select-dep="false"
        manager-type="view"
        @treeSelect="treeSelect"
      >
      </audit-tree>
      <div :class="$style.rightcard">
        <a-card>
          <audit-advanced-query
            :expand="expand"
            :search-data="formData"
            :ref-name="searchform"
            :search-style="{ height: '245px', left: '20px', top: '10%' }"
            :search-fun="handleSearch"
            @searchedClick="searchedClick"
          >
            <template>
              <a-col :span="12">
                <a-form-model-item :label="'标\u2002\u2002\u2002\u2002题'" prop="docTitle">
                  <a-input v-model="formData.docTitle" allow-clear />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="12">
                <a-form-model-item :label="'发布单位'" prop="publishUnit">
                  <a-input v-model="formData.publishUnit" allow-clear />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="12">
                <a-form-model-item :label="'制度所属单位'" prop="createUnitNameImp">
                  <a-input v-model="formData.createUnitNameImp" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="'发文字号'" prop="dispatchWord">
                  <a-input v-model="formData.dispatchWord" allow-clear />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="'发布日期'" prop="publishTime">
                  <a-range-picker v-model="formData.publishTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="'时\u2002效\u2002性'" prop="period">
                  <sd-select v-model="formData.period" :allow-clear="true" :options="period" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item :label="'实施日期'" prop="implementTime">
                  <a-range-picker v-model="formData.implementTime" style="width: 100%" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="12">
                <a-form-model-item :label="'标\u2002\u2002\u2002\u2002签'" prop="label">
                  <a-input v-model="formData.label" allow-clear />
                </a-form-model-item>
              </a-col> -->
            </template>
          </audit-advanced-query>
          <sd-data-table-ex
            ref="list"
            :editnode="editnode"
            :projectlist="true"
            form-id="iamInstitution"
            page-id="core/institution/iamInstitution"
            :columns="columns"
            :actions="actions"
            show-selection
            :process-req="processReq"
            :search-fields="['docTitle', 'createUnitNameImp', 'dispatchWord']"
            :filter-expressions="filterExpressions"
            :show-advance-query="true"
            @searchbtnClick="searchbtnClick"
          >
            <div slot="islink" slot-scope="text, record">
              <a :title="text" @click="rowClick(record)">{{ text }}</a>
            </div>
          </sd-data-table-ex>
          <div :class="[$style.btns]">
            <audit-advanced-import
              ref="import"
              :config-id="'81'"
              :table-id="'list'"
              :relevant-column="parentId"
              :class-style="[$style.buttonSpacing]"
              :v-if="false"
              @importfromfileAfter="after"
            >
            </audit-advanced-import>
          </div>
          <div :class="[$style.btns]">
            <audit-advanced-import
              ref="zipimport"
              :config-id="'82'"
              :table-id="'list'"
              :relevant-column="parentId"
              :class-style="[$style.buttonSpacing]"
              :v-if="false"
              @importfromfileAfter="after"
            >
            </audit-advanced-import>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import auditAdvancedQueryMixins from '../../components/audit-advanced-query-mixins'
import auditAdvancedQuery from '../../components/audit-advanced-query.vue'
import auditTree from '../../components/audit-tree.vue'
import auditAdvancedImport from '../../components/audit-advanced-import.vue'
import auditTreeService from '../../components/audit-tree-service'
import components from './_import-components/iam-audit-auditsource-institution-list-import'
import { getUserInfo } from '@/common/store-mixin'
import axios from '@/common/services/axios-instance'
import openAsTrustId from '@/common/services/open-as-trust-id'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
const columns = [
  {
    title: '序号',
    dataIndex: 'sortNumber',
    width: '80px',
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    dataIndex: 'id',
    sdHidden: true,
  },
  {
    dataIndex: 'parentId',
    sdHidden: true,
  },
  {
    title: '标题',
    dataIndex: 'docTitle',
    // sdClickable: true, // 列内容是否可点击
    scopedSlots: { customRender: 'islink' },
    width: '550px',
  },
  {
    title: '发布单位',
    dataIndex: 'publishUnit',
    width: '200px',
  },
  {
    title: '制度所属单位',
    dataIndex: 'createUnitNameImp',
    width: '200px',
  },
  {
    title: '发文字号',
    dataIndex: 'dispatchWord',
    width: '200px',
    sdHidden: true,
  },
  {
    title: '发布日期',
    dataIndex: 'publishTime',
    sdRender: TableColumnTypes.date,
    sorter: true,
    defaultSortOrder: 'desc',
    width: '120px',
  },
  {
    title: '实施日期',
    dataIndex: 'implementTime',
    sdRender: TableColumnTypes.date,
    width: '120px',
  },
  {
    title: '时效性',
    dataIndex: 'period',
    width: '120px',
  },
  {
    title: '创建时间',
    dataIndex: 'creationTime',
    sdHidden: true,
    width: '150px',
  },
  {
    title: '状态',
    dataIndex: 'whether',
    width: '120px',
  },
]
export default {
  name: 'IamAuditAuditsourceInstitutionList',
  metaInfo: {
    title: '内部制度',
  },
  components: {
    ...components,
    auditTree,
    auditAdvancedQuery,
    auditAdvancedImport,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      currentUser: '',
      // 有编辑权限
      edit: '',
      //
      editnode: true,
      // 列表展示用
      columns,
      // 导入用
      groupid: '',
      visible: false,
      title: '内部制度导入',
      editNodes: [], // 分级授权授予的编辑节点
      viewNodes: [], // 分级授权授予的查看节点
      // 左侧树用，用于创建对应分类数据
      parentId: 0,
      categorys: [],
      // 是否是根节点
      isRoot: true,
      req: true,
      // 高级搜索用
      expand: false,
      searchform: 'searchform',
      formData: {
        docTitle: '',
        // publishUnit: '',
        createUnitNameImp: '',
        dispatchWord: '',
        publishTime: null,
        period: null,
        label: null,
        // devoteLevel: null,
        implementTime: null,
      },
      period: [],
      devoteLevel: [],
      // 列表数据过滤公式
      filterExpressions: [
        {
          dataType: 'long',
          name: 'parentId',
          op: 'eq',
          longValue: -1,
        },
      ],
      // 按钮
      actions: [
        {
          label: '新建',
          id: 'new',
          // type: TableActionTypes.ex.create,
          permission: 'create',
          type: TableActionTypes.primary,
          callback: () => {
            this.createNew()
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.ex.delete, // 删除按钮，不需要回调，会自动处理（对sd-data-table无效）
        },
        // {
        //   label: '批量导入',
        //   id: 'importManyExcel', // 按钮id
        //   permission: 'create', // 有创建的权限才能导入
        //   // type: TableActionTypes.primary,
        //   callback: () => {
        //     this.$refs.import.showImportPanel()
        //   },
        // },
        // {
        //   label: '导入',
        //   id: 'importExcel', // 按钮id
        //   permission: 'create', // 有创建的权限才能导入
        //   // type: TableActionTypes.primary,
        //   callback: () => {
        //     this.$refs.zipimport.showImportPanel()
        //     this.flush()
        //   },
        // },

        // {
        //   label: '分类配置',
        //   id: 'categoryConfig', // 按钮id
        //   permission: 'create', // 有创建的权限才能导入
        //   // type: TableActionTypes.primary,
        //   callback: () => {
        //     this.categoryConfig()
        //   },
        // },
        // {
        //   label: '全量同步',
        //   id: 'dataImpAll', // 按钮id
        //   permission: 'create', // 有创建的权限才能导入
        //   // type: TableActionTypes.primary,
        //   callback: () => {
        //     this.dataImpAll(0, 1)
        //     this.flush()
        //   },
        // },
        // {
        //   label: '增量同步',
        //   id: 'dataImpByDay', // 按钮id
        //   permission: 'create', // 有创建的权限才能导入
        //   // type: TableActionTypes.primary,
        //   callback: () => {
        //     this.dataImpAll(1, 1)
        //     this.flush()
        //   },
        // },
      ],
    }
  },
  created() {
    // 查找当前用户角色，如果不是管理员，则不显示根节点新建按钮
    this.checkRootNodeEdit()
    // 获取当前用户分级授权的维护节点和查看节点
    const formId = 'iamInstitution'
    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)
      })
    })
  },
  mounted() {
    axios({
      url: 'api/xcoa-mobile/v1/iameditpermission/editPerm?formId=iamInstitution',
      method: 'get',
    }).then((res) => {
      this.edit = res.data
    })
    this.currentUser = getUserInfo().account
  },
  methods: {
    flush() {
      return this.$refs.list?.refresh(true)
    },
    // 导入页面点击取消
    handleCancel() {
      this.visible = false
    },
    // 新建、详情打开新页面
    rowClick(record) {
      const url = '/iam-audit-auditsource-institution-form?record=' + record.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.flush()
        }
      })
      // const res = crossWindowWatcher.waitForChanged(url)
    },
    treeSelect(selectedKeys, info) {
      debugger
      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

      // 不是根节点，就添加parentId过滤条件
      this.filterExpressions = []
      if (!this.nodeIsRoot) {
        this.filterExpressions.push({
          dataType: 'str',
          name: 'parentId',
          op: 'eq',
          stringValue: 0,
        })
      } else {
        this.filterExpressions = []
      }
      this.filterExpressions.forEach((item) => {
        if (item.name === 'parentId') {
          item.stringValue = Number(info.selectedNodes[0].data.props.id)
        }
      })

      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
        }
      }

      // if (info.selectedNodes && info.selectedNodes.length > 0) {
      //   this.filterExpressions[0].longValue = info.selectedNodes[0].data.props.id
      //   this.parentId = info.selectedNodes[0].data.props.id
      //   this.editnode = info.selectedNodes[0] ? info.selectedNodes[0].data.props.edit : false
      // } else {
      //   this.editnode = false
      //   this.filterExpressions[0].longValue = -1
      // }
      // const props = info.selectedNodes[0].data.props.props
      // if (props) {
      //   const flag = props.isroot
      //   if (flag !== undefined && flag === true) {
      //     this.isRoot = flag
      //   } else {
      //     this.isRoot = false
      //   }
      // }
      // if (this.isRoot === true) {
      //   axios({
      //     url:
      //       'api/xcoa-mobile/v1/iam-institution-category/rootCateId?orgId=' +
      //       info.selectedNodes[0].data.props.id,
      //     method: 'get',
      //   })
      // }
      // this.filterExpressions = []
      // if (this.isRoot === true) {
      //   // 发送请求
      //   axios({
      //     url:
      //       'api/xcoa-mobile/v1/iam-institution-category/getAllNode?nodeId=' +
      //       info.selectedNodes[0].data.props.id,
      //     method: 'get',
      //   }).then((res) => {
      //     if (res) {
      //       this.filterExpressions.push({
      //         dataType: 'long',
      //         name: 'parentId',
      //         op: 'in',
      //         longValues: res.data,
      //       })
      //     }
      //   })
      // } else {
      //   this.filterExpressions.push({
      //     dataType: 'long',
      //     name: 'parentId',
      //     op: 'eq',
      //     longValue: this.parentId,
      //   })
      // }
    },
    // 检查根节点属性
    checkRootNodeEdit() {
      const adminRole = getUserInfo().roles.find((item) => {
        return item.code === 'ADMINISTRATOR'
      })
      if (!adminRole) {
        this.editnode = false
      } else {
        this.editnode = true
      }
    },
    // 高级搜索
    seniorSearch() {
      this.expand = !this.expand
      if (this.expand === true) {
        // 如果是展示的，那么可能去获取字典值去
        if (!this.strOrArr(this.formData.period)) {
          // 获取时效性的字典值 'PERIOD'
          if (!this.strOrArr(this.period)) {
            axios({
              url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PERIOD',
              method: 'get',
            }).then((res) => {
              if (res.status === 200) {
                this.period = res.data
              }
            })
          }
        }
        // if (!this.strOrArr(this.formData.devoteLevel)) {
        //   // 获取效力级别的字典值 'DEVOTE_LEVEL'
        //   if (!this.strOrArr(this.devoteLevel)) {
        //     axios({
        //       url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=DEVOTE_LEVEL',
        //       method: 'get',
        //     }).then((res) => {
        //       if (res.status === 200) {
        //         this.devoteLevel = res.data
        //       }
        //     })
        //   }
        // }
      }
    },
    handleSearch() {
      debugger
      const formData = this.formData
      // 修改表格过滤条件进行，再刷新进行数据过滤
      // 获取当前节点parentId过滤条件
      // const parentIdExpression = this.filterExpressions.find((item) => item.name === 'parentId')
      // 获取当前表格过滤条件
      // this.filterExpressions = []
      // this.filterExpressions.push(parentIdExpression)

      if (!this.nodeIsRoot) {
        const parentIdExpression = this.filterExpressions.find((item) => item.name === 'parentId')
        // 获取当前表格过滤条件
        this.filterExpressions = []
        this.filterExpressions.push(parentIdExpression)
      } else {
        this.filterExpressions = []
      }
      // 获取高级搜索的数据
      // 开始修改
      if (formData !== null) {
        // 标题
        if (this.strOrArr(formData.docTitle)) {
          this.filterExpressions.push({
            dataType: 'str',
            name: 'docTitle',
            op: 'like',
            stringValue: formData.docTitle,
          })
        }
        // 发布单位
        // if (this.strOrArr(formData.publishUnit)) {
        //   this.filterExpressions.push({
        //     dataType: 'str',
        //     name: 'publishUnit',
        //     op: 'like',
        //     stringValue: formData.publishUnit,
        //   })
        // }
        // 制度所属单位
        if (this.strOrArr(formData.createUnitNameImp)) {
          this.filterExpressions.push({
            dataType: 'str',
            name: 'createUnitNameImp',
            op: 'like',
            stringValue: formData.createUnitNameImp,
          })
        }
        // 发文字号
        if (this.strOrArr(formData.dispatchWord)) {
          this.filterExpressions.push({
            dataType: 'str',
            name: 'dispatchWord',
            op: 'like',
            stringValue: formData.dispatchWord,
          })
        }
        // 发布日期
        if (this.strOrArr(formData.publishTime)) {
          if (formData.publishTime[0] === null) {
            formData.publishTime = null
          } else {
            this.filterExpressions.push({
              dataType: 'long',
              name: 'publishTime',
              op: 'ge',
              longValue: new Date(
                formData.publishTime[0].format('YYYY-MM-DD') + ' 00:00:00'
              ).valueOf(),
            })
            this.filterExpressions.push({
              dataType: 'long',
              name: 'publishTime',
              op: 'le',
              longValue: new Date(
                formData.publishTime[1].format('YYYY-MM-DD') + ' 23:59:59'
              ).valueOf(),
            })
          }
        }
        // 时效性
        if (this.strOrArr(formData.period)) {
          if (formData.period[0] === null) {
            formData.period = null
          } else {
            this.filterExpressions.push({
              dataType: 'str',
              name: 'period',
              op: 'eq',
              stringValue: formData.period[0].id,
            })
          }
        }
        // 效力级别
        // if (this.strOrArr(formData.devoteLevel)) {
        //   if (formData.devoteLevel[0] === null) {
        //     formData.devoteLevel = null
        //   } else {
        //     this.filterExpressions.push({
        //       dataType: 'str',
        //       name: 'devoteLevel',
        //       op: 'eq',
        //       stringValue: formData.devoteLevel[0].id,
        //     })
        //   }
        // }
        if (this.strOrArr(formData.label)) {
          this.filterExpressions.push({
            dataType: 'str',
            name: 'label',
            op: 'like',
            stringValue: formData.label,
          })
        }
        // 实施日期
        if (this.strOrArr(formData.implementTime)) {
          if (formData.implementTime[0] === null) {
            formData.implementTime = null
          } else {
            this.filterExpressions.push({
              dataType: 'long',
              name: 'implementTime',
              op: 'ge',
              longValue: new Date(
                formData.implementTime[0].format('YYYY-MM-DD') + ' 00:00:00'
              ).valueOf(),
            })
            this.filterExpressions.push({
              dataType: 'long',
              name: 'implementTime',
              op: 'le',
              longValue: new Date(
                formData.implementTime[1].format('YYYY-MM-DD') + ' 23:59:59'
              ).valueOf(),
            })
          }
        }
      }
    },
    searchbtnClick() {
      this.expand = !this.expand
      if (this.expand === true) {
        // 如果是展示的，那么可能去获取字典值去
        if (!this.strOrArr(this.formData.period)) {
          // 获取时效性的字典值 'PERIOD'
          if (!this.strOrArr(this.period)) {
            axios({
              url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=PERIOD',
              method: 'get',
            }).then((res) => {
              if (res.status === 200) {
                this.period = res.data
              }
            })
          }
        }
      }
    },
    // 判断数组或字符串为null或长度为0
    strOrArr(strOrArr) {
      return strOrArr !== null && strOrArr.length > 0
    },
    createNew() {
      if (this.parentId === 0) {
        Modal.warning({
          title: '提示',
          content: '请选择分类!',
        })
        return
      }

      const url = '/iam-audit-auditsource-institution-form?parentId=' + this.parentId // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.flush()
        }
      })
    },
    categoryConfig() {
      const url = '/sd-frame/iam-audit-auditsource-institutioncategory-form' // 新页面要打开的路由地址
      openAsTrustId(url, null)
    },
    processReq(req) {
      debugger
      const url = req.url
      const arr = req.data.expressions
      if (url === 'api/xcoa-mobile/v1/iam-page/businessList') {
        if (this.edit === false) {
          arr.push({
            dataType: 'str',
            name: 'whether',
            op: 'eq',
            stringValue: '0',
          })
        }
      }
      if (this.edit === true) {
        const seaArr = { dataType: 'exps', op: 'or', expressionsValue: [] }
        seaArr.expressionsValue.push({
          dataType: 'str',
          name: 'whether',
          op: 'eq',
          stringValue: '0',
        })
        seaArr.expressionsValue.push({
          dataType: 'str',
          name: 'creatorAccount',
          op: 'eq',
          stringValue: this.currentUser,
        })
        arr.push(seaArr)
      }
      req.data.expressions = arr
      return req
    },
    after() {
      this.$refs.tree.refreshNode(this.parentId)
    },
    dataImpAll(IsAll, number) {
      axios({
        url:
          'api/xcoa-mobile/v1/iam-institution-category/impCategoryInfo?IsAll=' +
          IsAll +
          '&number=' +
          number,
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          var aa = res.data
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.btns {
  position: absolute;
  top: 24px;
  right: 490px;
  z-index: 100;
}
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      right: 10%;
      // overflow: hidden;
      flex: 1;
      width: 80%;
      // width: calc(200% - 20%);
      height: 100%;
      :global(.ant-table) {
        // overflow: scroll;
      }
      :global(.anticon-setting) {
        display: none;
      }
    }
  }
}
</style>
