<template>
  <div>
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '210px', left: '20px', top: '57px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002评价名称'" prop="evaluationName">
              <a-input v-model="formData.evaluationName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002控制点名称'" prop="measureName">
              <a-input v-model="formData.measureName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002缺陷类型'" prop="defectType">
              <sd-select v-model="formData.defectType" :options="defectType" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'缺陷责任组织'" prop="liabilityOrgOpt">
              <sd-group-picker v-model="formData.liabilityOrgOpt" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'整改联系人'" prop="rectTracker">
              <!-- <sd-select v-model="formData.rectTracker" :options="defectType" /> -->
              <sd-user-picker v-model="formData.rectTracker" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2002\u2002\u2002\u2002整改状态'" prop="rectStatus">
              <sd-select v-model="formData.rectStatus" :options="rectStatus" />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <div :class="[$style.btns]">
        <audit-advanced-export
          ref="Export"
          :class-style="[$style.buttonSpacing]"
          :exclebxh="false"
          :expressions="expressions"
          :config-id="211"
          :v-if="false"
        />
      </div>
      <sd-data-table-ex
        :key="key"
        ref="icDefectStatementList"
        :projectlist="true"
        :editnode="editnode"
        form-id="icDefectList"
        page-id="ic/defect/statement/icDefectList"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['evaluationName', 'measureName']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </template>
      </sd-data-table-ex>
    </a-card>
  </div>
</template>

<script>
import PageService from '@/common/services/page-service'
import { Modal, message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import systemManage from '@/system-manage/system-manage'
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 auditAdvancedExport from '@product/iam/components/audit-advanced-export.vue'
import auditAdvancedQuery from '../../../components/audit-advanced-query.vue'
import IcService from '../../ic-service'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import components from './_import-components/ic-defect-statement-list-import'
export default {
  name: 'IcDefectStatementList',
  metaInfo: {
    title: '缺陷清单列表',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    auditAdvancedExport,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      recordId: '',
      editnode: true, // 列表是否可以新建
      key: 0,
      treeData: [],
      searchform: 'searchform',
      formData: {
        evaluationName: '',
        measureName: '',
        defectType: null,
        liabilityOrgOpt: [],
        rectTracker: null,
        rectStatus: null,
      },
      evaluationways: [],
      evaluationtype: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '65px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'rectRequireId', sdHidden: true },
        {
          title: '评价名称',
          dataIndex: 'evaluationName',
          width: '180px',
        },
        {
          title: '控制点名称',
          dataIndex: 'measureName',
          scopedSlots: { customRender: 'islink' },
          width: '160px',
        },

        {
          title: '控制点编号',
          dataIndex: 'measureCode',
          width: '140px',
        },
        {
          title: '录入方式',
          dataIndex: 'entryMethod',
          width: '100px',
        },
        {
          title: '缺陷类型',
          dataIndex: 'defectType',
          width: '100px',
        },
        {
          title: '缺陷责任组织',
          dataIndex: 'liabilityOrgName',
          width: '160px',
        },
        { title: '整改联系人', dataIndex: 'rectContactName', width: '140px' },
        {
          title: '拟整改完成日期',
          dataIndex: 'finishDate',
          width: '160px',
          sdRender: TableColumnTypes.date,
        },
        { title: '整改状态', dataIndex: 'rectStatus', width: '100px' },
        {
          title: '整改完成日期',
          dataIndex: 'rectFinishDate',
          width: '140px',
          sdRender: TableColumnTypes.date,
        },
        {
          title: '创建日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          width: '140px',
          defaultSortOrder: 'desc',
        },
      ],
      actions: [
        {
          label: '导出',
          id: 'export',
          permission: null,
          callback: this.export,
          index: 1,
        },
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null,
          callback: this.createStatement,
          index: 4,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          class: 'batch',
          callback: this.deleteRows,
          index: 3,
        },
      ],
      expressions: [],
      createDeptId: undefined,
      catalogId: null,
      catalogName: '',
      auditMattersPath: '',
      visible: false,
      defectType: [],
      rectStatus: [],
    }
  },
  mounted() {
    // 初始化年份下拉框
    this.initYearSelect()
    this.initDictionaryInfo()
    // 获取当前人组织
    IcService.getGroupIds().then((res) => {
      this.createDeptId = res.data
      this.expressions.push({
        dataType: 'long',
        name: 'createDeptId',
        op: 'in',
        longValues: res.data,
      })
    })
  },
  methods: {
    createStatement() {
      const url = '/ic-defect-statement-form'
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refresh()
        }
      })
    },
    export() {
      this.$refs.Export.exportdata()
    },
    refresh() {
      if (this.$refs.icDefectStatementList) {
        this.$refs.icDefectStatementList.clearSelection()
        this.$refs.icDefectStatementList.refresh()
      }
    },
    // 初始化年份下拉框
    initYearSelect() {
      const nowYear = new Date().getFullYear()
      const yearArry = []
      yearArry.push(nowYear)
      for (let i = 1; i < 6; i++) {
        yearArry.push(nowYear - i)
      }
      for (let i = 1; i < 11; i++) {
        yearArry.push(nowYear + i)
      }
      yearArry.sort()
      yearArry.forEach((year) => {
        this.yearArry.push({
          name: year,
          id: year,
        })
      })
    },
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=DEFECT_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.defectType = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=IC_RECT_STATUS',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.rectStatus = res.data
        }
      })
    },
    Saved() {
      message.success('保存成功')
      this.$refs.versionform.hide()
    },
    Closed() {
      this.$refs.versionform.hide()
      // this.$refs.versionform.resetFields()
    },
    open(record) {
      this.recordId = record.id
      window.open('#/sd-webflow/done-pages/' + record.instId)
    },
    // 新建、详情打开新页面
    rowClick(record) {
      const url = '/ic-defect-statement-form?record=' + record.id // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.refresh()
        }
      })
      // const res = crossWindowWatcher.waitForChanged(url)
    },
    // openversion(record) {
    //   if (record.flowState === '结束') {
    //     if (record.evaluationType === '穿行测试') {
    //       window.open('#/ic-work/iam-ic-cross-list?planId=' + record.id)
    //     } else {
    //       window.open('#/ic-work/iam-ic-control-list?planId=' + record.id)
    //     }
    //   } else {
    //     if (record.flowState === '起草') {
    //       window.open('#/sd-webflow/pages/draft/' + record.instId)
    //     } else {
    //       window.open('#/sd-webflow/done-pages/' + record.instId)
    //     }
    //   }
    // },
    handleSearch() {
      this.expressions = [
        {
          dataType: 'long',
          name: 'createDeptId',
          op: 'in',
          longValues: this.createDeptId,
        },
      ]
      // 评价名称
      if (this.formData.evaluationName) {
        this.expressions.push({
          dataType: 'str',
          name: 'evaluationName',
          op: 'like',
          stringValue: '%' + this.formData.evaluationName + '%',
        })
      }
      // 事项编号
      if (this.formData.measureName) {
        this.expressions.push({
          dataType: 'str',
          name: 'measureName',
          op: 'like',
          stringValue: '%' + this.formData.measureName + '%',
        })
      }

      if (this.formData.defectType) {
        this.expressions.push({
          dataType: 'str',
          name: 'defectType',
          op: 'eq',
          stringValue: this.formData.defectType[0].id,
        })
      }
      if (this.formData.liabilityOrgOpt.length > 0) {
        const optExpressions = []
        this.formData.liabilityOrgOpt.forEach((opt) => {
          optExpressions.push({
            dataType: 'str',
            name: 'liabilityOrgName',
            op: 'like',
            stringValue: '%' + opt.name + '%',
          })
        })
        if (optExpressions.length > 0) {
          this.expressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: optExpressions,
          })
        }
      }
      // 整改联系人
      if (this.formData.rectTracker) {
        const userExpressions = []
        this.formData.rectTracker.forEach((user) => {
          userExpressions.push({
            dataType: 'str',
            name: 'rectContactAccount',
            op: 'eq',
            stringValue: user.code,
          })
        })
        if (userExpressions.length > 0) {
          this.expressions.push({
            dataType: 'exps',
            op: 'or',
            expressionsValue: userExpressions,
          })
        }
      }
      // 整改状态
      if (this.formData.rectStatus) {
        this.expressions.push({
          dataType: 'str',
          name: 'rectStatus',
          op: 'eq',
          stringValue: this.formData.rectStatus[0].id,
        })
      }

      this.expressions = [...this.expressions]
    },

    // 重置
    resetForm() {
      this.formData.defectType = null
      this.formData.liabilityOrgOpt = []
      this.formData.rectTracker = null
      this.formData.rectStatus = null
    },
    // 删除数据
    deleteRows(record) {
      const selecteRows = this.$refs.icDefectStatementList.getSelectedRows()
      const selectedRowKeys = this.$refs.icDefectStatementList.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selecteRows.forEach((item) => {
        if (item.entryMethod === '转入') {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在转入的数据！',
        })
        return
      }
      selecteRows.forEach((item) => {
        if (item.rectRequireId !== '' && item.rectRequireId !== null) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败:存在已进入整改要求阶段的数据！',
        })
      } else {
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const params = {
              ids: selectedRowKeys.join(','),
            }

            PageService.delete(params, 'icDefectList').then((res) => {
              if (res.status === 200) {
                message.success({ content: '删除成功！' }, 1).then(() => {
                  this.$refs.icDefectStatementList.clearSelection()
                  this.$refs.icDefectStatementList.refresh()
                  this.loading = 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%;
    }
  }
}
.btns {
  position: absolute;
  top: 24px;
  right: 99.5px;
  z-index: 100;
}
</style>
