<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-input v-model="formData.reportNumber" allow-clear
            /></a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="编制单位" prop="fldNiGaoDW">
              <sd-group-picker
                v-model="formData.fldNiGaoDW"
                :single="false"
                :read-only="false"
                :root-node="[{ code: '-1' }]"
                allow-clear
              />
            </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 { 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 components from './_import-components/risk-task-report-list-import'
export default {
  name: 'RiskTaskReportList',
  metaInfo: {
    title: '风险任务报告',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      taskId: null,
      loading: false,
      searchform: 'searchform',
      formData: {
        title: '',
        reportNumber: '',
        fldNiGaoDW: [],
        status: [],
      },
      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: 'REPORT_NUMBER',
          width: '140px',
        },
        {
          title: '编制人员',
          dataIndex: 'CREATOR_NAME',
          width: '120px',
        },
        {
          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: [
        {
          dataType: 'long',
          name: 'TASK_ID',
          op: 'eq',
          longValue: this.$root.$route.query.taskId,
        },
      ],
    }
  },
  mounted() {
    const taskId = this.$route.query.taskId
    if (taskId) {
      this.taskId = taskId
    }
  },
  methods: {
    // 默认且必须的条件
    processReq(req) {
      req.data.formId = 'riskTaskReport'
      return req
    },
    createReport() {
      const url = '/sd-flow-guide?code=PRODUCT_RISK_TREPORT&taskId=' + this.taskId // 新页面要打开的路由地址
      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 = []
      this.expressions.push({
        dataType: 'long',
        name: 'TASK_ID',
        op: 'eq',
        longValue: this.$root.$route.query.taskId,
      })
      // 报告名称
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'TITLE',
          op: 'like',
          stringValue: '%' + this.formData.title + '%',
        })
      }
      // 报告编号
      if (this.formData.reportNumber) {
        this.expressions.push({
          dataType: 'str',
          name: 'REPORT_NUMBER',
          op: 'like',
          stringValue: '%' + this.formData.reportNumber + '%',
        })
      }

      // 编制单位
      const arrCreateDeptId = this.formData.fldNiGaoDW.map((n) => n.code)
      const createDeptId = arrCreateDeptId.join(',')
      if (createDeptId) {
        const createDeptItem = {
          dataType: 'str',
          name: 'CREATE_DEPT_ID',
          op: 'in',
          stringValue: createDeptId,
        }
        this.expressions.push(createDeptItem)
      }

      // 流程状态
      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: '',
        reportNumber: '',
        status: [],
        fldNiGaoDW: [],
      }
    },
    // 删除数据
    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>
