<template>
  <a-card :bordered="false" title="证书档案" :loading="treeLoading">
    <div class="table-page-search-wrapper">
      <SearchCom :form="queryParam" :list="queryOptions" @search="handleRefresh" @reset="() => {queryParam.type = '', handleRefresh()}"></SearchCom>
      <div style="width: 100%; height: 32px; margin-bottom: 8px;">
        <a-button type="primary" @click="editCertificateType()">编辑证书类型</a-button>
      </div>
    </div>

    <a-row :gutter="24">
      <a-col :md="5" :sm="24" class="borderTop ">
        <div>
          <div v-if="this.orgTree != ''">
            <a-tree :treeData="orgTree" v-if="orgTree.length" @select="handleClick" :defaultExpandAll="true" :defaultExpandedKeys="defaultExpandedKeys" :replaceFields="replaceFields" />
          </div>
          <div v-else>
            <a-empty :image="simpleImage" />
          </div>

          <a-button type="primary" @click="changeOrgType" style="display: block; margin: 10px auto;">
            {{ queryParam.orgType === 1 ? '切换到项目组' : '切换到单位' }}
          </a-button>
        </div>
      </a-col>
      <a-col :md="19" :sm="24" style="padding-left: 0px">
        <s-table ref="table" size="small" rowKey="id" :columns="columns" :data="loadData">
          <template slot="action" slot-scope="text, record">
            <a-dropdown>
              <a class="ant-dropdown-link">操作
                <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-if="hasPerm('person:certificate:edit')">
                  <a href="javascript:;" @click="editPersonCertificate(record)">修改</a>
                </a-menu-item>
                <a-menu-item v-if="hasPerm('person:certificate:export')">
                  <a href="javascript:;" @click="exportPersonCertificate(record)">导出</a>
                </a-menu-item>
                <a-menu-item v-if="hasPerm('person:certificate:del')">
                  <a-popconfirm placement="topRight" title="确认删除？" @confirm="() => delPersonCertificate(record)">
                    <a href="javascript:;">删除</a>
                  </a-popconfirm>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </s-table>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { STable, SearchCom } from '@/components'
import { getArchivesCertificatelist, delCertificate, exportCertificate } from '@/api/archives/certificate'
import { downloadExportFile } from '@/api/common/common'
import { dictionaryDropDown } from '@/api/sys/dictionaryItem'
import { orgList } from '@/api/org/org'
import { listToTree } from '@/utils/util'

export default {
  // import引入的组件需要注入到对象中才能使用
  components: { STable, SearchCom },
  props: {},
  data() {
    // 这里存放数据
    return {
      queryParam: { orgId: '', orgType: 1, type: '' },
      queryOptions: [
        { type: 'select-dic', placeholder: '证书类型', key: 'type', options: [] }
      ],
      state: [], // 证书状态字典

      // 组织机构数需要用到的参数
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      orgTree: [],
      defaultExpandedKeys: [],
      treeLoading: true,
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id'
      },

      // 表格参数
      columns: [
        { title: '姓名', width: '80px', align: 'center', dataIndex: 'personName', key: 'personName' },
        { title: '单位信息', width: 'auto', align: 'center', dataIndex: 'dwOrgName', key: 'dwOrgName' },
        { title: '部门信息', width: 'auto', align: 'center', dataIndex: 'bmOrgName', key: 'bmOrgName' },
        { title: '证书名称', width: 'auto', align: 'center', dataIndex: 'name', key: 'name' },
        {
          title: '证书类型', width: 'auto', align: 'center', dataIndex: 'type', key: 'type', customRender: (text, record, index) => {
            let textStr = '';
            this.queryOptions[0].options.forEach(element => { if (element.value.toString() === text) textStr = element.name; });
            return textStr;
          }
        },
        { title: '注册日期', width: 'auto', align: 'center', dataIndex: 'registerDate', key: 'registerDate' },
        { title: '失效日期', width: 'auto', align: 'center', dataIndex: 'validityEndDate', key: 'validityEndDate' },
        {
          title: '证书状态', width: '80px', align: 'center', dataIndex: 'state', key: 'state', customRender: (text, record, index) => {
            let textStr = '';
            this.state.forEach(element => { if (element.value.toString() === text) textStr = element.name; });
            return textStr;
          }
        },
        { title: '操作', width: '70px', key: 'operation', align: 'center', scopedSlots: { customRender: 'action' } }
      ],
      loadData: null,
    };
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    // 获取到机构树，展开顶级下树节点，考虑到后期数据量变大，不建议全部展开
    getOrgTree() {
      orgList({ orgType: this.queryParam.orgType }).then(res => {
        this.treeLoading = false
        if (!res.code === 200 || !res.data.length) {
          return
        }
        this.defaultExpandedKeys = []
        this.orgTree = listToTree(res.data, [], 0)
        this.queryParam.orgId = this.orgTree[0].id
        for (var item of this.orgTree) {
          if (item.pid === 0) {
            this.defaultExpandedKeys.push(item.id)
          }
        }

        if (!this.loadData) this.loadData = parameter => { return getArchivesCertificatelist(Object.assign(parameter, this.queryParam)).then(res => { return res }) };
        else this.handleRefresh();

      });
    },

    // 获取词典项
    dictionaryDropDown() {
      // 获取证书类型
      dictionaryDropDown({ dictionaryCode: '0001' }).then((res) => {
        this.queryOptions[0].options = res.data;
      })

      // 获取证书状态
      dictionaryDropDown({ dictionaryCode: '0010' }).then((res) => {
        this.state = res.data;
      })
    },

    // 编辑证书类型
    editCertificateType() {
      this.$router.push({ path: '/archives/certificate/CertificateType', query: {} });
    },

    // 搜索区查询按钮
    handleRefresh() {
      this.$refs.table.refresh(true)
    },

    // 切换组织树
    changeOrgType() {
      this.queryParam.orgType = this.queryParam.orgType === 1 ? 2 : 1;
      this.getOrgTree();
      // this.handleClick();
    },

    // 点击组织树节点时调用
    handleClick(e) {
      this.queryParam.orgId = e.toString()
      this.$refs.table.refresh(true)
    },

    // 修改人员证书
    editPersonCertificate(record) {
      this.$router.push({
        path: '/archives/certificate/EditCertificate', query: {
          certificateId: record.id
        }
      });
    },

    // 导出人员证书
    exportPersonCertificate(record) {
      exportCertificate({ id: record.id }).then(res => {
        downloadExportFile(res.data);
      });
    },

    // 删除人员证书
    delPersonCertificate(record) {
      delCertificate({ id: record.id }).then(res => {
        this.$message.success("删除证书成功!");
        this.$refs.table.refresh(true)
      });
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 获取组织机构树
    this.getOrgTree();

    // 获取所有证书类型
    this.dictionaryDropDown();
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() { },
  // 生命周期 - 创建之前
  beforeCreate() { },
  // 生命周期 - 挂载之前
  beforeMount() { },
  // 生命周期 - 更新之前
  beforeUpdate() { },
  // 生命周期 - 更新之后
  updated() { },
  // 生命周期 - 销毁之前
  beforeDestroy() { },
  // 生命周期 - 销毁完成
  destroyed() { },
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated() { }
};

</script>
<style scoped>
.borderTop {
  border-top: 1px solid #e8e8e8;
}
.borderRight {
  border-right: 1px solid #e8e8e8;
}
</style>