<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="任务年度">
              <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="任务名称">
              <a-input v-model="formData.dutieName" allow-clear />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发起机构">
              <a-input v-model="formData.inspectUnitName" allow-clear />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table-ex
        :key="key"
        ref="riskDutieTable"
        form-id="riskDutie"
        page-id="risk/dutie/riskDutie"
        data-url="api/xcoa-mobile/v1/riskdutie/all-list"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['year', 'dutieName']"
        @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>
  </div>
</template>

<script>
import { getUserInfo } from '@/common/store-mixin'
import FlowcenterService from '@/flowcenter/flowcenter-service'
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 components from './_import-components/risk-tasks-list-import'
export default {
  name: 'RiskTasksList',
  metaInfo: {
    title: '风险任务',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      key: 0,
      searchform: 'searchform',
      formData: {
        year: '',
        dutieName: '',
        inspectUnitName: '',
      },
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'instId', sdHidden: true },
        {
          title: '任务年度',
          dataIndex: 'year',
          width: '120px',
          defaultSortOrder: 'desc',
        },
        {
          title: '任务名称',
          dataIndex: 'dutieName',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '任务编号',
          dataIndex: 'dutieCode',
        },
        {
          title: '发起机构',
          dataIndex: 'inspectUnitName',
        },
        {
          title: '任务类型',
          dataIndex: 'dutieType',
        },
        {
          title: '创建人员',
          dataIndex: 'creatorName',
        },
        {
          title: '创建日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          width: '120px',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
          width: '120px',
        },
        { title: '当前处理人', dataIndex: 'currentUser', width: '120px' },
        { title: '文档状态', dataIndex: 'endType', width: '120px', sdHidden: true },
        {
          title: '操作',
          dataIndex: '',
          scopedSlots: { customRender: 'action' },
          align: 'center',
          width: '80px',
        },
      ],
      actions: [
        {
          label: '新建任务',
          id: 'new',
          type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
          permission: null,
          callback: this.createRiskTask,
          index: 4,
        },
        {
          label: '删除',
          id: 'delete',
          permission: null,
          class: 'batch',
          callback: this.deleteRows,
          index: 3,
        },
      ],
      expressions: [],

      auditMattersPath: '',
      visible: false,
      radioValue: '0',
      radioType: true,
      radioStyle: {},
    }
  },
  mounted() {
    // 初始化年份下拉框
    this.initYearSelect()
  },
  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.riskDutieTable.clearSelection()
    },
    // 创建任务
    createRiskTask() {
      const url = '/sd-flow-guide?code=PRODUCT_RISK_TASKS' // 新页面要打开的路由地址
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshDataTable()
        }
      })
    },
    // 刷新列表
    refreshDataTable() {
      if (this.$refs.riskDutieTable) {
        this.$refs.riskDutieTable.refresh()
        this.$refs.riskDutieTable.clearSelection()
      }
    },
    // 初始化年份下拉框
    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,
        })
      })
    },
    open(record) {
      this.recordId = record.id
      window.open('#/sd-webflow/done-pages/' + record.instId)
    },
    openversion(record) {
      if (record.flowState === '结束') {
        window.open('#/risk-tasks/?taskId=' + record.id)
      } else {
        let openurl = ''
        const loginUser = getUserInfo()
        if (
          (record.flowState === '开始') |
          (record.flowState === '起草') |
          (record.flowState === null)
        ) {
          if (loginUser.name === record.currentUser) {
            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.radioValue === '1') {
        this.Expressions.push({
          dataType: 'str',
          name: 'pending',
          op: 'eq',
          stringValue: this.radioValue,
        })
      }
      // 年度
      if (this.formData.year.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'year',
          op: 'eq',
          stringValue: this.formData.year[0].name + '',
        })
      }
      // 任务名称
      if (this.formData.dutieName) {
        this.expressions.push({
          dataType: 'str',
          name: 'dutieName',
          op: 'like',
          stringValue: '%' + this.formData.dutieName + '%',
        })
      }
      // 发起机构
      if (this.formData.inspectUnitName) {
        this.expressions.push({
          dataType: 'str',
          name: 'inspectUnitName',
          op: 'like',
          stringValue: '%' + this.formData.inspectUnitName + '%',
        })
      }

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

    // 重置
    resetForm() {
      this.formData = {
        year: '',
        dutieName: '',
        inspectUnitName: [],
      }
    },
    // 删除数据
    deleteRows(record) {
      const selecteFlowState = this.$refs.riskDutieTable.getSelectedRows()
      const selectedRowKeys = this.$refs.riskDutieTable.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.riskDutieTable.clearSelection()
                  this.$refs.riskDutieTable.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>
