<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      @actionBtnClick="actionBtnClick"
      @saveproject="saveproject"
      @afterDispatch="afterDispatch"
    >
      <template v-slot:form="{ model, fields, FlowData }">
        <table>
          <tr>
            <td style="border: none">
              <audit-advanced-group
                :expand="Expand"
                :expand-str="'Expand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="Expand">
          <tr v-show="initData(model, fields)">
            <!-- ID -->
            <sd-form-item-td name="id" />
            <!-- 随机ID -->
            <sd-form-item-td name="riskDutiesId" />
          </tr>
          <tr>
            <!-- 风险分类 -->
            <sd-form-item-td name="riskCategoryPath">
              {{ model.riskCategoryPath }}
            </sd-form-item-td>
            <!-- 风险事项编号 -->
            <sd-form-item-td name="eventCode">
              {{ model.eventCode }}
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 风险事项名称 -->
            <sd-form-item-td name="eventName">
              {{ model.eventName }}
            </sd-form-item-td>
            <!-- 测试结果 -->
            <!-- <sd-form-item-td name="testResult" /> -->
          </tr>
          <tr>
            <!-- 风险事项描述 -->
            <sd-form-item-td name="eventDesc" :colspan="3">
              <a-textarea v-model="model.eventDesc" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 发生可能性 -->
            <td class="ant-form-item-label ant-form-item-label">
              <div style="float:right">
                <a-tooltip>
                  <template v-slot:title>
                    <span style="white-space:pre-wrap;"
                      ><p class="text">{{ fxknprops }}</p></span
                    ></template
                  >
                  <a-icon type="info-circle" /> </a-tooltip
              ></div>
              <label
                title="发生可能性(P)"
                :class="
                  FlowData.mode === 'EDIT' && !fields.responseCompletionState.readonly
                    ? 'ant-form-item-required'
                    : ''
                "
              >
                发生可能性(P)
              </label>
            </td>
            <sd-form-item-td name="occurPossibility" :label="null">
              <template v-slot:read-and-edit="{ editable }">
                <span v-if="!editable">{{
                  model.occurPossibility &&
                  JSON.parse(model.occurPossibility) &&
                  typeof JSON.parse(model.occurPossibility) === 'object'
                    ? JSON.parse(model.occurPossibility)[0].name
                    : model.occurPossibility
                }}</span>
                <sd-select
                  v-else
                  v-model="model.occurPossibility"
                  :options="occurPossibility"
                  style="width:95%"
                  @change="changefz"
                />
              </template>
            </sd-form-item-td>
            <!-- 风险影响程度 -->
            <td class="ant-form-item-label ant-form-item-label">
              <div style="float:right">
                <a-tooltip slot="suffix">
                  <template v-slot:title>
                    <span style="white-space:pre-wrap;"
                      ><p class="text">{{ fxyxprops }}</p></span
                    ></template
                  >
                  <a-icon type="info-circle" /> </a-tooltip
              ></div>
              <label
                title="风险影响程度(C)"
                :class="
                  FlowData.mode === 'EDIT' && !fields.responseCompletionState.readonly
                    ? 'ant-form-item-required'
                    : ''
                "
              >
                风险影响程度(C)
              </label>
            </td>
            <sd-form-item-td name="riskImpactDegree" :label="null">
              <template v-slot:read-and-edit="{ editable }">
                <span v-if="!editable">{{
                  model.riskImpactDegree &&
                  JSON.parse(model.riskImpactDegree) &&
                  typeof JSON.parse(model.riskImpactDegree) === 'object'
                    ? JSON.parse(model.riskImpactDegree)[0].name
                    : model.riskImpactDegree
                }}</span>
                <sd-select
                  v-else
                  v-model="model.riskImpactDegree"
                  :options="riskImpactDegree"
                  @change="changefz"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 固有风险分值 -->
            <sd-form-item-td name="inherentRiskScore">{{
              model.inherentRiskScore
            }}</sd-form-item-td>
            <!-- 控制水平 -->
            <sd-form-item-td name="controlLevel" @change="changefz" />
          </tr>
          <tr>
            <!-- 控制水平系数 -->
            <sd-form-item-td name="controlLevelCoefficient">{{
              model.controlLevelCoefficient
            }}</sd-form-item-td>
            <!-- 剩余风险分值 -->
            <sd-form-item-td name="residualRiskScore">{{
              model.residualRiskScore
            }}</sd-form-item-td>
          </tr>
          <tr>
            <!-- 风险等级 -->
            <sd-form-item-td name="riskLevel">{{ model.riskLevel }}</sd-form-item-td>
            <!-- 未来风险趋势 -->
            <sd-form-item-td name="riskTrend" />
          </tr>
          <tr v-show="false"><sd-form-item-td name="riskDimension"/></tr>
          <tr v-show="false"
            ><sd-form-item-td name="occurPossibilityNum"/><sd-form-item-td
              name="riskImpactDegreeNum"
          /></tr>
          <tr>
            <!-- 是否应对 -->
            <sd-form-item-td
              name="isAnswer"
              :input-props="{ defaultValue: 'no' }"
              @change="changesfyd"
            />
            <!-- 评估人员 -->
            <sd-form-item-td name="testUserName" :label="'评估人员'">
              {{ model.testUserName }}
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 评估日期 -->
            <sd-form-item-td
              name="evaluationTime"
              :colspan="3"
              :input-props="{ defaultValue: evaluationTime }"
            />
          </tr>
          <tr>
            <!-- 备注 -->
            <sd-form-item-td name="remark" :colspan="3">
              <a-textarea v-model="model.remark" :rows="3" />
            </sd-form-item-td>
          </tr>
        </table>

        <table v-if="model.isAnswer === 'yes'">
          <tr>
            <td style="border: none">
              <audit-advanced-group
                :expand="YdExpand"
                :expand-str="'YdExpand'"
                :group-label="'应对信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
          <tr v-if="YdExpand"
            ><td style="border: none">
              <table
                v-if="FlowData.mode === 'EDIT' && !fields.responseCompletionState.readonly"
                style="width:100%"
              >
                <tr>
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="风险应对策略" class="ant-form-item-required">
                      风险应对策略
                    </label>
                  </td>
                  <!-- 风险应对策略 -->
                  <sd-form-item-td name="riskResponseStrategy" :label="null">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="riskResponseStrategy"
                    >
                      <a-input v-model="model.riskResponseStrategy"></a-input>
                    </a-form-model-item>
                  </sd-form-item-td>
                  <!-- 责任部门 -->
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="责任部门" class="ant-form-item-required"> 责任部门 </label>
                  </td>
                  <sd-form-item-td name="responsibleDeptName" :label="null">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="responsibleDeptName"
                    >
                      <a-input v-model="model.responsibleDeptName"></a-input>
                    </a-form-model-item>
                  </sd-form-item-td>
                </tr>
                <tr>
                  <!-- 应对措施 -->
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="应对措施" class="ant-form-item-required"> 应对措施 </label>
                  </td>
                  <sd-form-item-td name="riskResponseMeasures" :label="null" :colspan="3">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="riskResponseMeasures"
                    >
                      <a-textarea v-model="model.riskResponseMeasures" :rows="3" />
                    </a-form-model-item>
                  </sd-form-item-td>
                </tr>
                <tr>
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="应对完成情况描述" class="ant-form-item-required">
                      应对完成情况描述
                    </label>
                  </td>
                  <!-- 应对完成情况描述 -->
                  <sd-form-item-td name="responseCompletionDesc" :label="null" :colspan="3">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="responseCompletionDesc"
                    >
                      <a-textarea v-model="model.responseCompletionDesc" :rows="3" />
                    </a-form-model-item>
                  </sd-form-item-td>
                </tr>
                <tr>
                  <!-- 应对完成状态 -->
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="应对完成状态" class="ant-form-item-required">
                      应对完成状态
                    </label>
                  </td>
                  <sd-form-item-td name="responseCompletionState" :label="null">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="responseCompletionState"
                    >
                      <sd-select
                        v-model="model.responseCompletionState"
                        :options="responseCompletionStateoptions"
                      ></sd-select>
                    </a-form-model-item>
                  </sd-form-item-td>
                  <!-- 应对人员 -->
                  <sd-form-item-td name="responsePersonOpt">
                    <sd-user-picker v-model="model.responsePersonOpt" @change="changeuser" />
                  </sd-form-item-td>
                </tr>
                <tr>
                  <!-- 人员所属单位 -->
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="人员所属单位" class="ant-form-item-required">
                      人员所属单位
                    </label>
                  </td>
                  <sd-form-item-td name="responsibleDeptOpt" :label="null">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="responsibleDeptOpt"
                    >
                      <sd-group-picker
                        v-model="model.responsibleDeptOpt"
                        @change="changedept"
                      ></sd-group-picker>
                    </a-form-model-item>
                  </sd-form-item-td>
                  <!-- 应对日期 -->
                  <td class="ant-form-item-label ant-form-item-label">
                    <label title="应对日期" class="ant-form-item-required"> 应对日期 </label>
                  </td>
                  <sd-form-item-td name="responseTime" :label="null">
                    <a-form-model-item
                      :rules="[
                        {
                          required: true,
                          trigger: ['change', 'blur'],
                        },
                      ]"
                      prop="responseTime"
                      ><a-date-picker v-model="model.responseTime" />
                    </a-form-model-item>
                  </sd-form-item-td>
                </tr>
                <tr v-show="false">
                  <sd-form-item-td name="responsePersonName"/>
                  <sd-form-item-td name="responsibleDeptName"
                /></tr>
                <tr>
                  <!-- 附件 -->
                  <sd-form-item-td name="attachment" :colspan="3" />
                </tr>
              </table>

              <table v-else style="width:100%">
                <tr>
                  <!-- 风险应对策略 -->
                  <sd-form-item-td name="riskResponseStrategy"
                    ><template v-slot:read-and-edit>
                      {{ model.riskResponseStrategy }}</template
                    ></sd-form-item-td
                  >
                  <!-- 责任部门 -->
                  <sd-form-item-td name="responsibleDeptName" :label="'责任部门'">{{
                    model.responsibleDeptName
                  }}</sd-form-item-td>
                </tr>
                <tr>
                  <!-- 应对措施 -->
                  <sd-form-item-td name="riskResponseMeasures" :colspan="3">
                    {{ model.riskResponseMeasures }}
                  </sd-form-item-td>
                </tr>
                <tr>
                  <!-- 应对完成情况描述 -->
                  <sd-form-item-td name="responseCompletionDesc" :colspan="3">
                    {{ model.responseCompletionDesc }}
                  </sd-form-item-td>
                </tr>
                <tr>
                  <!-- 应对完成状态 -->
                  <sd-form-item-td name="responseCompletionState">
                    <template v-slot:read-and-edit="{ editable }">{{
                      model.responseCompletionState && JSON.parse(model.responseCompletionState)
                        ? JSON.parse(model.responseCompletionState)[0].name
                        : model.responseCompletionState
                    }}</template></sd-form-item-td
                  >
                  <!-- 应对人员 -->
                  <sd-form-item-td name="responsePersonOpt">{{
                    model.responsePersonName
                  }}</sd-form-item-td>
                </tr>
                <tr>
                  <!-- 人员所属单位 -->
                  <sd-form-item-td name="responsibleDeptOpt">{{
                    model.responsePersonDeptName
                  }}</sd-form-item-td>
                  <!-- 应对日期 -->
                  <sd-form-item-td name="responseTime">{{ model.responseTime }}</sd-form-item-td>
                </tr>
                <tr>
                  <!-- 附件 -->
                  <sd-form-item-td name="attachment" :colspan="3">
                    <template v-slot:read-and-edit>
                      <sd-attachment
                        v-model="model.attachment"
                        :group-id="JSON.parse(fields.attachment.value).value"
                        :read-only="true"
                      />
                    </template>
                  </sd-form-item-td>
                </tr>
              </table> </td></tr
        ></table>
      </template>
    </sd-webflow>
  </div>
</template>

<script>
import moment from 'moment'
import { Modal, message } from 'ant-design-vue'
import riskTasksService from '../risk-tasks-service'
import auditAdvancedGroup from '../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../components/audit-advanced-group-mixins'
import components from './_import-components/risk-assessment-form-import'

export default {
  name: 'RiskAssessmentForm',
  metaInfo: {
    title: '风险评估',
  },
  components: {
    ...components,
    auditAdvancedGroup,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      Expand: true,
      YdExpand: true,
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'sourceId', sdHidden: true },
        {
          dataIndex: 'stepName',
          title: '步骤名称',
          width: '30%',
        },
        { dataIndex: 'stepReason', title: '步骤说明', width: '30%' },
        {
          title: '附件',
          dataIndex: 'attachment',
        },
      ],
      infocolumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'sourceId', sdHidden: true },
        {
          dataIndex: 'sampleName',
          title: '样本名称',
          width: '30%',
        },
        { dataIndex: 'sampleDesc', title: '样本描述', width: '30%' },
        {
          title: '附件',
          dataIndex: 'attachment',
        },
      ],
      orgId: null,
      versionId: null,
      flag: true,
      occurPossibility: [],
      riskImpactDegree: [],
      riskLevel: [],
      taskId: '',
      fxknprops: '',
      fxyxprops: '',
      responseCompletionStateoptions: [],
    }
  },
  computed: {
    evaluationTime() {
      return moment(new Date())
    },
  },
  // created(){
  // },
  methods: {
    sdFormReady() {
      this.mode = this.$refs.flow.formData.mode
    },
    initData(model, fields) {
      if (this.flag) {
        this.flag = false
        const taskId = model.riskDutiesId
        if (taskId) {
          this.taskId = taskId
        }
        this.occurPossibility = []
        this.riskImpactDegree = []
        riskTasksService.getRiskTaskInfo(taskId).then((res) => {
          const riskCriteriaId = res.data.pageFormData.pageFieldInfos.findIndex(
            (i) => i.name === 'riskCriteriaId'
          )
          riskTasksService
            .getRiskCriteriaInfo(res.data.pageFormData.pageFieldInfos[riskCriteriaId].value)
            .then((res) => {
              const fskn = res.data.pageFormData.pageFieldInfos.findIndex(
                (i) => i.name === 'riskPossibilityEntitys'
              )
              const fxyx = res.data.pageFormData.pageFieldInfos.findIndex(
                (i) => i.name === 'riskDegreeEntitys'
              )
              const fxdj = res.data.pageFormData.pageFieldInfos.findIndex(
                (i) => i.name === 'riskLevelEntitys'
              )
              let value = res.data.pageFormData.pageFieldInfos[fskn].value
              if (value && value !== '[]') {
                const valueobj = JSON.parse(value)
                valueobj.forEach((f, index) => {
                  const obj = {
                    id: index + 1,
                    name: f.definition,
                  }
                  this.fxknprops += obj.name + ' :' + obj.id.toString() + '\n\r'
                  this.occurPossibility.push(obj)
                })
                if (this.fxknprops !== '') {
                  this.fxknprops = this.fxknprops.substring(0, this.fxknprops.length - 2)
                }
              }
              value = res.data.pageFormData.pageFieldInfos[fxyx].value
              if (value && value !== '[]') {
                const valueobj = JSON.parse(value)
                for (var i = 1; i < 6; i++) {
                  if (valueobj[0]['score' + i] !== '') {
                    const obj = {
                      id: i,
                      name: valueobj[0]['score' + i],
                    }
                    this.fxyxprops += obj.name + ' :' + obj.id.toString() + '\r\n'
                    this.riskImpactDegree.push(obj)
                  }
                }
                if (this.fxyxprops !== '') {
                  this.fxyxprops = this.fxyxprops.substring(0, this.fxyxprops.length - 2)
                }
              }
              value = res.data.pageFormData.pageFieldInfos[fxdj].value
              if (value && value !== '[]') {
                const valueobj = JSON.parse(value)
                valueobj.forEach((f, index) => {
                  const obj = {
                    dj: f.riskLevel,
                    min: f.maxNum,
                    max: f.minNum,
                  }
                  this.riskLevel.push(obj)
                })
              }
            })
        })
        this.responseCompletionStateoptions = []
        fields.responseCompletionState.attr.selectListItem.forEach((i) => {
          this.responseCompletionStateoptions.push({
            id: i.value,
            name: i.label,
          })
        })
      }
      return false
    },
    changedept(value) {
      let deptname = ''
      if (value) {
        value.forEach((d) => {
          deptname += ',' + d.name
        })
        if (deptname !== '') deptname = deptname.substring(1, deptname.length)
        this.$refs.flow.setFieldValue('responsePersonDeptName', deptname)
      }
    },
    changeuser(value) {
      let name = ''
      if (value) {
        value.forEach((d) => {
          name += ',' + d.name
        })
        if (name !== '') name = name.substring(1, name.length)
        this.$refs.flow.setFieldValue('responsePersonName', name)
      }
    },
    changefz() {
      // 发生可能
      const fskn = this.$refs.flow.getFieldValue('occurPossibility')
      // 风险影响
      const fxyx = this.$refs.flow.getFieldValue('riskImpactDegree')
      let gyfx = 0
      let fxdj = ''
      if (fskn && fxyx && fskn.length > 0 && fxyx.length > 0) {
        gyfx = fskn[0].id * fxyx[0].id
        fxdj = gyfx
        this.$refs.flow.setFieldValue('occurPossibilityNum', fskn[0].id.toString())
        this.$refs.flow.setFieldValue('riskImpactDegreeNum', fxyx[0].id.toString())
        const fxdjobj = this.riskLevel.find(
          (i) => fxdj >= parseFloat(i.max) && fxdj <= parseFloat(i.min)
        )

        if (fxdjobj) {
          this.$refs.flow.setFieldValue('riskDimension', fxdjobj.dj)
        } else {
          this.$refs.flow.setFieldValue('riskDimension', '')
        }
      }
      this.$refs.flow.setFieldValue('inherentRiskScore', (Math.round(gyfx * 100) / 100).toString())
      const kzsp = this.$refs.flow.getFieldValue('controlLevel')
      if (kzsp) {
        this.$refs.flow.setFieldValue(
          'controlLevelCoefficient',
          (Math.round(kzsp * 100) / 100).toString()
        )
        const syfx = parseFloat(kzsp) * gyfx
        fxdj = syfx
        this.$refs.flow.setFieldValue(
          'residualRiskScore',
          (Math.round(syfx * 100) / 100).toString()
        )
      }
      // const obj = this.riskLevel.find((i) => fxdj >= i.min && fxdj <= i.max)
      const obj = this.riskLevel.find((i) => fxdj >= parseFloat(i.max) && fxdj <= parseFloat(i.min))
      if (obj) {
        this.$refs.flow.setFieldValue('riskLevel', obj.dj)
      } else {
        this.$refs.flow.setFieldValue('riskLevel', '')
      }
    },
    changesfyd() {
      const sfyd = this.$refs.flow.getFieldValue('isAnswer')
      if (sfyd === 'no') {
        // 应对信息 清空
        this.$refs.flow.setFieldValue('riskResponseStrategy', '')
        this.$refs.flow.setFieldValue('riskResponseMeasures', '')
        this.$refs.flow.setFieldValue('responsibleDeptName', '')
        this.$refs.flow.setFieldValue('responsePersonName', '')
        this.$refs.flow.setFieldValue('responseCompletionState', null)
        this.$refs.flow.setFieldValue('responseTime', '')
        this.$refs.flow.setFieldValue('responseCompletionDesc', '')
        this.$refs.flow.setFieldValue('responsePersonDeptName', '')
      }
    },
    actionBtnClick(evt, { button, FlowData }) {
      if (button.fakeId === 'save') {
      }
    },
    // 保存操作，记录标识位
    saveproject() {
      this.isSave = true
    },
    /**
     * 提交后事件
     */
    afterDispatch() {
      // 提交也认为是保存
      this.isSave = true
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
