<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '170px', left: '20px', top: '57px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item label="计划年度" prop="year">
              <sd-select v-model="formData.year" :options="yearArry" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="评价名称" 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="评价类型" prop="evaluationtype">
              <sd-select v-model="formData.evaluationtype" :options="evaluationtype" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="评价方式" prop="evaluationways">
              <sd-select v-model="formData.evaluationways" :options="evaluationways" />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table-ex
        v-show="flag"
        :key="key"
        ref="icevaluationTable"
        :editnode="editnode"
        form-id="icEvaluationPlan"
        page-id="ic/evaluation/icEvaluationPlan"
        data-url="api/xcoa-mobile/v1/icevaluationplan/all-list"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['year', 'evaluationName']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="openversion(record)">{{ text }}</a>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="open(record)"
            ><sd-icon type="sd-eye" :style="{ fontSize: '25px' }"
          /></a-button>
        </template>
      </sd-data-table-ex>
      <div :class="[$style.btns]">
        <a-col :span="13" :offset="0">
          <a-radio-group v-model="radioValue" @change="radioOnChange">
            <a-radio :style="radioStyle" :value="'0'">
              全部
            </a-radio>
            <a-radio :style="radioStyle" :value="'1'">
              待处理
            </a-radio>
          </a-radio-group>
        </a-col>
      </div>
    </a-card>
    <sd-detail-modal
      ref="versionform"
      :read-only="true"
      :record-id="recordId"
      page-id="ic/version/icMtxVersion"
      :modal-props="{ width: 1200 }"
    >
      <template v-slot="{ model, fields }">
        <table style="width:80%">
          <colgroup>
            <col style="width: 20%;" />
            <col style="width: 30%;" />
            <col style="width: 20%;" />
            <col style="width: 30%;" />
          </colgroup>
          <tr
            ><sd-form-item-td name="belongUnitName"></sd-form-item-td
            ><sd-form-item-td name="year"></sd-form-item-td
          ></tr>
          <tr v-show="false"
            ><sd-form-item-td name="belongUnitCode"></sd-form-item-td>
            <sd-form-item-td name="belongUnitId"></sd-form-item-td>
          </tr>

          <tr
            ><sd-form-item-td name="auditOrgId" :hidden="true"></sd-form-item-td>
            <sd-form-item-td name="modifyDeptId" :hidden="true"></sd-form-item-td>
          </tr>
          <tr
            ><sd-form-item-td name="modifyDeptCode" :hidden="true"></sd-form-item-td>
            <sd-form-item-td name="modifyDeptName" :hidden="true"></sd-form-item-td>
          </tr>

          <tr
            ><sd-form-item-td name="versionCode"></sd-form-item-td
            ><sd-form-item-td name="versuibType"></sd-form-item-td
          ></tr>
          <tr><sd-form-item-td colspan="3" name="matrixType"></sd-form-item-td></tr>
          <tr><sd-form-item-td colspan="3" name="matrixDesc"></sd-form-item-td></tr>
          <tr
            ><sd-form-item-td name="creatorName"></sd-form-item-td
            ><sd-form-item-td name="creationTime"></sd-form-item-td></tr
        ></table>
      </template>
    </sd-detail-modal>
  </div>
</template>

<script>
import PageService from '@/common/services/page-service'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import { Modal, message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import systemManage from '@/system-manage/system-manage'
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 pickValues from '@/common/services/pick-values'
import sdIconPicker from '@/common/components/sd-icon-picker.vue'
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 mtxVersionForm from './mtx-version-form'
// import MtxVersionService from './ic-evaluation-service'
import components from './_import-components/ic-evaluation-list-import'
export default {
  name: 'MtxEvaluationList',
  metaInfo: {
    title: '内控评价',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    // mtxVersionForm,
  },
  // auditAdvancedGroupMixins
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      editnode: true, // 列表是否可以新建
      key: 0,
      treeData: [],
      searchform: 'searchform',
      formData: {
        year: '',
        evaluationname: '',
        evaluationways: '',
        evaluationtype: '',
      },
      evaluationways: [],
      evaluationtype: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'instId', sdHidden: true },
        { dataIndex: 'evaluationType', sdHidden: true },
        {
          title: '计划年度',
          dataIndex: 'year',
          width: '120px',
          defaultSortOrder: 'desc',
        },
        {
          title: '计划名称',
          dataIndex: 'evaluationName',
          scopedSlots: { customRender: 'islink' },
        },

        {
          title: '检查单位',
          dataIndex: 'inspectUnitName',
        },
        {
          title: '创建日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          width: '120px',
        },
        {
          title: '评价类型',
          dataIndex: 'evaluationType',
          width: '100px',
        },
        {
          title: '流程状态',
          dataIndex: 'flowState',
          width: '120px',
        },
        { title: '当前处理人', dataIndex: 'currentUser', width: '120px' },
        {
          title: '操作',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: '80px',
        },
      ],
      actions: [
        {
          label: '新建计划',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null,
          callback: this.createEvaluationPlan,
          index: 4,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          class: 'batch',
          callback: this.deleteRows,
          index: 3,
        },
      ],
      expressions: [],
      catalogId: null,
      catalogName: '',
      auditMattersPath: '',
      visible: false,
      radioValue: '0',
      radioType: true,
      radioStyle: {},
    }
  },
  mounted() {
    // 初始化年份下拉框
    this.initYearSelect()
    this.initDictionaryInfo()
  },
  methods: {
    radioOnChange(e, info) {
      this.radioValue = e.target.value
      this.radioType = true
      this.expressions.forEach((item) => {
        if (item.name === 'pending') {
          item.stringValue = this.radioValue
          this.radioType = false
        }
      })

      if (this.radioType) {
        this.expressions.push({
          dataType: 'str',
          name: 'pending',
          op: 'eq',
          stringValue: this.radioValue,
        })
      }
      this.expressions = [...this.expressions]
      this.$refs.icevaluationTable.clearSelection()
    },
    createEvaluationPlan() {
      const url = '/sd-flow-guide?code=PRODUCT_IC_NKPJJH' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },

    refreshDataTable() {
      if (this.$refs.icevaluationTable) {
        this.$refs.icevaluationTable.clearSelection()
        this.$refs.icevaluationTable.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=EVALUATION_TYPE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.evaluationtype = res.data
        }
      })
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=EVALUATION_MODE',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.evaluationways = 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)
    },
    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 {
        let url = ''
        if ((record.flowState === '起草') | (record.flowState === '开始')) {
          // window.open('#/sd-webflow/pages/draft/' + record.instId)
          url = `/sd-webflow/pages/draft/` + record.instId
        } else {
          // window.open('#/sd-webflow/done-pages/' + record.instId)
          url = `/sd-webflow/done-pages/` + record.instId
        }
        crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
          if (refreshFlag) this.refreshDataTable()
        })
      }
    },
    handleSearch() {
      this.expressions = []
      // 全部 待处理
      if (this.radioValue === '1') {
        this.Expressions.push({
          dataType: 'str',
          name: 'pending',
          op: 'eq',
          stringValue: this.radioValue,
        })
      }
      // 审计事项名称
      if (this.formData.year) {
        this.expressions.push({
          dataType: 'str',
          name: 'year',
          op: 'eq',
          stringValue: this.formData.year[0].name,
        })
      }
      // 审计事项编号
      if (this.formData.evaluationname) {
        this.expressions.push({
          dataType: 'str',
          name: 'evaluationName',
          op: 'like',
          stringValue: '%' + this.formData.evaluationname + '%',
        })
      }

      if (this.formData.evaluationtype) {
        this.expressions.push({
          dataType: 'str',
          name: 'evaluationType',
          op: 'like',
          stringValue: this.formData.evaluationtype[0].id,
        })
      }
      if (this.formData.evaluationways) {
        this.expressions.push({
          dataType: 'str',
          name: 'evaluationMode',
          op: 'eq',
          stringValue: this.formData.evaluationways[0].id,
        })
      }

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

    // 重置
    resetForm() {
      this.formData.year = null
      this.formData.evaluationways = null
      this.formData.evaluationtype = null
    },
    // 删除数据
    deleteRows(record) {
      const selecteFlowState = this.$refs.icevaluationTable.getSelectedRows()
      const selectedRowKeys = this.$refs.icevaluationTable.getSelectedRowKeys()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selecteFlowState.forEach((item) => {
        if (item.endType !== 0) {
          flag = true
        }
      })
      if (flag) {
        // 有过错误
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
      } else {
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const instIds = []
            selecteFlowState.forEach((item) => {
              if (item.instId) {
                instIds.push(item.instId)
              }
            })
            const params = {
              flowCallbackBeanName: 'formBeanCleanerCallBack',
              processInstanceIds: instIds.join(','),
            }
            FlowcenterService.fnDarftsDelete(params).then((res) => {
              if (res.status === 200) {
                message.success({ content: '删除成功！' }, 1).then(() => {
                  this.$refs.icevaluationTable.clearSelection()
                  this.$refs.icevaluationTable.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: 20px;
  right: 0;
  left: 20px;
  z-index: 100;
  width: calc(100% - 400px);
  span {
    color: blue;
  }
}
</style>
