<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '173px', top: '45px !important' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-col :span="12">
            <a-form-model-item :label="'标\u2003\u2003题'">
              <a-input v-model="formData.title" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="编制人员">
              <sd-user-picker v-model="formData.creatorName" :single="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="编制日期">
              <a-range-picker v-model="formData.creationTime" />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table
        :key="key"
        ref="riskIdentifyTable"
        page-id="risk/identify/riskIdentify"
        row-key="instId"
        :data-url="dataUrl"
        :columns="columns"
        :actions="actions"
        :show-selection="showSelection"
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['title']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="openDoc(record)">{{ text }}</a>
        </template>
      </sd-data-table>
      <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 v-show="false">
      <sd-user-picker
        ref="userSelect"
        v-model="selectuser"
        :single="isSingle"
        :read-only="false"
        @change="userChange"
      />
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import FlowcenterService from '@/flowcenter/flowcenter-service'
import { Modal, message } from 'ant-design-vue'
import { getUserInfo } from '@/common/store-mixin'
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 riskTasksService from '../risk-tasks-service'
import riskIdentificationService from './risk-identification-service'
import components from './_import-components/risk-identification-list-import'
export default {
  name: 'RiskIdentificationList',
  metaInfo: {
    title: '风险识别',
  },
  components: {
    ...components,
    auditAdvancedQuery,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      showSelection: true, // 是否显示复选框
      isSingle: false,
      selectuser: [], // 分配识别人
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      key: 0,
      searchform: 'searchform',
      formData: {
        title: '',
        creatorName: [],
        creationTime: [],
      },
      dataUrl: 'api/xcoa-mobile/v1/riskidentify/all-list?taskId=' + this.$route.query.taskId,
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '标题',
          dataIndex: 'title',
          scopedSlots: { customRender: 'islink' },
        },
        {
          title: '编制人员',
          dataIndex: 'creatorName',
        },
        {
          title: '编制日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          defaultSortOrder: 'descend',
        },
        {
          title: '流程状态',
          dataIndex: 'flowState',
        },
        { title: '当前处理人', dataIndex: 'currentUser', width: '120px' },
        { title: '识别人', dataIndex: 'contactsName', width: '120px' },
      ],
      actions: [
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
          permission: null,
          callback: (keys) => {
            this.deleteRows(keys)
          },
          index: 3,
        },
      ],
      expressions: [
        {
          dataType: 'long',
          name: 'taskId',
          op: 'eq',
          longValue: this.$route.query.taskId,
        },
      ],
      auditMattersPath: '',
      visible: false,
      radioValue: '0',
      radioType: true,
      radioStyle: {},
    }
  },
  mounted() {
    const taskId = this.$route.query.taskId
    if (taskId) {
      this.taskId = taskId
    }
    riskTasksService.getRiskTaskInfo(taskId).then((res) => {
      const creatorName = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'creatorName'
      )
      // 判断任务创建人 start
      const creatorNameField = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'riskDutieTaskUserList'
      )
      const creatorNameList = JSON.parse(
        res.data.pageFormData.pageFieldInfos[creatorNameField].value
      )
        .filter((item) => {
          return item.contactsRole === 'contactsUser'
        })
        .map((item) => {
          return item.contactsName
        })
      // 判断任务创建人 end
      if (
        res.data.pageFormData.pageFieldInfos[creatorName].value === getUserInfo().name ||
        creatorNameList.includes(getUserInfo().name)
      ) {
        this.showSelection = true
        this.actions = [
          {
            label: '分配识别人',
            id: 'new',
            type: TableActionTypes.primary, // 新建按钮，不需要回调，自动处理
            permission: null,
            callback: this.createRiskIdentify,
            index: 4,
          },
          {
            label: '删除',
            id: 'delete',
            type: TableActionTypes.batch, // 批处理按钮，选中文档时才能点击
            permission: null,
            callback: (keys) => {
              this.deleteRows(keys)
            },
            index: 3,
          },
        ]
      }
    })
  },
  methods: {
    // 选择了分配人之后
    userChange(values) {
      // 如果是设置识别人，则需要是起草状态
      if (this.isSingle === true) {
        const selectRows = this.$refs.riskIdentifyTable.getSelectedRows()
        let flag = true
        selectRows.forEach((item) => {
          if (item.flowState !== '起草') {
            flag = false
          }
        })
        // 如果存在不是起草的文件
        if (!flag) {
          Modal.info({
            content: '请选择起草状态的文件',
          })
          this.selectuser = []
          return
        }
      }
      const selectRowsId = this.$refs.riskIdentifyTable.getSelectedRows().map((item) => {
        return parseFloat(item.id)
      })
      const account = values.map((item) => item.code)
      const data = {
        account: account,
        taskId: parseFloat(this.$route.query.taskId),
      }
      // 分配识别人
      data.identifyId = selectRowsId
      riskIdentificationService.setIdentifyUser(data).then((data) => {
        if (data) {
          message.success({ content: '处理成功！' }, 1).then(() => {
            this.selectuser = []
            this.refreshDataTable()
          })
        }
      })
    },
    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.riskIdentifyTable.clearSelection()
    },
    // 创建任务
    createRiskIdentify() {
      const selectRows = this.$refs.riskIdentifyTable.getSelectedRows()
      if (selectRows.length > 0) {
        this.isSingle = true
      } else {
        this.isSingle = false
      }
      this.$refs.userSelect.openPicker()
    },
    // 刷新列表
    refreshDataTable() {
      if (this.$refs.riskIdentifyTable) {
        this.$refs.riskIdentifyTable.clearSelection()
        this.$refs.riskIdentifyTable.refresh()
      }
    },
    openDoc(record) {
      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 = [
        {
          dataType: 'long',
          name: 'taskId',
          op: 'eq',
          longValue: this.$route.query.taskId,
        },
      ]
      // 全部 待处理
      if (this.radioValue === '1') {
        this.expressions.push({
          dataType: 'str',
          name: 'pending',
          op: 'eq',
          stringValue: this.radioValue,
        })
      }
      // 标题
      if (this.formData.title) {
        this.expressions.push({
          dataType: 'str',
          name: 'title',
          op: 'like',
          stringValue: '%' + this.formData.title + '%',
        })
      }
      // 任务名称
      if (this.formData.creatorName.length > 0) {
        this.expressions.push({
          dataType: 'str',
          name: 'creatorName',
          op: 'eq',
          stringValue: this.formData.creatorName[0].name,
        })
      }
      // 发起机构
      if (this.formData.creationTime.length > 0) {
        this.expressions.push({
          dataType: 'long',
          name: 'creationTime',
          op: 'between',
          longValues: [
            moment(moment(this.formData.creationTime[0]).startOf('day')).valueOf(),
            moment(moment(this.formData.creationTime[1]).endOf('day')).valueOf(),
          ],
        })
      }

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

    // 重置
    resetForm() {
      this.formData = {
        title: '',
        creatorName: [],
        creationTime: [],
      }
    },
    // 删除数据
    deleteRows(selectedRowKeys) {
      const selecteFlowState = this.$refs.riskIdentifyTable.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: '删除失败：存在不是草稿状态的数据',
        })
        return
      }
      let flagName = true
      selecteFlowState.forEach((item) => {
        if (item.contactsName !== getUserInfo().name) {
          flagName = false
        }
      })
      // 如果删除数据识别人非当前用户
      if (!flagName) {
        Modal.info({
          content: '请选择识别人为自己的文件',
        })
        this.selectuser = []
        return
      }
      const ids = []
      const instIds = []
      selecteFlowState.forEach((item) => {
        ids.push(item.id)
        instIds.push(item.instId)
      })
      Modal.confirm({
        title: '你确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          this.loading = true
          const params = {
            ids: ids.join(','),
            instIds: instIds.join(','),
          }
          riskIdentificationService.deletIdentify(params, 'riskIdentify').then((res) => {
            if (res.status === 200) {
              message.success({ content: '删除成功！' }, 1).then(() => {
                this.$refs.riskIdentifyTable.clearSelection()
                this.$refs.riskIdentifyTable.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: 5px;
  right: 0;
  left: 20px;
  z-index: 100;
  width: 50%;
  span {
    color: blue;
  }
}
</style>
