<template>
  <div>
    <a-card :class="$style.surveyCard">
      <audit-advanced-query
        :expand="expand"
        :search-data="surveyFormData"
        :ref-name="searchform"
        :search-style="{ height: '130px', left: '20px', top: '40px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'评价名称'" prop="evaluationName">
              <a-input v-model="surveyFormData.evaluationName" allow-clear />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table
        ref="icConfirm"
        data-url="api/xcoa-mobile/v1/iam-common/search"
        :row-key="'INST_ID'"
        :columns="Columns"
        :filter-expressions="Expressions"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :process-req="processReq"
        :search-fields="['EVALUATION_NAME', 'YEAR']"
        @searchbtnClick="searchbtnClick"
      >
        <div slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </div>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import PageService from '@/common/services/page-service'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import axios from '@/common/services/axios-instance'
import { Modal, message } from 'ant-design-vue'
import moment from 'moment'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import TableActionTypes from '@/common/services/table-action-types'
import auditAdvancedQuery from '../../../components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '../../../components/audit-advanced-query-mixins'
import components from './_import-components/iam-work-confirm-import'

const Columns = [
  {
    title: '序号',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    title: '评价名称',
    dataIndex: 'EVALUATION_NAME',
    scopedSlots: { customRender: 'islink' },
  },
  {
    title: '年度',
    dataIndex: 'YEAR',
    width: '20%',
  },
  {
    title: '检查单位',
    width: '10%',
    dataIndex: 'INSPECT_UNIT_NAME',
  },
  {
    title: '被检查单位',
    dataIndex: 'EVALUATION_UNIT_NAME',
    width: '10%',
  },
  {
    title: '当前状态',
    dataIndex: 'FLOW_STATE',
    width: '120px',
  },
  { title: '当前处理人', dataIndex: 'CURRENT_USER' },
  { title: '评价计划ID', dataIndex: 'PLAN_ID', sdHidden: true },
]
export default {
  name: 'IamWorkConfirm',
  metaInfo: {
    title: '缺陷列表',
  },
  components: { ...components, auditAdvancedQuery },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      formId: 'icEvaluationConfirm',
      planId: this.$root.$route.query.planId,
      Columns,
      searchform: 'searchform',
      surveyFormData: {
        evaluationName: '',
      },
      Expressions: [
        {
          dataType: 'long',
          name: 'PLAN_ID',
          op: 'eq',
          longValue: this.$root.$route.query.planId,
        },
      ],
      actions: [],
      versionId: '',
      orgId: '',
      orgName: '',
    }
  },
  mounted() {
    const planId = this.$route.query.planId
    if (planId) {
      this.planId = planId
    }
    axios({
      url: `api/framework/v1/page/wp/ic/evaluation/plan/icEvaluationPlan?id=` + planId,
    }).then((res) => {
      const creatorName = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'creatorName'
      )
      if (res.data.pageFormData.pageFieldInfos[creatorName].value === getUserInfo().name) {
        this.actions = [
          {
            label: '新建',
            id: 'new',
            type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
            permission: null,
            callback: this.createconfirm,
            index: 1,
          },
          {
            label: '删除',
            id: 'delete',
            type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
            permission: null,
            callback: (keys) => {
              this.deleteRows(keys)
            },
            index: 3,
          },
        ]
      }
    })
  },
  methods: {
    // 默认且必须的条件
    processReq(req) {
      req.data.formId = 'icEvaluationConfirm'
      return req
    },
    createconfirm() {
      const url = '/sd-flow-guide?code=PRODUCT_IC_CONFIRM&planId=' + this.planId // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refresh()
        }
      })
    },
    deleteRows(selectedRowKeys) {
      const selecteFlowState = this.$refs.icConfirm.getSelectedRows()
      if (selecteFlowState.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selecteFlowState.forEach((item) => {
        if (item.END_TYPE !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
      } else {
        Modal.confirm({
          title: '您确定删除这项内容吗？',
          content: '删除数据后，就无法恢复初始的状态。',
          okText: '删除',
          cancelText: '取消',
          okType: 'danger',
          onOk: () => {
            this.loading = true
            const params = {
              flowCallbackBeanName: 'formBeanCleanerCallBack',
              processInstanceIds: selectedRowKeys.join(','),
            }
            FlowcenterService.fnDarftsDelete(params).then((res) => {
              if (res.status === 200) {
                message.success({ content: '删除成功！' }, 1).then(() => {
                  this.refresh()
                })
              }
            })
          },
          onCancel: () => {
            // resolve()
          },
        })
      }
    },
    moment,
    rowClick(record) {
      let url = ''
      if ((record.FLOW_STATE === '起草') | (record.FLOW_STATE === '开始')) {
        url = `/sd-webflow/pages/draft/` + record.INST_ID
      } else {
        url = `/sd-webflow/done-pages/` + record.INST_ID
      }
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) this.refresh()
      })
    },
    refresh() {
      if (this.$refs.icConfirm) {
        this.$refs.icConfirm.clearSelection()
        this.$refs.icConfirm.refresh()
      }
    },
    handleSearch() {
      this.Expressions = []
      this.Expressions.push({
        dataType: 'long',
        name: 'PLAN_ID',
        op: 'eq',
        longValue: this.$root.$route.query.planId,
      })
      if (this.surveyFormData.evaluationName) {
        this.Expressions.push({
          dataType: 'str',
          name: 'EVALUATION_NAME',
          op: 'like',
          stringValue: `%${this.surveyFormData.evaluationName}%`,
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.sjfxTable {
  :global .ant-table-column-title {
    white-space: normal;
  }
  :global(.ant-table-body) {
    overflow-x: scroll !important;
  }

  :global(.ant-table-empty) {
    :global(.ant-table-body) {
      overflow-x: scroll !important;
    }
  }
}
.survey-card {
  margin-top: -7px;
}
.btns {
  position: absolute;
  top: 0;
  right: 0;
  left: 20px;
  z-index: 100;
  width: calc(100% - 40px);
  span {
    color: blue;
  }
}
</style>
