<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        :ref-name="searchform"
        :search-style="{ height: '243px', 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.riskCategoryPath" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="风险事项名称">
              <a-input v-model="formData.eventName" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="风险事项编号">
              <a-input v-model="formData.eventCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'风险应对策略'">
              <sd-select
                v-model="formData.riskResponseStrategy"
                :options="riskResponseStrategy"
                allow-clear
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2003\u2003填报人员'">
              <sd-user-picker v-model="formData.testUserName" :single="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="'\u2003\u2003流程状态'" prop="status">
              <sd-select
                v-model="formData.status"
                :allow-clear="true"
                :options="flowStateOptions"
              />
            </a-form-model-item>
          </a-col>
        </template>
      </audit-advanced-query>
      <sd-data-table
        :key="key"
        ref="riskResponseTable"
        :projectlist="true"
        page-id="risk/task/response/riskResponse"
        :data-url="dataUrl"
        :columns="columns"
        :actions="actions"
        show-selection
        :show-advance-query="true"
        :filter-expressions="expressions"
        :search-fields="['eventName']"
        @searchbtnClick="searchbtnClick"
      >
        <template slot="islink" slot-scope="text, record">
          <a @click="openDoc(record)">{{ text }}</a>
        </template>
        <template slot="select" slot-scope="text, record">
          {{
            text && JSON.parse(text) && typeof JSON.parse(text) === 'object'
              ? JSON.parse(text)[0].name
              : text
          }}
        </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-checkbox v-model="checkboxValue" style="margin-left: 15px" @change="onChange">
            未分配
          </a-checkbox>
        </a-col>
        <!-- 选择人员组件 -->
        <div v-show="false">
          <ic-measure-picker
            ref="riskeventsel"
            v-model="measureSelect"
            :version-id="versionId"
            :org-id="orgId"
            :org-name="orgName + '风险库'"
            :types="'FK'"
            :single="false"
            :read-only="false"
            @change="fnqd"
          ></ic-measure-picker>
          <sd-user-picker
            ref="userSelect"
            v-model="selectuserOpt"
            :single="true"
            :read-only="false"
            @change="userChange"
          />
        </div>
      </div>
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import { Modal, message } from 'ant-design-vue'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import icMeasurePicker from '@product/iam/components/ic-picker/ic-measure-picker.vue'
import riskService from '../../risklib/risk-service'
import riskTasksService from '../risk-tasks-service'
import components from './_import-components/risk-response-list-import'
import axios from '@/common/services/axios-instance'
import FlowcenterService from '@/flowcenter/flowcenter-service'
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'
export default {
  name: 'RiskResponseList',
  metaInfo: {
    title: '风险应对',
  },
  components: {
    ...components,
    auditAdvancedQuery,
    icMeasurePicker,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      yearArry: [],
      waterMark: systemManage.getFormWaterMark(),
      flag: true,
      recordId: '',
      key: 0,
      searchform: 'searchform',
      formData: {
        riskCategoryPath: '',
        eventName: '',
        eventCode: '',
        riskResponseStrategy: null,
        testUserName: null,
        status: null,
      },
      dataUrl: 'api/xcoa-mobile/v1/riskresponse/all-list',
      // ?taskId=' + this.$route.query.taskId,
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '风险分类',
          dataIndex: 'riskCategoryPath',
          width: '100px',
        },
        {
          title: '风险事项编号',
          dataIndex: 'eventCode',
          defaultSortOrder: 'ascend',
          width: '150px',
        },
        {
          title: '风险事项名称',
          dataIndex: 'eventName',
          scopedSlots: { customRender: 'islink' },
          width: '150px',
        },
        {
          title: '风险应对策略',
          dataIndex: 'riskResponseStrategy',
          width: '150px',
        },
        {
          title: '责任部门',
          dataIndex: 'responsibleDeptName',
          width: '100px',
        },
        {
          title: '应对完成状态',
          dataIndex: 'responseCompletionState',
          width: '150px',
        },
        {
          title: '填报人员',
          dataIndex: 'testUserName',
          width: '100px',
        },
        {
          title: '填报日期',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          width: '100px',
        },
        {
          title: '当前状态',
          dataIndex: 'flowState',
          width: '100px',
        },
        { title: '当前处理人', dataIndex: 'currentUser', width: '120px' },
        { dataIndex: 'endType', sdHidden: true },
      ],
      actions: [],
      expressions: [
        {
          dataType: 'long',
          name: 'riskDutiesId',
          op: 'eq',
          longValue: this.$root.$route.query.taskId,
        },
      ],
      formId: 'riskResponse',
      auditMattersPath: '',
      visible: false,
      radioValue: '0',
      radioType: true,
      radioStyle: {},
      measureSelect: [],
      measureSellist: [],
      checkboxValue: false,
      selectuserOpt: [],
      measureList: [],
      versionId: '',
      orgId: '',
      orgName: '',
      taskId: this.$root.$route.query.taskId,
      riskResponseStrategy: [],
      flowStateOptions: [
        { id: '0', name: '起草' },
        { id: '1', name: '审核' },
        { id: '2', name: '结束' },
      ],
    }
  },
  created() {
    const taskId = this.$route.query.taskId
    if (taskId) {
      this.taskId = taskId
    }
    riskTasksService.getRiskTaskInfo(taskId).then((res) => {
      const unitname = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'inspectUnitName'
      )
      const unitid = res.data.pageFormData.pageFieldInfos.findIndex(
        (i) => i.name === 'inspectUnitId'
      )
      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.actions = [
          {
            label: '选择风险事项',
            id: 'new',
            permission: null,
            class: 'ant-btn-primary',
            callback: () => {
              if (this.versionId === '') {
                Modal.info({
                  content: '请配置机构对应的风险库',
                })
              } else {
                this.$refs.riskeventsel.openPicker()
              }
            },
            index: 4,
          },
          {
            label: '分配填报人',
            id: 'set',
            permission: null,
            class: 'ant-btn-primary',
            callback: () => {
              const ids = this.$refs.riskResponseTable.getSelectedRowKeys()
              const records = this.$refs.riskResponseTable.getSelectedRows()
              if (ids.length > 0) {
                let flag = true
                records.forEach((i) => {
                  if (i.flowState !== '起草') {
                    flag = false
                  }
                })
                if (flag) {
                  this.$refs.userSelect.openPicker()
                } else {
                  Modal.info({
                    content: '请选择起草的文件',
                  })
                }
              } else {
                Modal.info({
                  content: '请选择需要设置的文件',
                })
              }
            },
            index: 5,
          },
          {
            label: '删除',
            id: 'delete',
            permission: null,
            class: 'batch',
            callback: (keys) => {
              this.deleteRows()
            },
            index: 6,
          },
        ]
      }
      this.orgName = res.data.pageFormData.pageFieldInfos[unitname].value.toString()
      riskTasksService
        .findIamOrgId(res.data.pageFormData.pageFieldInfos[unitid].value, 'riskLibraryVersion')
        .then((res) => {
          if (res.data) {
            this.orgId = res.data.toString()
            riskService.getversion(this.orgId).then((res) => {
              if (res.data.id) {
                this.versionId = res.data.id.toString()
              }
            })
          }
        })
    })
    this.fngetlist()
    this.initDictionaryInfo()
  },
  methods: {
    initDictionaryInfo() {
      axios({
        url: 'api/xcoa-mobile/v1/iam-law/dictionary?key=RISK_RESPONSE_STRATEGY',
        method: 'get',
      }).then((res) => {
        if (res.status === 200) {
          this.riskResponseStrategy = res.data
        }
      })
    },
    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.riskResponseTable.clearSelection()
    },
    onChange(e) {
      const index = this.expressions.findIndex(
        (i) => i.name === 'testUserName' && i.op === 'is_null'
      )
      if (e.target.checked) {
        // 未分配
        if (index === -1) {
          this.checkboxValue = true
          this.expressions.push({
            dataType: 'str',
            name: 'testUserName',
            op: 'is_null',
          })
        }
      } else {
        this.checkboxValue = false
        if (index > -1) {
          this.expressions.splice(index, 1)
        }
      }
      this.expressions = [...this.expressions]
      this.$refs.riskResponseTable.clearSelection()
    },
    userChange(values) {
      const ids = this.$refs.riskResponseTable.getSelectedRowKeys()
      const accout = values[0].code
      riskTasksService.setResponseTestor(accout, ids).then((data) => {
        if (data) {
          message.success({ content: '处理成功！' }, 1).then(() => {
            this.selectuserOpt = []
            this.refreshDataTable()
          })
        }
      })
    },
    fngetlist() {
      this.measureList = []
      this.measureSellist = []
      riskTasksService.getAllResponseids(this.taskId).then((data) => {
        if (data !== '') {
          if (typeof data === 'number') {
            this.measureList = [data]
          } else {
            this.measureList = data.split(',')
          }
          const obj = []
          this.measureList.forEach((i) => {
            const arr = i.split('$')
            obj.push({
              id: parseInt(arr[0]),
              code: arr[0].toString(),
              text: arr[1],
            })
          })
          this.measureSellist = obj
          this.measureSelect = obj
        } else {
          this.measureSelect = []
        }
      })
    },
    fnqd(data) {
      const ids = []
      data.forEach((i) => {
        let id = i.id.toString()
        if (id.indexOf('1000') > -1) {
          id = id.substring(4, id.length)
        }
        if (this.measureSellist.length > 0) {
          if (this.measureSellist.findIndex((si) => si.id.toString() === i.id.toString()) === -1) {
            ids.push(id)
          }
        } else {
          ids.push(id)
        }
      })
      riskTasksService.saveResponse(this.taskId, ids).then((data) => {
        if (data) {
          message.success({ content: '处理成功！' }, 1).then(() => {
            this.fngetlist()
            this.refreshDataTable()
          })
        }
      })
    },
    // 刷新列表
    refreshDataTable() {
      if (this.$refs.riskResponseTable) {
        this.$refs.riskResponseTable.clearSelection()
        this.$refs.riskResponseTable.refresh()
      }
    },
    openDoc(record) {
      if (record.instId) {
        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()
          }
        })
      } else {
        Modal.confirm({
          title: '提示',
          content: '请先分配填报人员！',
          okText: '确定',
          okType: '取消',
        })
      }
    },
    handleSearch() {
      this.expressions = [
        {
          dataType: 'long',
          name: 'riskDutiesId',
          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.checkboxValue === true) {
        this.expressions.push({
          dataType: 'str',
          name: 'testUserName',
          op: 'is_null',
        })
      }
      // 风险分类
      if (this.formData.riskCategoryPath) {
        this.expressions.push({
          dataType: 'str',
          name: 'riskCategoryPath',
          op: 'like',
          stringValue: '%' + this.formData.riskCategoryPath + '%',
        })
      }
      // 事项名称
      if (this.formData.eventName) {
        this.expressions.push({
          dataType: 'str',
          name: 'eventName',
          op: 'like',
          stringValue: '%' + this.formData.eventName + '%',
        })
      }
      // 事项编号
      if (this.formData.eventCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'eventCode',
          op: 'like',
          stringValue: '%' + this.formData.eventCode + '%',
        })
      }
      // 发起机构
      if (this.formData.riskResponseStrategy && this.formData.riskResponseStrategy.length > 0) {
        this.expressions.push({
          dataType: 'String',
          name: 'riskResponseStrategy',
          op: 'eq',
          stringValue: this.formData.riskResponseStrategy[0].id,
        })
      }
      if (this.formData.testUserName && this.formData.testUserName.length > 0) {
        this.expressions.push({
          dataType: 'String',
          name: 'testUserName',
          op: 'eq',
          stringValue: this.formData.testUserName[0].name,
        })
      }
      if (this.formData.status && this.formData.status.length > 0) {
        this.expressions.push({
          dataType: 'String',
          name: 'flowState',
          op: 'like',
          stringValue: '%' + this.formData.status[0].name + '%',
        })
      }

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

    // 重置
    resetForm() {
      this.formData = {
        riskCategoryPath: '',
        eventName: '',
        eventCode: '',
        riskResponseStrategy: null,
        testUserAccount: null,
        status: null,
      }
    },
    // 删除数据
    deleteRows() {
      const selectedRows = this.$refs.riskResponseTable.getSelectedRows()
      if (selectedRows.length === 0) {
        Modal.info({
          content: '请选择需要删除的文件',
        })
        return
      }
      let flag = false
      selectedRows.forEach((item) => {
        if (item.flowState !== '起草') {
          flag = true
        }
      })
      if (flag) {
        Modal.error({
          title: '删除失败：存在不是草稿状态的数据',
        })
        return
      }
      const ids = []
      const instIds = []
      selectedRows.forEach((item) => {
        if (item.instId === '' || item.instId === null) {
          ids.push(item.id)
        } else {
          instIds.push(item.instId)
        }
      })

      Modal.confirm({
        title: '您确定删除这项内容吗？',
        content: '删除数据后，就无法恢复初始的状态。',
        okText: '删除',
        cancelText: '取消',
        okType: 'danger',
        onOk: () => {
          const params = {
            ids: ids.join(','),
            instIds: instIds.join(','),
          }
          riskTasksService.deleteresponse(params, this.formId).then((res) => {
            if (res.status === 200) {
              message.success({ content: '删除成功！' }, 1).then(() => {
                this.fngetlist()
                this.refreshDataTable()
              })
            }
          })
        },
      })
    },
  },
}
</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>
