<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="this.$route.query.mode ? null : saveForm"
      :form-data="mode"
      @handelSaveForm="saveForm"
    >
      <a-spin :spinning="spinning" tip="加载数据中...">
        <sd-detail-form
          ref="docform"
          page-id="risk/task/identify/riskIdentifyUpdateMatter"
          :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
          :class="$style.form"
          :read-only="this.$route.query.mode ? true : false"
          @close="close(true)"
          @saved="saved"
          @sdFormReady="sdFormReady"
        >
          <template v-slot="{ model, fields }">
            <table
              ><tr
                ><td style="padding-left:5px;border:none">
                  <audit-advanced-group
                    :expand="expandA"
                    :expand-str="'expandA'"
                    :group-label="'基本信息'"
                    tablestyle="''"
                    @changedClick="changedClick"
                  ></audit-advanced-group> </td></tr
            ></table>

            <table v-show="expandA">
              <colgroup>
                <col style="width: 15%;"/>
                <col style="width: 35%;"/>
                <col style="width: 15%;"/>
                <col style="width: 35%;"
              /></colgroup>
              <tr v-show="false">
                <sd-form-item-td name="riskCategoryId" />
                <sd-form-item-td name="auditOrgId" />
                <sd-form-item-td name="randomId" />
                <sd-form-item-td name="eventId" />
              </tr>
              <tr v-show="false"
                ><sd-form-item-td name="versionId" /><sd-form-item-td name="id" />
              </tr>
              <tr
                ><sd-form-item-td name="riskCategoryPath" :colspan="3" :label="'风险分类'">
                  <a-input
                    v-model="model.riskCategoryPath"
                    style="width:calc(100% - 80px);"
                    read-only
                  />
                  <span style="padding:5px">
                    <a-button @click="showflpath">选择</a-button>
                  </span>
                </sd-form-item-td></tr
              >
              <tr>
                <!-- 措施编号 -->
                <sd-form-item-td name="eventCode" />
                <!-- 措施名称 -->
                <sd-form-item-td name="eventName"> </sd-form-item-td>
              </tr>
              <tr>
                <!-- 措施描述 -->
                <sd-form-item-td name="eventDesc" :colspan="3">
                  <a-textarea v-model="model.eventDesc" :rows="3" />
                </sd-form-item-td>
              </tr>
              <tr>
                <sd-form-item-td
                  name="riskSource"
                  :input-props="{
                    defaultValue: 'within',
                  }"
                />

                <td class="ant-form-item-label">
                  <label title="主管部门" :class="{ 'ant-form-item-required': !$route.query.mode }">
                    主管部门
                  </label>
                </td>
                <sd-form-item-td name="competentDeptOpt" :label="null">
                  <template v-slot:read-and-edit="{ editable }">
                    <div v-if="editable">
                      <sd-group-picker
                        v-show="false"
                        v-model="model.competentDeptOpt"
                        style="width:calc(100% - 120px)"
                        @change="changecompetentDept"
                      />
                      <sd-group-picker
                        v-model="competentDeptOpt"
                        style="width:calc(100% - 120px)"
                      />
                      <a-input v-show="false" v-model="model.competentDeptName" />
                      <a-input v-show="false" v-model="model.competentDeptId" />
                      <a-button
                        type="primary"
                        icon="plus"
                        block
                        style="width:110px;margin-left:5px;"
                        @click="manualEntry('competentDeptOpt', 'docform')"
                      >
                        手工添加
                      </a-button>
                    </div>
                    <div v-else>{{ model.competentDeptName }}</div>
                  </template>
                </sd-form-item-td>
              </tr>
              <tr
                ><sd-form-item-td name="riskReasonDesc" :colspan="3">
                  <a-textarea v-model="model.riskReasonDesc" :rows="3" /> </sd-form-item-td
              ></tr>
              <tr>
                <sd-form-item-td
                  name="riskLevel"
                  component="a-select"
                  :input-props="{
                    disabled: true,
                  }"
                />
                <sd-form-item-td
                  name="status"
                  component="a-select"
                  :input-props="{
                    disabled: statusDisabled,
                    defaultValue: 'enable',
                  }"
                />
              </tr>
              <tr>
                <sd-form-item-td
                  name="occurPossibility"
                  component="a-select"
                  :input-props="{
                    disabled: true,
                  }"
                />
                <sd-form-item-td
                  name="riskImpactDegree"
                  component="a-select"
                  :input-props="{
                    disabled: true,
                  }"
                />
              </tr>
              <tr>
                <sd-form-item-td name="creationTime">
                  <template v-slot:read-and-edit="{ editable }">
                    {{ model.creationTime | sdDateFormat('YYYY-MM-DD') }}
                  </template>
                </sd-form-item-td>
                <sd-form-item-td name="creatorName" />
              </tr>
              <tr>
                <sd-form-item-td v-if="initParam(model)" name="remark" :colspan="3">
                  <a-textarea v-model="model.remark" :rows="3" />
                </sd-form-item-td>
              </tr> </table

            ><table>
              <tr
                ><td :colspan="4">
                  <sd-form-item name="riskIdentifyUpdateLawEntitys" :label="null">
                    <template v-slot:read-and-edit="{ editable }">
                      <audit-advanced-group
                        :expand="expandC"
                        :expand-str="'expandC'"
                        :group-label="'相关法规制度'"
                        @changedClick="changedClick"
                        ><template>
                          <template>
                            <div :class="$style.wrapper">
                              <div v-show="expandY && editable" :class="$style.btnselect">
                                <a-button
                                  type="link"
                                  :class="$style.batchselect"
                                  @click="lawsRelSelect"
                                >
                                  <a-icon type="check-circle" :theme="'filled'" />
                                  选择
                                </a-button>
                              </div>
                            </div>
                          </template>
                          <xm-child-table
                            ref="docformlawlist"
                            v-model="model.riskIdentifyUpdateLawEntitys"
                            :read-only="!editable"
                            label=""
                            :fields="
                              [
                                {
                                  caption: '序号',
                                  name: 'sortNum',
                                  dataType: 'number',
                                  attr: {},
                                },
                              ].concat(Array.from(fields.riskIdentifyUpdateLawEntitys.attr.dync))
                            "
                            :columns="childlawlistColumns"
                            :width="1200"
                            :addfun="addfun"
                          >
                          </xm-child-table>
                        </template>
                      </audit-advanced-group>
                    </template> </sd-form-item
                ></td>
              </tr>

              <tr
                ><td :colspan="4">
                  <sd-form-item name="riskIdentifyUpdateResultEntitys" :label="null">
                    <template v-slot:read-and-edit="{ editable }">
                      <audit-advanced-group
                        :expand="expandY"
                        :expand-str="'expandY'"
                        :group-label="'关联风险评估结果'"
                        @changedClick="changedClick"
                        ><template>
                          <xm-child-table
                            ref="docformEventresult"
                            v-model="model.riskIdentifyUpdateResultEntitys"
                            :read-only="true"
                            label=""
                            :fields="
                              [
                                {
                                  caption: '序号',
                                  name: 'sortNum',
                                  dataType: 'number',
                                  attr: {},
                                },
                              ].concat(Array.from(fields.riskIdentifyUpdateResultEntitys.attr.dync))
                            "
                            :columns="childEventresultColumns"
                            :width="1200"
                          >
                          </xm-child-table
                        ></template>
                      </audit-advanced-group>
                    </template> </sd-form-item
                ></td>
              </tr>
              <tr
                ><td :colspan="4">
                  <sd-form-item name="riskIdentifyUpdateCaseEntitys" :label="null">
                    <template v-slot:read-and-edit="{ editable }">
                      <audit-advanced-group
                        :expand="expandX"
                        :expand-str="'expandX'"
                        :group-label="'关联风险案例'"
                        @changedClick="changedClick"
                        ><template>
                          <xm-child-table
                            ref="docformEventCase"
                            v-model="model.riskIdentifyUpdateCaseEntitys"
                            :read-only="true"
                            label=""
                            :fields="
                              [
                                {
                                  caption: '序号',
                                  name: 'sortNum',
                                  dataType: 'number',
                                  attr: {},
                                },
                              ].concat(Array.from(fields.riskIdentifyUpdateCaseEntitys.attr.dync))
                            "
                            :columns="childEventCaseColumns"
                            :width="1200"
                          >
                          </xm-child-table>
                        </template>
                      </audit-advanced-group>
                    </template> </sd-form-item
                ></td>
              </tr>
              <tr
                ><td :colspan="4">
                  <sd-form-item name="riskIdentifyUpdateLossEntitys" :label="null">
                    <template v-slot:read-and-edit="{ editable }">
                      <audit-advanced-group
                        :expand="expandZ"
                        :expand-str="'expandZ'"
                        :group-label="'关联损失事件'"
                        @changedClick="changedClick"
                        ><template>
                          <xm-child-table
                            ref="docformEventLoss"
                            v-model="model.riskIdentifyUpdateLossEntitys"
                            :read-only="true"
                            label=""
                            :fields="
                              [
                                {
                                  caption: '序号',
                                  name: 'sortNum',
                                  dataType: 'number',
                                  attr: {},
                                },
                              ].concat(Array.from(fields.riskIdentifyUpdateLossEntitys.attr.dync))
                            "
                            :columns="childEventLossColumns"
                            :width="1200"
                          >
                          </xm-child-table>
                        </template>
                      </audit-advanced-group>
                    </template> </sd-form-item
                ></td>
              </tr>

              <tr
                ><td :colspan="4">
                  <sd-form-item name="riskIdentifyUpdateMeasureEntitys" :label="null">
                    <template v-slot:read-and-edit="{ editable }">
                      <audit-advanced-group
                        :expand="expandW"
                        :expand-str="'expandW'"
                        :group-label="'关联内控措施'"
                        @changedClick="changedClick"
                        ><template>
                          <xm-child-table
                            ref="docformEventMeasure"
                            v-model="model.riskIdentifyUpdateMeasureEntitys"
                            :read-only="true"
                            label=""
                            :fields="
                              [
                                {
                                  caption: '序号',
                                  name: 'sortNum',
                                  dataType: 'number',
                                  attr: {},
                                },
                              ].concat(
                                Array.from(fields.riskIdentifyUpdateMeasureEntitys.attr.dync)
                              )
                            "
                            :columns="childEventMeasureColumns"
                            :width="1200"
                          >
                          </xm-child-table>
                        </template>
                      </audit-advanced-group>
                    </template> </sd-form-item
                ></td>
              </tr>
            </table>

            <table>
              <tr>
                <td style="padding-left:5px;border:none">
                  <audit-advanced-group
                    :expand="change"
                    :expand-str="'change'"
                    :group-label="'风险事项_变更信息'"
                    tablestyle="''"
                    @changedClick="changedClick"
                  ></audit-advanced-group>
                </td>
              </tr>
            </table>

            <table
              v-for="(bg, index) in fndeal(model.iamDetailFormModifyLogEntities)"
              v-show="change"
              :key="index"
              :class="$style.tablexm"
            >
              <colgroup>
                <col style="width: 20%;" />
                <col style="width: 30%;" />
                <col style="width: 20%;" />
                <col style="width: 30%;" />
              </colgroup>
              <tr>
                <td style="width:160px;text-align:right;vertical-align:top">{{ bg.creatorName }}</td
                ><td colspan="3"
                  ><div
                    style="
    width: 18px;margin-left:2px;
    font-size: 8px;
    color: #fff;
    text-align:center;
    background-color: lightgreen;
    border-radius: 100%;
"
                    >√</div
                  ><div style="padding-left:10px;margin-left:9px;border-left:1px solid gray"
                    >{{ bg.creationTime | sdDateFormat('YYYY-MM-DD HH:mm:ss') }}
                    <table
                      ><tr v-for="(x, index) in bg.xx" :key="index">
                        <td style="width:150px">[{{ x.fieldDesc }}]</td
                        ><td
                          >{{ x.oldValue !== '' ? '"' : ''
                          }}{{
                            x.oldValue.indexOf('[') !== -1 ||
                            x.oldValue.indexOf('{') !== -1 ||
                            x.newValue.indexOf('[') !== -1 ||
                            x.newValue.indexOf('{') !== -1
                              ? ''
                              : x.oldValue === 'null'
                              ? ''
                              : x.oldValue
                          }}{{ x.oldValue !== '' ? '" 改为 ' : ''
                          }}<span v-if="x.oldValue === ''" style="color:green">
                            {{
                              x.newValue.indexOf('[') !== -1 || x.newValue.indexOf('{') !== -1
                                ? '修改动态表格数据'
                                : x.newValue
                            }}</span
                          >
                          <span v-else>{{
                            x.newValue.indexOf('[') !== -1 || x.newValue.indexOf('{') !== -1
                              ? '修改动态表格数据'
                              : '"' + x.newValue + '"'
                          }}</span>
                        </td></tr
                      ></table
                    >
                  </div></td
                >
              </tr>
            </table>
          </template>
        </sd-detail-form>
      </a-spin>
    </audit-form-top-banner>
    <audit-matters-select-modal
      :visible="visible"
      :org-id="null"
      :show-selection="showSelectionlaw"
      @listSelected="listSelected"
    ></audit-matters-select-modal>
    <!-- 发现分类树 -->
    <a-modal
      :visible="catvisible"
      title="请选择"
      width="700px"
      :destroy-on-close="true"
      @ok="handlecatOk"
      @cancel="handlecatCancel"
    >
      <risk-category-tree
        ref="riskCategorytree"
        show-line
        top-node-text="风险库"
        :is-select-dep="true"
        manager-type="view"
        :classstyle="true"
        :history="true"
        :hisv="this.$route.query.versionId ? this.$route.query.versionId : this.versionId"
        :hisorg="this.$route.query.versionId ? this.$route.query.orgId : this.orgId"
        :hisorgn="this.$route.query.orgName ? this.$route.query.orgName : this.orgName"
        @treeSelect="treeSelect"
      />
    </a-modal>
    <!-- 主管部门手填组件 -->
    <a-modal v-model="ModalVisible" title="手动录入" @ok="ModalHandleOk">
      <a-form-model ref="ModalForm" :model="ModalForm">
        <a-form-model-item label="主管部门" prop="orgName">
          <a-input v-model="ModalForm.orgName" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </span>
</template>

<script>
import { Modal, Message } from 'ant-design-vue'
import sdGroupPicker from '@/common/components/sd-group-picker.vue'
import riskDeptSgtxMixins from '@product/iam/components/risk-dept-sgtx-mixins.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import auditMattersSelectModal from '@product/iam/audit/matters/audit-matters-select-modal.vue'
import RiskService from '@product/iam/risk/risklib/risk-service'
import riskCategoryTree from '@product/iam/risk/risklib/category/risk-category-tree'
import riskIdentificationService from '../risk-identification-service'
import components from './_import-components/risk-identification-event-form-import'

export default {
  name: 'RiskIdentificationEventUpdateForm',
  metaInfo() {
    return {
      title: this.pageTitle,
    }
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditAdvancedGroup,
    auditMattersSelectModal,
    riskCategoryTree,
    sdGroupPicker,
  },
  mixins: [auditAdvancedGroupMixins, riskDeptSgtxMixins],
  data() {
    return {
      competentDeptOpt: null,
      pageTitle: '风险识别-修改',
      statusDisabled: true, // 状态是否可编辑
      spinning: false,
      formData: {},
      change: true,
      catvisible: false,
      visible: false,
      expandA: true,
      expandC: true,
      mode: null,
      childlawlistColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'eventLawId', sdHidden: true },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'title', width: '40%' },
        { dataIndex: 'docNum', width: '100px' },
        { dataIndex: 'clauses' },
        { dataIndex: 'versionId', sdHidden: true },
      ],
      expandY: true,
      childEventresultColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'eventResultId', sdHidden: true },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'year', width: '10%' },
        { dataIndex: 'estimateName', width: '10%' },
        { dataIndex: 'occurPossibility', width: '10%' },
        { dataIndex: 'riskImpactDegree' },
        { dataIndex: 'riskLevel' },
        { dataIndex: 'riskTrend' },
        { dataIndex: 'versionId', sdHidden: true },
      ],
      expandX: true,
      childEventCaseColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'eventCaseId', sdHidden: true },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'caseName', width: '30%' },
        { dataIndex: 'caseType' },
        { dataIndex: 'year' },
        { dataIndex: 'versionId', sdHidden: true },
      ],
      expandZ: true,
      childEventLossColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '140px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'eventLossId', sdHidden: true },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'year', width: '10%' },
        { dataIndex: 'lossEventName', width: '15%' },
        { dataIndex: 'lossEventType', width: '10%' },
        { dataIndex: 'lossEventNature' },
        { dataIndex: 'lossMoney', title: '损失金额(万元)' },
        { dataIndex: 'happenDate' },
        { dataIndex: 'involvedLitigation' },
        { dataIndex: 'versionId', sdHidden: true },
      ],
      expandW: true,
      childEventMeasureColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '140px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'eventMeasureId', sdHidden: true },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'mtxPrcPath', width: '30%' },
        { dataIndex: 'measureName' },
        { dataIndex: 'measureCode' },
        { dataIndex: 'controlLevel', width: '10%' },
        { dataIndex: 'controlType', width: '10%' },
        { dataIndex: 'versionId', sdHidden: true },
      ],
      versionId: null,
      orgId: null,
      orgName: '',
      selectlist: [],
      catpath: '',
      catId: null,
      flag: false,
      sortNum: null,
    }
  },
  watch: {
    // 监听部门变化
    competentDeptOpt() {
      setTimeout(() => {
        this.$refs.docform.setFieldValue('competentDeptOpt', this.competentDeptOpt)
      }, 500)
    },
  },
  mounted() {
    if (this.$route.query.versionId) {
      this.versionId = parseInt(this.$route.query.versionId)
      this.orgId = this.$route.query.orgId
    }
    if (this.$route.query.isDelete) {
      this.pageTitle = '风险识别-废弃'
    }
  },
  methods: {
    changecompetentDept(value) {
      this.competentDeptOpt = value
    },
    initParam(model) {
      if (!this.flag && this.$refs.docform) {
        if (this.$route.query.isDelete) {
          this.$refs.docform.formData.pageTitle = '风险识别-废弃风险事项'
        }
        // 记录随机ID和风险版本ID
        model.randomId = parseFloat(this.$route.query.infoId)
        if (this.$route.query.eventId) {
          model.eventId = parseFloat(this.$route.query.eventId)
        }
        if (this.$route.query.identifyId) {
          model.identifyId = parseFloat(this.$route.query.identifyId)
        }
        model.versionId = parseFloat(this.$route.query.versionId)
        model.auditOrgId = parseFloat(this.$route.query.orgId)
        this.versionId = model.versionId
        this.orgId = model.auditOrgId
        // 如果没有传record，则说明是选择之后，没有保存，所以需要赋值
        if (!this.$route.query.record) {
          this.spinning = true
          riskIdentificationService
            .getRiskEventInfo(parseFloat(this.$route.query.eventId))
            .then((res) => {
              const info = res.data.pageFormData.pageFieldInfos
              // 法律法规
              const lawInfo = info.find((item) => {
                return item.name === 'riskEventLawEntitys'
              })
              lawInfo.name = 'riskIdentifyUpdateLawEntitys'
              const lawTable = JSON.parse(lawInfo.value ? lawInfo.value : '[]')
              lawTable.forEach((item) => {
                item.eventLawId = item.id
              })
              lawInfo.value = JSON.stringify(lawTable)
              // 结果
              const resultInfo = info.find((item) => {
                return item.name === 'riskEventResultEntitys'
              })
              resultInfo.name = 'riskIdentifyUpdateResultEntitys'
              const resultTable = JSON.parse(resultInfo.value ? resultInfo.value : '[]')
              resultTable.forEach((item) => {
                item.eventResultId = item.id
              })
              resultInfo.value = JSON.stringify(resultTable)
              // 风险损失事件
              const lossInfo = info.find((item) => {
                return item.name === 'riskEventLossEventEntitys'
              })
              lossInfo.name = 'riskIdentifyUpdateLossEntitys'
              const lossTable = JSON.parse(lossInfo.value ? lossInfo.value : '[]')
              lossTable.forEach((item) => {
                item.eventLossId = item.id
              })
              lossInfo.value = JSON.stringify(lossTable)
              // 内控措施
              const measureInfo = info.find((item) => {
                return item.name === 'riskEventMeasureEntitys'
              })
              measureInfo.name = 'riskIdentifyUpdateMeasureEntitys'
              const measureTable = JSON.parse(measureInfo.value ? measureInfo.value : '[]')
              measureTable.forEach((item) => {
                item.eventMeasureId = item.id
              })
              measureInfo.value = JSON.stringify(measureTable)
              // 风险案例
              const caseInfo = info.find((item) => {
                return item.name === 'riskEventCaseEntitys'
              })
              caseInfo.name = 'riskIdentifyUpdateCaseEntitys'
              const caseTable = JSON.parse(caseInfo.value ? caseInfo.value : '[]')
              caseTable.forEach((item) => {
                item.eventCaseId = item.id
              })
              caseInfo.value = JSON.stringify(caseTable)

              info.push(
                this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
                  return item.name === 'randomId'
                })
              )
              info.push(
                this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
                  return item.name === 'eventId'
                })
              )
              const fieldNames = [
                'riskIdentifyUpdateLawEntitys',
                'riskIdentifyUpdateCaseEntitys',
                'riskIdentifyUpdateMeasureEntitys',
                'riskIdentifyUpdateResultEntitys',
                'riskIdentifyUpdateLossEntitys',
              ]
              info.forEach((item) => {
                if (fieldNames.includes(item.name)) {
                  model[item.name] = JSON.parse(item.value ? item.value : '[]')
                } else {
                  if (item.name !== 'creationTime') {
                    model[item.name] = item.value
                  }
                }
              })
              // 如果修改的文件状态是废弃，则可以改为启用
              if (model.status === 'abandonment') {
                this.statusDisabled = false
              }
              // 记录随机ID和风险版本ID
              model.randomId = parseFloat(this.$route.query.infoId)
              if (this.$route.query.eventId) {
                model.eventId = parseFloat(this.$route.query.eventId)
              }
              model.versionId = parseFloat(this.$route.query.versionId)
              model.auditOrgId = parseFloat(this.$route.query.orgId)
              this.versionId = model.versionId
              this.orgId = model.auditOrgId
              this.setDepName(model)
              // 重新获取分类名称
              this.getpath(model.riskCategoryId).then((res) => {
                model.riskCategoryPath = res
                this.spinning = false
              })
            })
        }
        this.setDepName(model)
        this.flag = true
      }
      return true
    },
    setDepName(model) {
      // 处理主管部门高级字段
      if (!model.competentDeptOpt) return
      let opt
      if (typeof model.competentDeptOpt === 'string') {
        opt = JSON.parse(model.competentDeptOpt)
      } else {
        opt = model.competentDeptOpt
      }
      const name = model.competentDeptName
      const id = model.competentDeptId
      if (name !== undefined && id !== undefined && name !== null && id !== null) {
        const names = name.split(',')
        const ids = id.split(',')
        names.forEach((n, index) => {
          if (ids[index].indexOf('_sd') > -1) {
            const no = {
              type: 'GROUP',
              code: ids[index],
              name: n,
            }
            opt.splice(index, 0, no)
          }
        })
        this.competentDeptOpt = opt
        model.competentDeptOpt = opt
      }
    },
    getpath(id) {
      return new Promise((resolve, reject) => {
        RiskService.findupcatinfo(id).then((res) => {
          this.catpath = res.data.replace('内控矩阵', '风控矩阵')
          resolve(res.data)
        })
      })
    },
    getsortNum(id) {
      return new Promise((resolve, reject) => {
        RiskService.fngetsortNum(id).then((res) => {
          this.sortNum = res
          resolve(res)
        })
      })
    },
    showflpath() {
      this.catvisible = !this.catvisible
      if (this.catvisible) {
        setTimeout(() => {
          this.$refs.riskCategorytree.initDeptList('')
        }, 1000)
      }
    },
    treeSelect(select, info) {
      const id = info.selectedNodes[0].data.props.id
      this.catpath = ''
      this.catId = null
      if (info.selectedNodes[0].data.props.props) {
        if (info.selectedNodes[0].data.props.props.isEnd === '1') {
          if (id !== -1) {
            this.getpath(id)
            this.catId = id
          } else {
            this.catpath = this.$route.query.orgName + '风险库'
            this.catId = -1
          }
        } else {
          Modal.info({
            content: '请选择末级分类节点',
          })
        }
      }
    },
    handlecatOk() {
      if (this.catpath !== '') {
        this.$refs.docform.setFieldValue('riskCategoryPath', this.catpath)
        this.$refs.docform.setFieldValue('riskCategoryId', this.catId)
        this.showflpath()
        // this.findType = this.findcat.text
        this.catpath = ''
        this.catId = null
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择末级分类节点!',
        })
        return false
      }
    },
    handlecatCancel() {
      this.showflpath()
    },
    showSelectionlaw(record) {
      this.selectlist = this.$refs.docformlawlist.value
      if (this.selectlist.length === 0) {
        return true
      } else if (
        this.selectlist.findIndex(
          (i) => i.title + '-' + i.docNum === record.docTitle + '-' + record.dispatchWord
        ) > -1
      ) {
        return false
      } else {
        return true
      }
    },
    addfun(data) {
      if (!this.versionId) {
        this.versionId = this.$refs.docform.getFieldValue('versionId')
        this.orgId = this.$refs.docform.getFieldValue('auditOrgId')
      }
      data.versionId = this.versionId
      return data
    },
    // 页面加载完成后
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
      if (!this.mode) {
        this.mode = this.$route.query.mode
      }
    },
    close(beanId, flag) {
      crossWindowWatcher.notifyChange(true)
      window.close()
    },
    saved() {
      Message.success({ content: '保存成功！' }, 1).then(() => {
        this.close(true)
      })
    },
    // 保存
    saveForm() {
      // 如果是新文档，则赋值
      // 校验编号唯一
      let eventCode = this.$refs.docform.getFieldValue('eventCode')
      // const id = this.$refs.docform.getFieldValue('id')
      //   ? this.$refs.docform.getFieldValue('id')
      //   : -1
      // const versionId = parseInt(this.versionId)
      // const auditOrgId = parseInt(this.orgId)
      if (!eventCode) eventCode = ''
      riskIdentificationService.checkMeasurecode(eventCode).then((res) => {
        if (!res.data) {
          Message.info('编号重复请重新填写', 1)
        } else {
          let versionId = null
          if (this.$route.query.record === null || this.$route.query.record === undefined) {
            const orgId = this.$route.query.orgId
            versionId = parseInt(this.$route.query.versionId)
            this.$refs.docform.setFieldValue('auditOrgId', parseInt(orgId))
            this.$refs.docform.setFieldValue('versionId', versionId)
          } else {
            versionId = this.$refs.docform.getFieldValue('versionId')
          }
          // 处理主管部门高级字段
          // 默认必填
          this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
            return item.name === 'competentDeptOpt'
          }).required = true
          const competentDeptOpt = this.$refs.docform.getFieldValue('competentDeptOpt')
          if (competentDeptOpt) {
            let names = ''
            let ids = ''
            const nopt = []
            competentDeptOpt.forEach((o) => {
              names = names + o.name + ','
              ids = ids + o.code + ','
              if (o.code.indexOf('_sd') === -1) {
                nopt.push(o)
              }
            })
            if (names.substring(names.length - 1, names.length) === ',')
              names = names.substring(0, names.length - 1)
            if (ids.substring(ids.length - 1, ids.length) === ',')
              ids = ids.substring(0, ids.length - 1)
            this.$refs.docform.setFieldValue('competentDeptOpt', nopt)
            this.$refs.docform.setFieldValue('competentDeptName', names)
            this.$refs.docform.setFieldValue('competentDeptId', ids)

            // 如果只有一个手填，就不校验必填了
            // 组件显示有值 但是  实际是拼接的值，则不进行必填判断
            if (names !== '' && nopt.length === 0) {
              this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
                return item.name === 'competentDeptOpt'
              }).required = false
            } else {
              this.$refs.docform.formData.pageFormData.pageFieldInfos.find((item) => {
                return item.name === 'competentDeptOpt'
              }).required = true
            }
          }
          // 轮询所有子表赋值versionId
          setTimeout(() => {
            this.$refs.docform.saveBtnClick()
          }, 0)
        }
      })
    },
    measureRelSelect() {},

    fndeal(obj) {
      const newobj = []
      if (obj !== undefined) {
        if (typeof obj === 'string') obj = JSON.parse(obj)
        obj.forEach((item) => {
          if (
            [
              'riskIdentifyUpdateLawEntitys',
              'riskIdentifyUpdateLossEntitys',
              'riskIdentifyUpdateResultEntitys',
              'riskIdentifyUpdateMeasureEntitys',
              'riskIdentifyUpdateCaseEntitys',
              'iamDetailFormModifyLogEntities',
              'riskCategoryId',
              'riskCategoryPath',
            ].indexOf(item.fieldName) < 0
          ) {
            item.xt = item.creatorName + '_' + item.creationTime
            const i = newobj.find((n) => n.xt === item.xt)
            if (i !== undefined) {
              i.xx.push({
                fieldDesc: item.fieldDesc,
                fieldName: item.fieldName,
                newValue: item.newValue,
                oldValue: item.oldValue,
              })
            } else {
              item.xx = [
                {
                  fieldDesc: item.fieldDesc,
                  fieldName: item.fieldName,
                  newValue: item.newValue,
                  oldValue: item.oldValue,
                },
              ]
              newobj.push(item)
            }
          }
        })
      }
      return newobj
    },
    // 选择法律制度
    lawsRelSelect() {
      // 选择事项分类
      this.visible = true
    },
    listSelected(keys, keyinfos) {
      let iamAuditLaws = []
      if (this.$refs.docform.getFieldValue('riskIdentifyUpdateLawEntitys')) {
        iamAuditLaws = this.$refs.docform.getFieldValue('riskIdentifyUpdateLawEntitys')
      }
      keyinfos.forEach((element) => {
        const mmc = {}
        mmc.title = element.docTitle
        mmc.docNum = element.dispatchWord ? element.dispatchWord : ''
        mmc.versionId = this.versionId
        iamAuditLaws.push(mmc)
      })
      this.visible = false
      this.$refs.docform.setFieldValue('riskIdentifyUpdateLawEntitys', iamAuditLaws)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@import '@/webflow/sd-flow-form.scss';

.btnselect {
  position: relative;
  top: 4px;
  right: 200px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
.tablexm tr td {
  border: none !important;
}
</style>
