<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{
          height: '170px',
          width: 'calc(100% - 0px) !important',
          margin: 'auto 0px',
          top: '40px !important',
        }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item label="报告标题">
              <a-input v-model="formData.reportName"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="被评价单位">
              <audit-group-picker
                v-model="formData.evaluatedUnitOpt"
                :read-only="false"
                :root-node="{ code: 0, name: '内控机构', id: 0 }"
                :selectall="false"
                :top-node-text="'内控机构'"
                :treeparams="{
                  moduleId: 'icEvaluationReport',
                }"
              />
            </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
        v-show="flag"
        :key="key"
        ref="icevaluationTable"
        form-id="icEvaluationReport"
        :data-url="dataurl"
        row-key="instId"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :process-res="processRes"
        :filter-expressions="expressions"
        :search-fields="['reportName']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="open(record)">{{ text }}</a>
        </template>
      </sd-data-table>
    </a-card>
  </div>
</template>

<script>
import FlowcenterService from '@/flowcenter/flowcenter-service'
import auditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
import { getUserInfo } from '@/common/store-mixin'
import { Modal, message } from 'ant-design-vue'
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 auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import iamIcEvaluationReportServices from './iam-ic-evaluation-report-service'
import components from './_import-components/iam-ic-evaluation-report-list-import'
export default {
  name: 'IamIcEvaluationReportList',
  metaInfo: {
    title: '内控评价报告',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    auditGroupPicker,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      statusList: [
        {
          id: 0,
          name: '起草中',
        },
        {
          id: 1,
          name: '审批中',
        },
        {
          id: 5,
          name: '已结束',
        },
      ],
      dataurl: 'api/xcoa-mobile/v1/icevaluationreport/all-list?planId=' + this.$route.query.planId,
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      key: 0,
      searchform: 'searchform',
      formData: {
        reportName: '',
        evaluatedUnitOpt: [],
        status: [],
      },
      rootNode: {},
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'instId', sdHidden: true },
        { dataIndex: 'evaluationType', sdHidden: true },
        {
          title: '报告标题',
          dataIndex: 'reportName',
          scopedSlots: { customRender: 'islink' },
          width: '300px',
        },
        {
          title: '被评价单位',
          dataIndex: 'evaluatedUnitName',
          width: '300px',
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          sorter: true,
          defaultSortOrder: 'desc',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
        },
        { title: '当前处理人', dataIndex: 'nowUser' },
        { title: '流程状态', dataIndex: 'endType', sdHidden: true },
      ],
      actions: [],
      expressions: [],
    }
  },
  mounted() {
    // 判断用户权限是否可以新建及删除
    const loginUser = getUserInfo()
    const planId = parseFloat(this.$route.query.planId)
    iamIcEvaluationReportServices.getPlanInfo(planId).then((res) => {
      const userName = res.data.pageFormData.pageFieldInfos.find((item) => {
        return item.name === 'creatorName'
      }).value
      if (userName === loginUser.name) {
        this.actions.push(
          {
            label: '新建',
            id: 'new',
            type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
            permission: null,
            callback: this.createReport,
            index: 4,
          },
          {
            label: '删除',
            id: 'delete',
            type: TableActionTypes.batch,
            permission: null,
            index: 3,
            callback: (keys) => {
              this.deleteRows(keys)
            },
          }
        )
      }
    })
  },
  methods: {
    processRes(res) {
      res.data.forEach((item) => {
        item.INST_ID = item.instId
      })
      return res
    },
    createReport() {
      const url = '/sd-flow-guide?code=PRODUCT_IC_REPORT&planId=' + this.$route.query.planId // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },

    refreshDataTable() {
      if (this.$refs.icevaluationTable) {
        this.$refs.icevaluationTable.clearSelection()
        this.$refs.icevaluationTable.refresh()
      }
    },
    open(record) {
      let openurl = ''
      const loginUser = getUserInfo()
      if (
        (record.flowState === '起草') |
        (record.flowState === '开始') |
        (record.flowState === null)
      ) {
        if (loginUser.name === record.nowUser) {
          openurl = '/sd-webflow/pages/draft/' + record.instId
        } else {
          openurl = '/sd-webflow/done-pages/' + record.instId
        }
      } else {
        openurl = '/sd-webflow/done-pages/' + record.instId
      }
      crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    handleSearch() {
      this.expressions = []
      // 报告名称
      if (this.formData.reportName) {
        this.expressions.push({
          dataType: 'str',
          name: 'reportName',
          op: 'like',
          stringValue: '%' + this.formData.reportName + '%',
        })
      }
      // 被评价单位
      if (this.formData.evaluatedUnitOpt.length > 0) {
        const unitExp = this.formData.evaluatedUnitOpt.map((item) => item.code)
        this.expressions.push({
          dataType: 'str',
          name: 'evaluatedUnitId',
          op: 'in',
          stringValue: unitExp.join(','),
        })
      }
      // 流程状态
      if (this.formData.status.length > 0) {
        this.expressions.push({
          dataType: 'long',
          name: 'endType',
          op: 'eq',
          longValue: this.formData.status[0].id,
        })
      }

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

    // 重置
    resetForm() {
      this.formData = {
        reportName: '',
        evaluatedUnitOpt: [],
        status: [],
      }
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      const selecteFlowState = this.$refs.icevaluationTable.getSelectedRows()
      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 params = {
              flowCallbackBeanName: 'formBeanCleanerCallBack',
              processInstanceIds: selectedRowKeys.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%;
    }
  }
}
</style>
