<template>
  <div :class="$style.wrapHeight">
    <a-card>
      <!-- 高级搜索组件 -->
      <audit-advanced-query
        :expand="expand"
        :search-data="formData"
        ref-name="searchform"
        :search-style="{ height: '275px' }"
        :search-fun="handleSearch"
        @searchedClick="searchedClick"
        @resetForm="resetForm"
      >
        <template>
          <a-form-model :rules="rules">
            <a-col :span="12">
              <a-form-model-item :label="'\u2003\u2003\u2002风险事项编号'">
                <a-input v-model="formData.eventCode" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="'\u2003\u2002风险事项名称'">
                <a-input v-model="formData.eventName" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="'\u2003\u2003\u2003\u2003\u2002风险等级'">
                <a-select
                  v-model="formData.eventLevel"
                  label-in-value
                  :options="levelDict"
                  allow-clear
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="'发生可能性（P）'">
                <a-select
                  v-model="formData.possibility"
                  label-in-value
                  :options="possibilityDict"
                  allow-clear
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item :label="'风险影响程度（C）'">
                <a-select
                  v-model="formData.degree"
                  label-in-value
                  :options="degreeDict"
                  allow-clear
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item ref="gy" :label="'\u2003\u2002固有风险分值'" prop="gy">
                <a-input-number
                  v-model="formData.gyMin"
                  :class="$style.number"
                  :min="0"
                  :max="100"
                />~<a-input-number
                  v-model="formData.gyMax"
                  :class="$style.number"
                  :min="0"
                  :max="100"
                  @blur="
                    () => {
                      $refs.gy.onFieldBlur()
                    }
                  "
                  @change="
                    () => {
                      $refs.gy.onFieldChange()
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item ref="sy" :label="'\u2003\u2003\u2002剩余风险分值'" prop="sy">
                <a-input-number
                  v-model="formData.syMin"
                  :class="$style.number"
                  :min="0"
                  :max="100"
                />~<a-input-number
                  v-model="formData.syMax"
                  :class="$style.number"
                  :min="0"
                  :max="100"
                  @blur="
                    () => {
                      $refs.sy.onFieldBlur()
                    }
                  "
                  @change="
                    () => {
                      $refs.sy.onFieldChange()
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
          </a-form-model>
        </template>
      </audit-advanced-query>
      <div :class="$style.tableDiv">
        <sd-data-table
          v-if="loading"
          :key="controlKey"
          ref="dataTable"
          row-key="ID"
          :data-url="dataUrl"
          :columns="columns"
          form-id=""
          page-id=""
          :filter-expressions="expressions"
          :process-req="processReq"
          :search-fields="['EVENT_CODE', 'EVENT_NAME']"
          :show-advance-query="true"
          @searchbtnClick="searchbtnClick"
        >
          <template slot="islink" slot-scope="text, record">
            <a @click="openDoc(record)">{{ text }}</a>
          </template>
        </sd-data-table>
      </div>
    </a-card>
  </div>
</template>

<script>
import { Modal } from '@/common/one-ui'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { getUserInfo } from '@/common/store-mixin'
import auditAdvancedQuery from '@product/iam/components/audit-advanced-query.vue'
import auditAdvancedQueryMixins from '@product/iam/components/audit-advanced-query-mixins'
import systemManage from '@/system-manage/system-manage'
import riskTasksService from '../risk-tasks-service'
import components from './_import-components/risk-assessment-map-list-import'
const columns = [
  {
    title: '序号',
    customRender: (text, record, index) => `${index + 1}`,
    width: '80px',
  },
  {
    title: '风险事项编号',
    dataIndex: 'EVENT_CODE',
    scopedSlots: { customRender: 'islink' },
  },
  {
    title: '风险事项名称',
    dataIndex: 'EVENT_NAME',
  },

  {
    title: '风险等级',
    dataIndex: 'RISK_LEVEL',
    sorter: true,
    defaultSortOrder: 'ascend',
  },
  {
    title: '发生可能性（P）',
    dataIndex: 'OCCUR_POSSIBILITY',
    customRender: (text) => {
      return JSON.parse(text)[0].name
    },
    sorter: true,
  },
  {
    title: '风险影响程度（C）',
    dataIndex: 'RISK_IMPACT_DEGREE',
    customRender: (text) => {
      return JSON.parse(text)[0].name
    },
    sorter: true,
  },
  {
    title: '固有风险值',
    dataIndex: 'INHERENT_RISK_SCORE',
    sorter: true,
  },
  {
    title: '控制水平系数',
    dataIndex: 'CONTROL_LEVEL_COEFFICIENT',
  },
  {
    title: '剩余风险值',
    dataIndex: 'RESIDUAL_RISK_SCORE',
    sorter: true,
  },
]
export default {
  name: 'RiskAssessmentMapList',
  metaInfo: {
    title: '风险图谱查询列表',
  },
  components: {
    auditAdvancedQuery,
    ...components,
  },
  mixins: [auditAdvancedQueryMixins],
  data() {
    return {
      formData: {},
      loading: false,
      possibilityDict: [], // 发生可能性dict
      degreeDict: [], // 影响程度dict
      levelDict: [
        { label: '高风险', value: '高风险' },
        { label: '中风险', value: '中风险' },
        { label: '低风险', value: '低风险' },
      ],
      rules: {
        gy: [{ validator: this.checkMinMax, trigger: ['blur', 'change'] }],
        sy: [{ validator: this.checkMinMax, trigger: ['blur', 'change'] }],
      },
      columns,
      waterMark: systemManage.getFormWaterMark(),
      controlKey: 0,
      expressions: [],
      dataUrl: '',
      listType: '',
      recordValue: '',
      riskDimension: '',
      userAccount: null,
      params: {},
      loadCross: false,
      mtxPrcPathData: {},
    }
  },
  mounted() {
    // 获取影响程度和发生可能性
    riskTasksService
      .getRiskTaskInfo(parseFloat(this.$route.query.taskId))
      .then((res) => {
        const riskCriteriaId = res.data.pageFormData.pageFieldInfos.find((item) => {
          return item.name === 'riskCriteriaId'
        }).value
        return riskTasksService.getRiskCriteriaInfo(parseFloat(riskCriteriaId))
      })
      .then((res) => {
        // 发生可能性 riskPossibilityEntitys 横向
        const riskPossibilityEntitys = res.data.pageFormData.pageFieldInfos.find((item) => {
          return item.name === 'riskPossibilityEntitys'
        }).value
        const riskPossibilityEntitysObj = JSON.parse(riskPossibilityEntitys)
        this.possibilityDict.push({
          label: riskPossibilityEntitysObj[0].definition,
          value: 1,
        })
        this.possibilityDict.push({
          label: riskPossibilityEntitysObj[1].definition,
          value: 2,
        })
        this.possibilityDict.push({
          label: riskPossibilityEntitysObj[2].definition,
          value: 3,
        })
        this.possibilityDict.push({
          label: riskPossibilityEntitysObj[3].definition,
          value: 4,
        })
        this.possibilityDict.push({
          label: riskPossibilityEntitysObj[4].definition,
          value: 5,
        })
        // 风险影响程度 riskDegreeEntitys  纵向
        const riskDegreeEntitys = res.data.pageFormData.pageFieldInfos.find((item) => {
          return item.name === 'riskDegreeEntitys'
        }).value
        const riskDegreeEntitysObj = JSON.parse(riskDegreeEntitys)
        this.degreeDict.push({
          label: riskDegreeEntitysObj[0].score1,
          value: 1,
        })
        this.degreeDict.push({
          label: riskDegreeEntitysObj[0].score2,
          value: 2,
        })
        this.degreeDict.push({
          label: riskDegreeEntitysObj[0].score3,
          value: 3,
        })
        this.degreeDict.push({
          label: riskDegreeEntitysObj[0].score4,
          value: 4,
        })
        this.degreeDict.push({
          label: riskDegreeEntitysObj[0].score5,
          value: 5,
        })
      })
    this.taskId = this.$route.query.taskId
    this.listType = this.$route.query.listType
    this.dataUrl = 'api/xcoa-mobile/v1/risk-map/getTaskSurveyList'
    if (this.listType === 'left') {
      this.occurPossibilityNum = this.$route.query.occurPossibilityNum // x
      this.riskImpactDegreeNum = this.$route.query.riskImpactDegreeNum // y
      this.params = {
        taskId: this.taskId,
        columnValue: 'riskMapDrill',
        occurPossibilityNum: this.occurPossibilityNum,
        riskImpactDegreeNum: this.riskImpactDegreeNum,
      }
    }
    if (this.listType === 'right') {
      this.recordValue = this.$route.query.recordValue // recordValue
      this.riskDimension = this.$route.query.riskDimension
      this.params = {
        taskId: this.taskId,
        columnValue: 'riskMapDrill',
        recordValue: this.recordValue,
        riskDimension: this.riskDimension,
      }
      if (this.recordValue === '合计') {
        this.params = {
          taskId: this.taskId,
          columnValue: 'riskMapDrill',
          riskDimension: this.riskDimension,
        }
      }
    }
    // 最后显示，否则会有多余报错
    this.loading = true
  },
  methods: {
    // 判断大小值
    checkMinMax(rule, val, callback) {
      let min, max
      if (rule.field === 'gy') {
        min = this.formData.gyMin ? this.formData.gyMin : 0
        max = this.formData.gyMax ? this.formData.gyMax : 0
      }
      if (rule.field === 'sy') {
        min = this.formData.syMin ? this.formData.syMin : 0
        max = this.formData.syMax ? this.formData.syMax : 0
      }
      if (min > max && max !== 0) {
        callback('最大值不能小于最小值')
      } else {
        callback()
      }
    },
    // 获取字典值
    getDictValue(list, val) {
      const valList = []
      val.split(',').forEach((valItem) => {
        valList.push(
          list.find((item) => {
            return item.value.trim() === valItem.trim()
          })?.label
        )
      })
      return valList.join(',')
    },
    // 获取单值
    getOneDictValue(list, val) {
      return list.find((item) => {
        return item.value === val
      })?.label
    },
    // 控制请求处理
    processReq(req) {
      const maxNum = req.data.maxResults
      const startNum = req.data.startPosition
      const exp = req.data.expressions
      const orderBy = req.data.orderBy
      req.data = this.params
      req.data.expressions = exp
      req.data.orderBy = orderBy
      req.data.maxResults = maxNum
      req.data.startPosition = startNum
      return req
    },
    handleSearch() {
      this.expressions = []
      // 事项编号
      if (this.formData.eventCode) {
        this.expressions.push({
          dataType: 'str',
          name: 'eventCode',
          op: 'like',
          stringValue: '%' + this.formData.eventCode + '%',
        })
      }
      // 事项名称
      if (this.formData.eventName) {
        this.expressions.push({
          dataType: 'str',
          name: 'eventName',
          op: 'like',
          stringValue: '%' + this.formData.eventName + '%',
        })
      }
      // 风险级别
      if (this.formData.eventLevel) {
        this.expressions.push({
          dataType: 'String',
          name: 'riskLevel',
          op: 'eq',
          stringValue: this.formData.eventLevel.label,
        })
      }
      // 发生可能性
      if (this.formData.possibility) {
        this.expressions.push({
          dataType: 'String',
          name: 'occurPossibility',
          op: 'like',
          stringValue: '%' + this.formData.possibility.label + '%',
        })
      }
      // 影响程度
      if (this.formData.degree) {
        this.expressions.push({
          dataType: 'String',
          name: 'riskImpactDegree',
          op: 'like',
          stringValue: '%' + this.formData.degree.label + '%',
        })
      }
      // 固有风险值
      if (this.formData.gyMin | this.formData.gyMax) {
        const minNum =
          (this.formData.gyMin === null) | (this.formData.gyMin === undefined)
            ? 0
            : this.formData.gyMin
        const maxNum =
          (this.formData.gyMax === null) | (this.formData.gyMax === undefined)
            ? 100
            : this.formData.gyMax
        this.expressions.push({
          dataType: 'double',
          name: 'inherentRiskScore',
          op: 'between',
          doubleValues: [minNum, maxNum],
        })
      }
      // 剩余风险值
      if (this.formData.syMin | this.formData.syMax) {
        const minNum =
          (this.formData.syMin === null) | (this.formData.syMin === undefined)
            ? 0
            : this.formData.syMin
        const maxNum =
          (this.formData.syMax === null) | (this.formData.syMax === undefined)
            ? 100
            : this.formData.syMax
        this.expressions.push({
          dataType: 'double',
          name: 'residualRiskScore',
          op: 'between',
          doubleValues: [minNum, maxNum],
        })
      }
      this.expressions = [...this.expressions]
    },

    // 重置
    resetForm() {
      this.formData = {}
    },

    openDoc(record) {
      if (record.INST_ID) {
        let openurl = ''
        const loginUser = getUserInfo()
        if (
          (record.FLOW_STATE === '起草') |
          (record.FLOW_STATE === '开始') |
          (record.FLOW_STATE === null)
        ) {
          if (loginUser.name === record.CURRENT_USER) {
            openurl = '/sd-webflow/pages/draft/' + record.INST_ID
          } else {
            openurl = '/sd-webflow/done-pages/' + record.INST_ID
          }
        } else {
          openurl = '/sd-webflow/done-pages/' + record.INST_ID
        }
        crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
          if (refreshFlag) {
            // 这里写或者调刷新的方法
            this.refreshDataTable()
          }
        })
      } else {
        Modal.confirm({
          title: '提示',
          content: '请先分配评估人员！',
          okText: '确定',
          okType: '取消',
        })
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  .number {
    width: 20% !important;
  }
  height: 100%;
  .table-div {
    min-height: 450px;
  }
  .table-title {
    position: absolute;
    font-size: 17px;
    font-weight: bold;
    color: #44a5ff;
    margin: 0 3px;
  }
  :global(.ant-form-item-control-wrapper) {
    width: calc(100% - 170px) !important;
  }
}
</style>
