<template>
  <span>
    <audit-form-top-banner
      :handel-save-form="saveForm"
      :form-data="mode"
      @handelSaveForm="saveForm"
    >
      <sd-detail-form
        ref="docform"
        page-id="ic/measure/icMtxMeasure"
        :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
        :class="$style.form"
        @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="mtxPrcId"/> <sd-form-item-td name="auditOrgId"
            /></tr>
            <tr v-show="false"
              ><sd-form-item-td name="mtxVersionId" /><sd-form-item-td name="id" />
            </tr>
            <tr
              ><sd-form-item-td name="mtxPrcPath" :colspan="3" :label="'内控流程'">
                <a-input v-model="model.mtxPrcPath" 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="measureName"> </sd-form-item-td>
              <!-- 措施编号 -->
              <sd-form-item-td name="measureCode" />
            </tr>
            <tr>
              <!-- 措施描述 -->
              <sd-form-item-td name="measureDesc" :colspan="3">
                <a-textarea v-model="model.measureDesc" :rows="3" />
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="controlLevel" component="a-select" />
              <sd-form-item-td name="controlType" component="a-select" />
            </tr>
            <tr>
              <sd-form-item-td name="controlFrequency" component="a-select" />
              <sd-form-item-td name="controlWay" component="a-select" />
            </tr>
            <tr>
              <sd-form-item-td name="applicableOrgOpt" />
              <sd-form-item-td name="dutyDeptOpt" />
            </tr>
            <tr>
              <sd-form-item-td name="responPosition" />
              <sd-form-item-td
                name="sortNum"
                :input-props="{ defaultValue: sortNum }"
              ></sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="creationTime" />
              <sd-form-item-td name="creatorName" />
            </tr>
            <tr><sd-form-item-td name="businessDocument" :colspan="3"></sd-form-item-td></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="icMtxMeasureLawList" :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.icMtxMeasureLawList"
                          :read-only="!editable"
                          label=""
                          :fields="
                            [
                              {
                                caption: '序号',
                                name: 'sortNum',
                                dataType: 'number',
                                attr: {},
                              },
                            ].concat(Array.from(fields.icMtxMeasureLawList.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="icMtxMeasureEventList" :label="null">
                  <template v-slot:read-and-edit="{ editable }">
                    <audit-advanced-group
                      :expand="expandY"
                      :expand-str="'expandY'"
                      :group-label="'相关风险事项'"
                      @changedClick="changedClick"
                      ><template>
                        <template>
                          <div :class="$style.wrapper">
                            <div v-show="expandY && editable" :class="$style.btnfxselect">
                              <a-button
                                type="link"
                                :class="$style.batchselect"
                                @click="measureRelSelect"
                              >
                                <a-icon type="check-circle" :theme="'filled'" />
                                选择风险事项
                              </a-button>
                            </div>
                          </div>
                        </template>
                        <sd-child-table
                          ref="docformMeasureRel"
                          v-model="model.icMtxMeasureEventList"
                          :read-only="!editable"
                          label=""
                          :fields="[].concat(Array.from(fields.icMtxMeasureEventList.attr.dync))"
                          :columns="childmeasureColumns"
                          :width="1200"
                          @change="icMtxMeasureEventListChange"
                        >
                          <template v-slot:competentDeptOpt="{ record }">
                            <span>{{ record.competentDeptName }}</span>
                          </template>
                          <!-- form 表示这部分是子表组件的form插槽 -->
                          <template v-slot:form="{ model, fields }">
                            <table>
                              <tr>
                                <td style="padding-left:5px">
                                  <audit-advanced-group
                                    :expand-str="'findinfoExpand'"
                                    :group-label="'基本信息'"
                                  ></audit-advanced-group>
                                </td>
                              </tr>
                            </table>

                            <table :class="$style.rectprojectchildForm">
                              <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="parentId"/>
                                <sd-form-item-td name="auditOrgId"
                              /></tr>
                              <tr v-show="false"
                                ><sd-form-item-td
                                  name="versionId"
                                  :input-props="{ defaultValue: parseInt(FxversionId) }"
                                /><sd-form-item-td name="id" />
                                <sd-form-item-td name="sourceId" />
                              </tr>
                              <tr v-show="false"
                                ><sd-form-item-td name="creatorName"></sd-form-item-td
                                ><sd-form-item-td name="creationTime"></sd-form-item-td
                              ></tr>
                            </table>

                            <table v-if="model.sourceId === undefined">
                              <colgroup>
                                <col style="width: 15%;" />
                                <col style="width: 35%;" />
                                <col style="width: 15%;" />
                                <col style="width: 35%;" />
                              </colgroup>
                              <tr>
                                <sd-form-item-td
                                  name="eventTypePath"
                                  :colspan="3"
                                  :label="'风险分类'"
                                >
                                  <a-input
                                    v-model="model.eventTypePath"
                                    style="width:calc(100% - 80px);"
                                    read-only
                                  />
                                  <span style="padding:5px">
                                    <a-button @click="showFxflpath">选择</a-button>
                                  </span>
                                </sd-form-item-td></tr
                              >
                              <tr>
                                <!-- 措施编号 -->
                                <sd-form-item-td name="eventCode">
                                  <a-form-model-item
                                    :label="null"
                                    prop="eventCode"
                                    :rules="[{ validator: checkbh }]"
                                  >
                                    <a-input v-model.trim="model.eventCode" />
                                  </a-form-model-item>
                                </sd-form-item-td>
                                <!-- 措施名称 -->
                                <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" />
                                <sd-form-item-td name="competentDeptOpt">
                                  <sd-group-picker
                                    v-model="model.competentDeptOpt"
                                    style="width:calc(100% - 120px)"
                                    @change="changecomDepOpt"
                                  />
                                  <a-button
                                    type="primary"
                                    icon="plus"
                                    block
                                    style="width:110px;margin-left:5px;"
                                    @click="manualEntry('competentDeptOpt', 'docformMeasureRel')"
                                  >
                                    手工添加
                                  </a-button>
                                </sd-form-item-td>
                              </tr>
                              <tr v-show="false">
                                <sd-form-item-td name="competentDeptName" />
                                <sd-form-item-td name="competentDeptId" />
                                <sd-form-item-td
                                  name="eventType"
                                  :colspan="3"
                                  :label="'风险分类Id'"
                                />
                              </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: true,
                                    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" />
                                <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 v-else>
                              <colgroup>
                                <col style="width: 15%;" />
                                <col style="width: 35%;" />
                                <col style="width: 15%;" />
                                <col style="width: 35%;" />
                              </colgroup>
                              <tr>
                                <sd-form-item-td
                                  name="eventTypePath"
                                  :colspan="3"
                                  :label="'风险分类'"
                                >
                                  {{ model.eventTypePath }}
                                </sd-form-item-td></tr
                              >
                              <tr>
                                <!-- 措施编号 -->
                                <sd-form-item-td name="eventCode">
                                  {{ model.eventCode }}
                                </sd-form-item-td>
                                <!-- 措施名称 -->
                                <sd-form-item-td name="eventName">
                                  {{ model.eventName }}</sd-form-item-td
                                >
                              </tr>
                              <tr>
                                <!-- 措施描述 -->
                                <sd-form-item-td name="eventDesc" :colspan="3">
                                  {{ model.eventDesc }}
                                </sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td name="riskSource">{{
                                  getDisplayVaule(fields.riskSource, model.riskSource)
                                }}</sd-form-item-td>
                                <sd-form-item-td name="competentDeptOpt">{{
                                  model.competentDeptName
                                }}</sd-form-item-td>
                              </tr>
                              <tr
                                ><sd-form-item-td name="riskReasonDesc" :colspan="3">
                                  {{
                                    model.riskReasonDesc === null ||
                                    model.riskReasonDesc === undefined
                                      ? '&nbsp;'
                                      : model.riskReasonDesc
                                  }}</sd-form-item-td
                                ></tr
                              >
                              <tr>
                                <sd-form-item-td name="riskLevel">
                                  {{
                                    model.riskLevel === null || model.riskLevel === undefined
                                      ? '&nbsp;'
                                      : getDisplayVaule(fields.riskLevel, model.riskLevel)
                                  }}</sd-form-item-td
                                >
                                <sd-form-item-td name="status">
                                  {{
                                    model.status === null || model.status === undefined
                                      ? '启用'
                                      : getDisplayVaule(fields.status, model.status)
                                  }}</sd-form-item-td
                                >
                              </tr>
                              <tr>
                                <sd-form-item-td name="occurPossibility">{{
                                  getDisplayVaule(fields.occurPossibility, model.occurPossibility)
                                }}</sd-form-item-td>
                                <sd-form-item-td name="riskImpactDegree">{{
                                  getDisplayVaule(fields.riskImpactDegree, model.riskImpactDegree)
                                }}</sd-form-item-td>
                              </tr>
                              <tr>
                                <sd-form-item-td name="creationTime" />
                                <sd-form-item-td name="creatorName" />
                              </tr>
                              <tr>
                                <sd-form-item-td v-if="initParam(model)" name="remark" :colspan="3">
                                  {{ model.remark }}
                                </sd-form-item-td>
                              </tr>
                            </table>
                          </template>
                        </sd-child-table></template
                      >
                    </audit-advanced-group>
                  </template>
                </sd-form-item></td
              >
            </tr>
            <tr
              ><td :colspan="4">
                <sd-form-item name="icMtxMeasureStepList" :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="docformsteplist"
                          v-model="model.icMtxMeasureStepList"
                          :read-only="!editable"
                          label=""
                          :fields="
                            [
                              {
                                caption: '序号',
                                name: 'sortNum',
                                dataType: 'number',
                                attr: {},
                              },
                            ].concat(Array.from(fields.icMtxMeasureStepList.attr.dync))
                          "
                          :columns="childsteplistColumns"
                          :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="icMtxMeasureResultList" :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="docformResultlist"
                          v-model="model.icMtxMeasureResultList"
                          :read-only="true"
                          label=""
                          :fields="
                            [
                              {
                                caption: '序号',
                                name: 'sortNum',
                                dataType: 'number',
                                attr: {},
                              },
                            ].concat(Array.from(fields.icMtxMeasureResultList.attr.dync))
                          "
                          :columns="childresultlistColumns"
                          :width="1200"
                          :addfun="addfun"
                        >
                        </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>
    </audit-form-top-banner>
    <audit-matters-select-modal
      :visible="visible"
      :org-id="null"
      :show-selection="showSelectionlaw"
      @listSelected="listSelected"
    ></audit-matters-select-modal>
    <!-- 风险事项选择器-->
    <div v-show="false">
      <ic-measure-picker
        ref="icRiskeventsel"
        v-model="eventSelect"
        :version-id="this.FxversionId"
        :types="'FK'"
        :org-id="this.$route.query.orgId ? this.$route.query.orgId : this.orgId"
        :org-name="this.$route.query.orgName ? this.$route.query.orgName : this.orgName + '风险库'"
        :single="false"
        :read-only="false"
        @change="fnqd"
      ></ic-measure-picker>
    </div>
    <!-- 发现风险分类树 -->
    <a-modal
      :visible="catfxvisible"
      title="请选择"
      width="700px"
      :destroy-on-close="true"
      @ok="handlecatfxOk"
      @cancel="handlecatfxCancel"
    >
      <risk-category-tree
        ref="riskCategorytree"
        show-line
        top-node-text="风险库"
        :is-select-dep="true"
        manager-type="view"
        :classstyle="true"
        :history="true"
        :hisv="this.FxversionId"
        :hisorg="this.$route.query.versionId ? this.$route.query.orgId : this.orgId"
        :hisorgn="this.$route.query.orgName ? this.$route.query.orgName : this.orgName"
        @treeSelect="treeFxSelect"
      />
    </a-modal>
    <!-- 发现分类树 -->
    <a-modal
      :visible="catvisible"
      title="请选择"
      width="700px"
      :destroy-on-close="true"
      @ok="handlecatOk"
      @cancel="handlecatCancel"
    >
      <mtx-process-catalog-tree
        ref="mtxprocesstree"
        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="changecomDepOptforModal">
      <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 { getComponentSpec } from '@/common/components/sd-form'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import debounce from 'lodash.debounce'
import axios from '@/common/services/axios-instance'
import icMeasurePicker from '@product/iam/components/ic-picker/ic-measure-picker.vue'
import riskDeptSgtxMixins from '@product/iam/components/risk-dept-sgtx-mixins.vue'
import auditFormTopBanner from '../../components/audit-form-top-banner'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import auditMattersSelectModal from '../../audit/matters/audit-matters-select-modal.vue'
import RiskService from '../../risk/risklib/risk-service'
import riskCategoryTree from '../../risk/risklib/category/risk-category-tree'
import mtxProcessCatalogTree from './mtx-process-catalog-tree'
import MtxProcessService from './mtx-process-service'
import components from './_import-components/mtx-measure-form-import'

export default {
  name: 'MtxMeasureForm',
  metaInfo: {
    title: '内控措施',
  },
  components: {
    ...components,
    auditFormTopBanner,
    auditAdvancedGroup,
    auditMattersSelectModal,
    mtxProcessCatalogTree,
    icMeasurePicker,
    riskCategoryTree,
  },
  mixins: [auditAdvancedGroupMixins, riskDeptSgtxMixins],
  data() {
    return {
      eventSelect: [],
      eventSellist: [],
      catfxvisible: false,
      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: 'id', sdHidden: true },
        { dataIndex: 'title', width: '40%' },
        { dataIndex: 'docNum', width: '100px' },
        { dataIndex: 'clauses' },
        { dataIndex: 'mtxVersionId', sdHidden: true },
      ],
      expandY: true,
      childmeasureColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'eventTypePath', width: '10%' },
        { dataIndex: 'eventCode', width: '10%' },
        { dataIndex: 'eventName', width: '10%' },
        { dataIndex: 'competentDeptOpt', width: '10%' },
        { dataIndex: 'competentDeptName', sdHidden: true },
        { dataIndex: 'competentDeptId', sdHidden: true },
        { dataIndex: 'occurPossibility' },
        { dataIndex: 'riskImpactDegree' },
        { dataIndex: 'riskLevel' },
        { dataIndex: 'mtxVersionId', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'auditOrgId', sdHidden: true },
        { dataIndex: 'versionId', sdHidden: true },
        { dataIndex: 'eventType', sdHidden: true },
        { dataIndex: 'eventDesc', sdHidden: true },
        { dataIndex: 'riskSource', sdHidden: true },
        { dataIndex: 'riskReasonDesc', sdHidden: true },
        { dataIndex: 'status', sdHidden: true },
        { dataIndex: 'creationTime', sdHidden: true },
        { dataIndex: 'creatorName', sdHidden: true },
        { dataIndex: 'remark', sdHidden: true },
        { dataIndex: 'sourceId', sdHidden: true },
      ],
      expandX: true,
      childsteplistColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '80px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'stepName', width: '60%' },
        { dataIndex: 'attachment' },
        { dataIndex: 'mtxVersionId', sdHidden: true },
      ],
      expandZ: true,
      childresultlistColumns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '140px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'planName', width: '30%' },
        { dataIndex: 'evaluationRange', width: '30%' },
        { dataIndex: 'testResult', width: '10%' },
        { dataIndex: 'defectType', width: '10%' },
        { dataIndex: 'defectLevel', width: '10%' },
        { dataIndex: 'mtxVersionId', sdHidden: true },
      ],
      versionId: null,
      orgId: null,
      orgName: '',
      FxversionId: null,
      selectlist: [],
      catpath: '',
      catId: null,
      flag: false,
      sortNum: null,
    }
  },
  mounted() {
    if (this.$route.query.versionId) {
      this.versionId = parseInt(this.$route.query.versionId)
      this.orgId = this.$route.query.orgId
    }
  },
  methods: {
    // 事项变化时监听事件
    icMtxMeasureEventListChange(data) {
      const eventData = []
      if (data) {
        data.forEach((item) => {
          if (item.sortNum !== null && item.sortNum !== undefined) {
            eventData.push({
              id: item.sortNum,
              text: item.eventName,
              leaf: true,
              expandable: false,
              differentDisplay: false,
              props: {
                isItem: false,
                isEnd: '1',
              },
              disabled: false,
              code: item.sortNum + '',
              cat: false,
            })
          }
        })
      }
      this.eventSelect = eventData
    },
    // 设置子表必填
    setIcMtxMeasureEventListRequire(flag) {
      this.$refs.docform.formData.pageFormData.pageFieldInfos
        .find((item) => {
          return item.name === 'icMtxMeasureEventList'
        })
        .attr.dync.find((item) => {
          return item.name === 'competentDeptOpt'
        }).required = flag
    },
    checkIcMtxMeasureEventListRequire(data) {
      // 先给个默认值，不校验必填
      this.setIcMtxMeasureEventListRequire(false)
      // 循环所有数据，如果有一条的组织机构为空，则校验必填，否则不校验
      if (data) {
        data.forEach((oneData) => {
          const dept = JSON.parse(oneData.competentDeptOpt)
          const deptName = oneData.competentDeptName
          if (dept.length === 0 && (deptName === '') | !deptName) {
            this.setIcMtxMeasureEventListRequire(true)
          }
        })
      }
    },
    getDisplayVaule(field, text) {
      if (getComponentSpec(field).getDisplayValue) {
        if (typeof text !== 'undefined' && text !== null) {
          const value = getComponentSpec(field).parseBackendValue?.(text) || text
          return getComponentSpec(field).getDisplayValue(value)
        } else {
          return ''
        }
      }
      return text
    },
    checkbh(rule, value, callback) {
      const sourceId = this.$refs.docformMeasureRel.$refs.form.getFieldValue('sourceId')
      if (value && sourceId === undefined) {
        const eventCode = value
        let id = this.$refs.docformMeasureRel.$refs.form.getFieldValue('id')
          ? this.$refs.docformMeasureRel.$refs.form.getFieldValue('id')
          : -1
        // 判断是否为新增文件
        if (id.toString().includes('fakeId')) {
          id = -1
        }
        const versionId = parseInt(this.FxversionId)
        const auditOrgId = parseInt(this.orgId)
        RiskService.checkMeasurecode(eventCode, id, versionId, auditOrgId).then((res) => {
          if (!res.data) {
            callback(new Error('编号重复请重新填写'))
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    },
    // 保存时校验编号唯一
    onRecordSaved() {
      const eventCode = this.$refs.docformMeasureRel.$refs.form.getFieldValue('eventCode')
      const id = this.$refs.docformMeasureRel.$refs.form.getFieldValue('id')
        ? this.$refs.docformMeasureRel.$refs.form.getFieldValue('id')
        : -1
      const versionId = parseInt(this.FxversionId)
      const auditOrgId = parseInt(this.orgId)
      RiskService.checkMeasurecode(eventCode, id, versionId, auditOrgId).then((res) => {
        if (!res.data) {
          Message.info('编号重复请重新填写', 1)
          return false
        } else {
        }
      })
    },
    showFxflpath() {
      this.catfxvisible = !this.catfxvisible
      if (this.catfxvisible) {
        setTimeout(() => {
          this.$refs.riskCategorytree.initDeptList('')
        }, 1000)
      }
    },
    treeFxSelect(select, info) {
      const id = info.selectedNodes[0].data.props.id
      this.catfxpath = ''
      this.catfxId = null
      if (info.selectedNodes[0].data.props.props) {
        if (info.selectedNodes[0].data.props.props.isEnd === '1') {
          if (id !== -1) {
            this.getfxpath(id)
            this.catfxId = id
          } else {
            this.catfxpath = this.$route.query.orgName + '内控矩阵'
            this.catfxId = -1
          }
        } else {
          Modal.info({
            content: '请选择末级分类节点',
          })
        }
      }
    },
    handlecatfxOk() {
      if (this.catfxpath !== '') {
        this.$refs.docformMeasureRel.$refs.form.setFieldValue('eventTypePath', this.catfxpath)
        this.$refs.docformMeasureRel.$refs.form.setFieldValue('eventType', this.catfxId.toString())
        this.showFxflpath()
        // this.findType = this.findcat.text
        this.catfxpath = ''
        this.catfxId = null
      } else {
        Modal.warning({
          title: '提示',
          content: '请选择末级分类节点!',
        })
        return false
      }
    },
    handlecatfxCancel() {
      this.showFxflpath()
    },
    getfxpath(id) {
      return new Promise((resolve, reject) => {
        RiskService.findupcatinfo(id).then((res) => {
          this.catfxpath = res.data
          resolve(res.data)
        })
      })
    },
    changecomDepOptforModal() {
      const flow = 'docformMeasureRel'
      this.ModalHandleOk()
      this.changecomDepOpt(this.$refs[flow].$refs.form.getFieldValue(this.currentEntryField))
    },
    changecomDepOpt(value) {
      let names = ''
      let ids = ''
      value.forEach((v) => {
        names += ',' + v.name
        ids += ',' + v.code
      })
      if (names !== '') {
        names = names.substring(1, names.length)
      }
      if (ids !== '') {
        ids = ids.substring(1, ids.length)
      }
      this.$refs.docformMeasureRel.$refs.form.setFieldValue('competentDeptName', names)
      this.$refs.docformMeasureRel.$refs.form.setFieldValue('competentDeptId', ids)
    },
    fnqd(data) {
      const ids = []
      let iamAuditEvents = []
      if (this.$refs.docform.getFieldValue('icMtxMeasureEventList')) {
        iamAuditEvents = this.$refs.docform.getFieldValue('icMtxMeasureEventList')
      }
      const idList = {}
      data.forEach((i) => {
        const oldId = i.id.toString()
        let id = i.id.toString()
        if (id.indexOf('1000') > -1) {
          id = id.substring(4, id.length)
        }
        ids.push(parseInt(id))
        idList[id + ''] = oldId
      })
      RiskService.getFxlist(ids).then((data) => {
        if (data) {
          data.forEach((element) => {
            if (
              iamAuditEvents.findIndex(
                (i) => i.eventCode.toString() === element.eventCode.toString()
              ) === -1
            ) {
              const mmc = {}
              mmc.sourceId = element.id
              mmc.id = null
              mmc.eventTypePath = element.riskCategoryPath
              mmc.eventType = element.riskCategoryId.toString()
              mmc.mtxVersionId = parseInt(this.versionId)
              // 没用的字段，用来存实际ID
              mmc.sortNum = idList[element.id + '']
              const opt = element.competentDeptOpt
              const name = element.competentDeptName
              const id = element.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)
                  }
                })
                mmc.competentDeptOpt = JSON.stringify(opt)
              } else {
                if (element.competentDeptOpt) {
                  mmc.competentDeptOpt = JSON.stringify(element.competentDeptOpt)
                } else {
                  mmc.competentDeptOpt = JSON.stringify([])
                }
              }
              mmc.versionId = parseInt(this.FxversionId)
              let tyy =
                'eventCode;eventName;competentDeptName;competentDeptId;occurPossibility;riskImpactDegree;riskLevel;'
              tyy +=
                'auditOrgId;eventDesc;riskSource;riskReasonDesc;status;creationTime;creatorName;remark;creatorName;creationTime'
              // tyy = 'eventCode;eventName;riskSource;creatorName'
              const tyys = tyy.split(';')
              tyys.forEach((y) => {
                mmc[y] = element[y]
              })
              // mmc.competentDeptId = parseInt(mmc.competentDeptId)
              iamAuditEvents.push(mmc)
            }
          })
          this.visible = false
          this.$refs.docform.setFieldValue('icMtxMeasureEventList', iamAuditEvents)
        }
      })
    },
    initParam(model) {
      if (!this.flag) {
        if (this.$route.query.versionId) {
          this.getpath(this.$route.query.catalogId).then(() => {
            this.$refs.docform.mtxPrcPath = this.catpath
            model.mtxPrcPath = this.catpath
          })
          this.getsortNum(this.$route.query.catalogId).then(() => {
            this.$refs.docform.sortNum = this.sortNum
            model.sortNum = this.sortNum
          })
        } else {
          this.getpath(model.mtxPrcId).then(() => {
            this.$refs.docform.mtxPrcPath = this.catpath
            model.mtxPrcPath = this.catpath
          })
          this.versionId = model.mtxVersionId + ''
          this.orgId = model.auditOrgId + ''
        }
        // 默认风险事项
        this.icMtxMeasureEventListChange(model.icMtxMeasureEventList)
        // 根据orgId 获取到风险库版本ID
        this.FxversionId = null
        RiskService.getversion(this.orgId).then((res) => {
          if (res.data.id) {
            this.FxversionId = res.data.id.toString()
          }
        })
        if (model.icMtxMeasureLawList) {
          model.icMtxMeasureLawList.forEach((i) => {
            if (i.clauses === null) {
              i.clauses = ''
            }
          })
        }
        // 处理icMtxMeasureEventList 中的主管部门高级字段
        const measurelist = model.icMtxMeasureEventList
        if (measurelist !== null && measurelist !== undefined) {
          measurelist.forEach((l) => {
            const opt = JSON.parse(l.competentDeptOpt)
            const name = l.competentDeptName
            const id = l.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)
                }
              })
              l.competentDeptOpt = JSON.stringify(opt)
            }
          })
          model.icMtxMeasureEventList = measurelist
        }
        this.flag = true
      }
      return true
    },
    getpath(id) {
      return new Promise((resolve, reject) => {
        MtxProcessService.findupcatinfo(id).then((res) => {
          this.catpath = res.data
          resolve(res.data)
        })
      })
    },
    getsortNum(id) {
      return new Promise((resolve, reject) => {
        MtxProcessService.fngetsortNum(id).then((res) => {
          this.sortNum = res
          resolve(res)
        })
      })
    },
    showflpath() {
      this.catvisible = !this.catvisible
      if (this.catvisible) {
        setTimeout(() => {
          this.$refs.mtxprocesstree.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('mtxPrcPath', this.catpath)
        this.$refs.docform.setFieldValue('mtxPrcId', 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('mtxVersionId')
        this.orgId = this.$refs.docform.getFieldValue('auditOrgId')
      }
      data.mtxVersionId = this.versionId
      return data
    },
    // 页面加载完成后
    sdFormReady() {
      this.mode = this.$refs.docform.formData.mode
      if (!this.mode) {
        this.mode = this.$route.query.mode
      }
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    saved() {
      Message.success({ content: '保存成功！' }, 1).then(() => {
        debugger
        this.close(true)
      })
    },
    // 保存
    saveForm() {
      // 保存时校验必填
      this.checkIcMtxMeasureEventListRequire(
        this.$refs.docform.getFieldValue('icMtxMeasureEventList')
      )
      this.$refs.docform.validateFields().then((res) => {
        if (res) {
          // 如果是新文档，则赋值 mtxPrcId
          // 校验编号唯一
          const measureCode = this.$refs.docform.getFieldValue('measureCode')
          const id = this.$refs.docform.getFieldValue('id')
            ? this.$refs.docform.getFieldValue('id')
            : -1
          const mtxVersionId = parseInt(this.versionId)
          const auditOrgId = parseInt(this.orgId)
          MtxProcessService.checkMeasurecode(measureCode, id, mtxVersionId, auditOrgId).then(
            (res) => {
              if (!res.data) {
                Message.info('编号重复请重新填写', 1)
              } else {
                let versionId = null
                if (this.$route.query.record === null || this.$route.query.record === undefined) {
                  const catalogId = this.$route.query.catalogId
                  const orgId = this.$route.query.orgId
                  versionId = parseInt(this.$route.query.versionId)
                  this.$refs.docform.setFieldValue('mtxPrcId', parseInt(catalogId))
                  this.$refs.docform.setFieldValue('auditOrgId', parseInt(orgId))
                  this.$refs.docform.setFieldValue('mtxVersionId', versionId)
                } else {
                  versionId = this.$refs.docform.getFieldValue('mtxVersionId')
                }
                // 轮询所有子表赋值versionId

                // 处理icMtxMeasureEventList 中的主管部门高级字段
                const measurelist = this.$refs.docform.getFieldValue('icMtxMeasureEventList')
                if (measurelist !== null && measurelist !== undefined) {
                  measurelist.forEach((l) => {
                    const opt = JSON.parse(l.competentDeptOpt)
                    const nopt = []
                    opt.forEach((o) => {
                      if (o.code.indexOf('_sd') === -1) {
                        nopt.push(o)
                      }
                    })
                    l.auditOrgId = auditOrgId
                    l.competentDeptOpt = JSON.stringify(nopt)
                  })
                  this.$refs.docform.setFieldValue('icMtxMeasureEventList', measurelist)
                }
                this.$refs.docform.saveBtnClick()
              }
            }
          )
        } else {
          return false
        }
      })
    },
    measureRelSelect() {
      if (this.FxversionId) {
        this.$refs.icRiskeventsel.openPicker()
      } else {
        Modal.info({
          content: '请配置机构对应的风险库',
        })
      }
    },

    fndeal(obj) {
      const newobj = []
      if (obj !== undefined) {
        obj.forEach((item) => {
          if (
            [
              'icMtxMeasureLawList',
              'icMtxMeasureEventList',
              'icMtxMeasureStepList',
              'icMtxMeasureResultList',
              'iamDetailFormModifyLogEntities',
              'mtxPrcId',
              'mtxPrcPath',
            ].indexOf(item.fieldName) < 0
          ) {
            if (item.newValue !== '' && item.oldValue !== null) {
              item.xt = item.creatorName + '_' + item.creationTime
              if (item.oldValue.trim() === null || item.oldValue.trim() === 'null')
                item.oldValue = ''
              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('icMtxMeasureLawList')) {
        iamAuditLaws = this.$refs.docform.getFieldValue('icMtxMeasureLawList')
      }
      keyinfos.forEach((element) => {
        const mmc = {}
        mmc.title = element.docTitle
        mmc.docNum = element.dispatchWord ? element.dispatchWord : ''
        mmc.mtxVersionId = this.versionId
        mmc.clauses = ''
        iamAuditLaws.push(mmc)
      })
      this.visible = false
      this.$refs.docform.setFieldValue('icMtxMeasureLawList', 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;
  }
}
.btnfxselect {
  position: relative;
  right: 200px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-left: 10px;
  }
}
.tablexm tr td {
  border: none !important;
}
</style>
