<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="案例名称">
              <a-input v-model="formData.title" allow-clear></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发生年份">
              <a-date-picker
                v-model="formData.caseYear"
                placeholder="请选择年"
                mode="year"
                :open="dataopen"
                format="YYYY"
                :allow-clear="true"
                @openChange="openChangeYear"
                @panelChange="panelChangeYear"
            /></a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="案例来源">
              <a-select v-model="formData.caseSource" allow-clear>
                <a-select-option
                  v-for="(item, index) in caseSourceOptions"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select></a-form-model-item
            >
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="当前状态">
              <sd-select v-model="formData.status" :options="statusList" allow-clear />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table
        ref="dataTable"
        data-url="api/xcoa-mobile/v1/iam-common/search"
        :row-key="'INST_ID'"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :process-req="processReq"
        :filter-expressions="expressions"
        :search-fields="['title']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="rowClick(record)">{{ text }}</a>
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import { Modal, message } from 'ant-design-vue'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import { getUserInfo } from '@/common/store-mixin'
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 auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import CommonService from '../../core/api/common-service'
import components from './_import-components/risk-case-list-import'
export default {
  name: 'RiskCaseList',
  metaInfo: {
    title: '风险案例库',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      loading: false,
      searchform: 'searchform',
      dataopen: false,
      formData: {
        title: '',
        caseYear: '',
        caseSource: '',
        status: [],
      },
      caseSourceOptions: [],
      statusList: [
        {
          id: 0,
          name: '起草中',
        },
        {
          id: 1,
          name: '审批中',
        },
        {
          id: 5,
          name: '已结束',
        },
      ],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '65px',
        },
        {
          title: '案例名称',
          dataIndex: 'TITLE',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '案件类别',
          dataIndex: 'CASE_TYPE',
          width: '140px',
        },
        {
          title: '发生年份',
          dataIndex: 'CASE_YEAR',
          width: '140px',
        },
        {
          title: '案例来源',
          dataIndex: 'CASE_SOURCE',
          width: '140px',
        },
        {
          title: '编制人员',
          dataIndex: 'CREATOR_NAME',
          width: '120px',
          sdCandidate: true,
        },
        {
          title: '编制日期',
          dataIndex: 'CREATION_TIME',
          sdRender: TableColumnTypes.date,
          sorter: true,
          defaultSortOrder: 'desc',
          width: '140px',
        },
        {
          title: '编制单位',
          dataIndex: 'CREATE_DEPT_NAME',
          width: '140px',
        },
        {
          title: '当前状态',
          dataIndex: 'FLOW_STATE',
          width: '140px',
        },
        { title: '当前处理人', dataIndex: 'CURRENT_USER', width: '140px' },
      ],
      actions: [
        {
          label: '新建',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null,
          callback: this.createReport,
          index: 4,
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          permission: null,
          callback: (keys) => {
            this.deleteRows(keys)
          },
          index: 3,
        },
      ],
      expressions: [],
    }
  },
  created() {
    CommonService.getDictValues('CASE_SOURCE').then((res) => {
      this.caseSourceOptions = res
    })
  },
  methods: {
    // 默认且必须的条件
    processReq(req) {
      req.data.formId = 'riskCase'
      return req
    },
    // 点击选择框事件 弹出日期组件选择年
    openChangeYear(status) {
      if (status) {
        this.dataopen = true
      } else {
        this.dataopen = false
      }
    },
    // 选择年之后 关闭弹框
    panelChangeYear(value) {
      this.dataopen = false
      this.formData.caseYear = moment(value).format('YYYY')
    },
    createReport() {
      const url = '/sd-flow-guide?code=PRODUCT_RISK_CASE' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },

    refreshDataTable() {
      if (this.$refs.dataTable) {
        this.$refs.dataTable.clearSelection()
        this.$refs.dataTable.refresh()
      }
    },
    rowClick(record) {
      let url
      if (
        (record.FLOW_STATE === '起草') | (record.FLOW_STATE === '开始') &&
        record.CREATOR_ACCOUNT === getUserInfo().account
      ) {
        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.refreshDataTable()
        }
      })
    },
    handleSearch() {
      this.expressions = []
      // 案例名称
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'TITLE',
          op: 'like',
          stringValue: '%' + this.formData.title + '%',
        })
      }
      // 发生年份
      if (this.formData.caseYear) {
        this.expressions.push({
          dataType: 'str',
          name: 'CASE_YEAR',
          op: 'eq',
          stringValue: this.formData.caseYear,
        })
      }
      // 报告类型
      if (this.formData.caseSource) {
        this.expressions.push({
          dataType: 'str',
          name: 'CASE_SOURCE',
          op: 'eq',
          stringValue: this.formData.caseSource,
        })
      }
      // 流程状态
      if (this.formData.status.length > 0) {
        this.expressions.push({
          dataType: 'long',
          name: 'END_TYPE',
          op: 'eq',
          longValue: this.formData.status[0].id,
        })
      }

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

    // 重置
    resetForm() {
      this.formData = {
        title: '',
        caseYear: '',
        caseSource: '',
        status: [],
      }
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      const selectRows = this.$refs.dataTable.getSelectedRows()
      if (selectedRowKeys.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selectRows.forEach((item) => {
        if (item.END_TYPE !== 0) {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
      } else {
        Modal.confirm({
          title: '你确定删除这项内容吗？',
          content: '删除这条数据后，就无法恢复初始的状态。',
          okText: '删除',
          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.$refs.dataTable.clearSelection()
                  this.$refs.dataTable.refresh()
                  this.loading = false
                })
              }
            })
          },
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
