<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :validate-form="validForm"
      :class="$style.ristTasksForm"
      @saveproject="saveproject"
    >
      <template v-slot:form="{ model, fields }">
        <div v-show="loading" :class="$style.loadingDiv">
          <a-spin :spinning="true" tip="加载数据中..." />
        </div>
        <table>
          <tr>
            <td style="border: none">
              <audit-advanced-group
                :expand="planExpand"
                :expand-str="'planExpand'"
                :group-label="'基本信息'"
                tablestyle="''"
                @changedClick="changedClick"
              ></audit-advanced-group>
            </td>
          </tr>
        </table>

        <table v-show="planExpand">
          <tr v-show="initData(model)">
            <!-- 随机ID -->
            <sd-form-item-td name="randomId"> </sd-form-item-td>
            <sd-form-item-td name="id"> </sd-form-item-td>
            <sd-form-item-td name="taskId"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 标题 -->
            <sd-form-item-td name="title"> </sd-form-item-td>
            <!-- 风险识别类型 -->
            <sd-form-item-td name="identifyType" component="a-checkbox-group"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 编制日期 -->
            <sd-form-item-td name="creationTime"> </sd-form-item-td>
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="prove" :colspan="3">
              <a-textarea v-model="model.prove" :auto-size="{ maxRows: 3, minRows: 3 }" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment
                  v-model="model.attachment"
                  :group-id="JSON.parse(fields.attachment.value).value"
                  :read-only="!editable"
                ></sd-attachment>
              </template>
            </sd-form-item-td>
          </tr>
        </table>

        <!-- 新增风险事件 -->
        <table v-show="model.identifyType && model.identifyType.includes('insert')">
          <tr
            ><td :colspan="4">
              <sd-form-item name="riskIdentifyInsertMatterEntitys" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="addExpand"
                    expand-str="addExpand"
                    group-label="新增风险事件"
                    @changedClick="changedClick"
                  >
                    <template>
                      <risk-identification-child-table
                        ref="insertTable"
                        v-model="model.riskIdentifyInsertMatterEntitys"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :add-data="true"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.riskIdentifyInsertMatterEntitys.attr.dync))
                        "
                        :columns="columns"
                        :type="'add'"
                        :deleted-identify="deletedIdentify"
                        @add="addData"
                      >
                        <span slot="eventName" slot-scope="{ text, record }">
                          <a @click="openDoc(record, 'add', editable)">{{ text }}</a>
                        </span>
                      </risk-identification-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item>
            </td>
          </tr>
        </table>

        <!-- 修改风险事件 -->
        <table v-show="model.identifyType && model.identifyType.includes('update')">
          <tr
            ><td :colspan="4">
              <sd-form-item name="riskIdentifyUpdateMatterEntitys" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="selectExpand"
                    expand-str="selectExpand"
                    group-label="修改"
                    @changedClick="changedClick"
                  >
                    <template>
                      <risk-identification-child-table
                        ref="updateTable"
                        v-model="model.riskIdentifyUpdateMatterEntitys"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :select-data="true"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.riskIdentifyUpdateMatterEntitys.attr.dync))
                        "
                        :columns="columns"
                        :type="'update'"
                        :deleted-identify="deletedIdentify"
                        @select="selectData('update')"
                      >
                        <span slot="eventName" slot-scope="{ text, record }">
                          <a @click="openDoc(record, 'update', editable)">{{ text }}</a>
                        </span>
                      </risk-identification-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item>
            </td>
          </tr>
        </table>

        <!-- 废弃风险事件 -->
        <table v-show="model.identifyType && model.identifyType.includes('delete')">
          <tr
            ><td :colspan="4">
              <sd-form-item name="riskIdentifyDeleteMatterEntitys" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="trashExpand"
                    expand-str="trashExpand"
                    group-label="废弃"
                    @changedClick="changedClick"
                  >
                    <template>
                      <risk-identification-child-table
                        ref="removeTable"
                        v-model="model.riskIdentifyDeleteMatterEntitys"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :select-data="true"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.riskIdentifyDeleteMatterEntitys.attr.dync))
                        "
                        :columns="columns"
                        :type="'remove'"
                        :deleted-identify="deletedIdentify"
                        @select="selectData('remove')"
                      >
                        <span slot="eventName" slot-scope="{ text, record }">
                          <a @click="openDoc(record, 'remove', false)">{{ text }}</a>
                        </span>
                      </risk-identification-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item>
            </td>
          </tr>
        </table>
      </template>
    </sd-webflow>
    <!-- 风险事项选择器-->
    <div v-show="false">
      <ic-measure-picker
        ref="icRiskeventsel"
        v-model="eventSelect"
        :is-abandonment="isAbandonment"
        :version-id="FxversionId"
        types="FK"
        :org-id="auditOrgId + ''"
        :org-name="auditOrgName + '风险库'"
        :single="false"
        :read-only="false"
        @change="fnSelectRiskInfo"
      ></ic-measure-picker>
    </div>
  </div>
</template>

<script>
import FlowService from '@/webflow/flow-service'
import axios from '@/common/services/axios-instance'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import { Modal, message } from '@/common/one-ui'
import icMeasurePicker from '@product/iam/components/ic-picker/ic-measure-picker.vue'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import riskTasksService from '@product/iam/risk/task/risk-tasks-service'
import riskService from '@product/iam/risk/risklib/risk-service'
import riskIdentificationService from './risk-identification-service'
import riskIdentificationChildTable from './components/risk-identification-child-table.vue'
import components from './_import-components/risk-identification-form-import'
// 修改主子表的首行title名
export default {
  name: 'RiskIdentificationForm',
  metaInfo: {
    title: '风险识别',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    riskIdentificationChildTable,
    icMeasurePicker,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      isSubmit: false,
      isAbandonment: 'NO',
      loading: false,
      spinning: false,
      eventSelect: [],
      childTableKey: 0, // 刷新子表组件
      inited: true,
      planExpand: true,
      addExpand: true,
      selectExpand: true,
      trashExpand: true,
      expand: true,
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'riskCategoryPath',
          title: '风险分类',
        },
        { dataIndex: 'eventCode', title: '风险事项编号', defaultSortOrder: 'ascend' },
        {
          dataIndex: 'eventName',
          title: '风险事项名称',
        },
        { dataIndex: 'riskSource', title: '风险源' },
        { dataIndex: 'competentDeptName', title: '主管部门' },
        {
          dataIndex: 'isUpdate',
          title: '是否新增、修改、废弃',
          sdHidden: true,
        },
        {
          dataIndex: 'id',
          title: 'ID',
          sdHidden: true,
        },
        {
          dataIndex: 'randomId',
          title: 'randomId',
          sdHidden: true,
        },
        {
          dataIndex: 'identifyId',
          title: '风险事项ID',
          sdHidden: true,
        },
        {
          dataIndex: 'versionId',
          title: '风险版本库ID',
          sdHidden: true,
        },
        {
          dataIndex: 'unitCode',
          sdHidden: true,
        },
        {
          dataIndex: 'contactsId',
          sdHidden: true,
        },
        {
          dataIndex: 'contactsAccount',
          sdHidden: true,
        },
        {
          dataIndex: 'contactsName',
          sdHidden: true,
        },
        {
          dataIndex: 'eventId',
          sdHidden: true,
        },
      ],
      expressions: [],
      riskCriteriaDict: [],
      isSave: true, // 是否有保存操作
      riskDutieUnitList: [],
      sourceId: -1,
      unitOpt: [],
      riskCriteriaObj: null, // 风险准则
      riskid: null, // 风险识别ID
      taskInfo: {}, // 风险任务信息
      auditOrgId: null, // 审计机构ID，选择风险事项需要用
      auditOrgName: null, // 审计机构名称，选择风险事项需要用
      FxversionId: null, // 风险库版本
      selectType: null, // 选择类型 修改或者废弃
      identifyType: null, // 识别类型
      isIni: false,
      identifyId: null, // 识别ID保存之后才有
    }
  },
  computed: {
    // 计算随机key
    randomId() {
      let randomNum = Math.random()
      while (randomNum === 0) {
        randomNum = Math.random()
      }
      const time = new Date().getTime()
      return time + Math.ceil(randomNum * 1000000000)
    },
  },
  watch: {
    identifyType(val) {
      this.$refs.insertTable.$refs.childTable.reset()
      this.$refs.updateTable.$refs.childTable.reset()
      this.$refs.removeTable.$refs.childTable.reset()
      if (!val.includes('insert')) {
        this.$refs.flow.setFieldValue('riskIdentifyInsertMatterEntitys', [])
      }
      if (!val.includes('update')) {
        this.$refs.flow.setFieldValue('riskIdentifyUpdateMatterEntitys', [])
      }
      if (!val.includes('delete')) {
        this.$refs.flow.setFieldValue('riskIdentifyDeleteMatterEntitys', [])
      }
    },
  },
  created() {
    // 监听关闭事件，关闭时如果没有保存操作且没有id，则直接删除所有子表
    window.addEventListener('beforeunload', (e) => {
      this.beforeunloadHandler(e)
    })
  },
  methods: {
    beforeunloadHandler(e) {
      if (this.isSubmit) return
      const updateData = this.$refs.flow
        .getFieldValue('riskIdentifyUpdateMatterEntitys')
        .filter((item) => {
          return item.isAddItem === true
        })
        .map((item) => {
          return item.id
        })
      const deleteData = this.$refs.flow
        .getFieldValue('riskIdentifyDeleteMatterEntitys')
        .filter((item) => {
          return item.isAddItem === true
        })
        .map((item) => {
          return item.id
        })
      this.deletedIdentify(updateData, 'update')
      this.deletedIdentify(deleteData, 'remove')
    },
    deletedIdentify(ids, type) {
      if (ids.length === 0) return
      const strid = ids.join(',')
      axios({
        url:
          'api/xcoa-mobile/v1/riskidentify/deletedIdentify?ids=' + strid + '&deletedType=' + type,
        method: 'post',
      })
    },
    // 保存之后防止子表被覆盖，重新获取一下
    saveproject() {
      this.refreshAddDataTable()
      this.refreshUpdateDataTable()
      this.refreshRemoveDataTable()
    },
    // 刷新新增子表
    refreshAddDataTable() {
      riskIdentificationService
        .getRiskAddChildInfo({ identifyId: parseFloat(this.riskid) })
        .then((res) => {
          const newdata = res.data.sort((a, b) => {
            return a.eventCode.localeCompare(b.eventCode)
          })
          this.$refs.flow.setFieldValue('riskIdentifyInsertMatterEntitys', newdata)
        })
    },
    // 刷新修改子表
    refreshUpdateDataTable() {
      const data = this.$refs.flow.getFieldValue('riskIdentifyUpdateMatterEntitys') || []
      riskIdentificationService
        .getRiskUpdateChildInfo({ identifyId: parseFloat(this.riskid) })
        .then((res) => {
          if (data.length === 0) {
            const newdata = res.data.sort((a, b) => {
              return a.eventCode.localeCompare(b.eventCode)
            })
            this.$refs.flow.setFieldValue('riskIdentifyUpdateMatterEntitys', newdata)
            return
          }
          const newdata = data.map((dataItem) => {
            // 没有ID说名是新增的，增加标识
            const item = res.data.find((item) => {
              return dataItem.eventId === item.eventId
            })
            // 有ID直接返回，说明不是新增数据
            if (dataItem.id) {
              return item
            }
            item.isAddItem = true
            return item
          })
          newdata.sort((a, b) => {
            return a.eventCode.localeCompare(b.eventCode)
          })
          this.$refs.flow.setFieldValue('riskIdentifyUpdateMatterEntitys', newdata)
        })
    },

    // 刷新废弃表
    refreshRemoveDataTable() {
      const data = this.$refs.flow.getFieldValue('riskIdentifyDeleteMatterEntitys') || []
      riskIdentificationService
        .getRiskRemoveChildInfo({ identifyId: parseFloat(this.riskid) })
        .then((res) => {
          if (data.length === 0) {
            const newdata = res.data.sort((a, b) => {
              return a.eventCode.localeCompare(b.eventCode)
            })
            this.$refs.flow.setFieldValue('riskIdentifyDeleteMatterEntitys', newdata)
            return
          }
          const newdata = data.map((dataItem) => {
            if (dataItem.id) return dataItem
            // 没有ID说名是新增的，增加标识
            const item = res.data.find((item) => {
              return dataItem.eventId === item.eventId
            })
            item.isAddItem = true
            return item
          })
          newdata.sort((a, b) => {
            return a.eventCode.localeCompare(b.eventCode)
          })
          this.$refs.flow.setFieldValue('riskIdentifyDeleteMatterEntitys', newdata)
        })
    },

    // 打开子表数据
    openDoc(record, type, editable) {
      // 新增，直接根据ID打开
      let openurl
      // 如果是不可编辑，则直接传view
      let mode = ''
      if (!editable) {
        mode = '&mode=view'
      }
      if (type === 'add') {
        openurl = `/risk-identification-event-add-form?record=${record.id}&infoId=${this.riskid}&orgId=${this.auditOrgId}&versionId=${this.FxversionId}&orgName=${this.auditOrgName}${mode}`
      } else if (type === 'update') {
        // 如果有ID了，则直接赋值ID
        let identifyId = ''
        if (this.identifyId) {
          identifyId = '&identifyId=' + this.identifyId
        }
        openurl = `/risk-identification-event-update-form?${
          record.id ? '&record=' + record.id : ''
        }&taskId=${this.$refs.flow?.getFieldValue('taskId')}&infoId=${this.riskid}${
          record.eventId ? '&eventId=' + record.eventId : ''
        }&orgId=${this.auditOrgId}&versionId=${this.FxversionId}&orgName=${
          this.auditOrgName
        }${identifyId}${mode}`
      } else {
        let identifyId = ''
        if (this.identifyId) {
          identifyId = '&identifyId=' + this.identifyId
        }
        openurl = `/risk-identification-event-update-form?taskId=${this.$refs.flow?.getFieldValue(
          'taskId'
        )}&infoId=${this.riskid}${record.eventId ? '&eventId=' + record.eventId : ''}&orgId=${
          this.auditOrgId
        }&versionId=${this.FxversionId}&orgName=${this.auditOrgName}${identifyId}${mode}&isDelete=Y`
      }
      crossWindowWatcher.waitForChanged(openurl).then((info) => {
        if (type === 'add') {
          // 这里是新增的刷新的方法
          this.refreshAddDataTable()
        } else {
          // 这里是新增的刷新的方法
          this.refreshUpdateDataTable()
        }
      })
    },
    // 选择风险事项之后
    fnSelectRiskInfo(data) {
      const ids = []
      let iamAuditEvents = []
      let childTableName
      if (this.selectType === 'update') {
        childTableName = 'riskIdentifyUpdateMatterEntitys'
      } else {
        childTableName = 'riskIdentifyDeleteMatterEntitys'
      }
      if (this.$refs.flow.getFieldValue(childTableName)) {
        iamAuditEvents = this.$refs.flow.getFieldValue(childTableName)
      }
      let hasRepeat = false
      data.forEach((i) => {
        let id = i.id.toString()
        if (id.indexOf('1000') > -1) {
          id = id.substring(4, id.length)
        }
        if (iamAuditEvents.findIndex((item) => item.eventId.toString() === id.toString()) === -1) {
          ids.push(parseInt(id))
        } else {
          hasRepeat = true
        }
      })
      if (hasRepeat) {
        message.info('请勿选择重复数据')
      }
      // 获取选择的事项内容
      riskService
        .getFxlist(ids)
        .then((data) => {
          if (data) {
            data.forEach((element) => {
              const mmc = element
              mmc.eventId = element.id
              mmc.randomId = this.riskid
              mmc.riskCategoryPath = this.auditOrgName + '风险库/' + mmc.riskCategoryPath
              mmc.competentDeptOpt = JSON.stringify(element.competentDeptOpt)
              mmc.isAddItem = true
              iamAuditEvents.push(mmc)
            })
            this.visible = false
            this.$refs.flow.setFieldValue(childTableName, iamAuditEvents)
          }
          data.forEach((item) => {
            item.competentDeptOpt = []
          })
          // 保存子表
          if (this.selectType === 'update') {
            riskIdentificationService
              .saveUpdateMatter(data, this.$refs.flow.getFieldValue('id'))
              .then(() => {
                data.forEach((item) => {
                  item.id = null
                })
                this.refreshUpdateDataTable()
              })
          } else {
            riskIdentificationService
              .saveRemoveMatter(data, this.$refs.flow.getFieldValue('id'))
              .then(() => {
                data.forEach((item) => {
                  item.id = null
                })
                this.refreshRemoveDataTable()
              })
          }
        })
        .catch(() => {
          message.error('请选择风险事项')
        })
      this.eventSelect = []
    },
    // 获取风险任务信息
    getRiskTaskInfo(taskId) {
      this.loading = true
      riskTasksService.getRiskTaskInfo(taskId).then((res) => {
        this.taskInfo = res.data.pageFormData.pageFieldInfos
        if (!this.$refs.flow.getFieldValue('title')) {
          // 标题赋值
          this.$refs.flow?.setFieldValue(
            'title',
            this.taskInfo.find((item) => item.name === 'dutieName').value + '的风险识别'
          )
        }

        this.auditOrgName = this.taskInfo.find((item) => item.name === 'inspectUnitName').value
        // 获取发起机构对应的审计机构ID
        riskIdentificationService
          .findIamOrgId(this.taskInfo.find((item) => item.name === 'inspectUnitId').value)
          .then((res) => {
            this.auditOrgId = res.data
            // 获取风控库版本
            return riskService.getversion(parseFloat(this.auditOrgId))
          })
          .then((res) => {
            this.loading = false
            if (res.data.id) {
              this.FxversionId = res.data.id.toString()
            } else {
              message.info('当前所属机构未设置风险库版本，请联系管理员')
            }
          })
          .catch(() => {
            message.info('未获取到当前组织所属风险机构，请联系管理员', 1).then(() => {
              window.opener = window
              var win = window.open('', '_self')
              win.close()
            })
          })
      })
    },
    initData(model) {
      if (!this.$refs.flow) return // 没有加载出来表单组件，先退出
      // 保存之后，需要把riskid重新赋值，否则还是随机ID
      if (this.$refs.flow.FlowData.processFormData.beanId) {
        this.riskid = this.$refs.flow.FlowData.processFormData.beanId
        this.identifyId = this.$refs.flow.FlowData.processFormData.beanId
      }
      if (model.id !== undefined) {
        this.riskid = model.id
      } else {
        // 如果是新建，则直接传随机id
        this.riskid = this.randomId
      }
      // 赋值任务ID，后面都要用
      if (this.$route.query.extParams) {
        const params = JSON.parse(this.$route.query.extParams)
        if (params.taskId) {
          this.$refs.flow?.setFieldValue('taskId', params.taskId ? parseFloat(params.taskId) : null)
        }
      }
      // 加载时获取风险任务信息只有起草环节才赋值
      if (!this.isIni) {
        // 打开的时候获取一下子表数据
        this.saveproject()
        this.getRiskTaskInfo(this.$refs.flow?.getFieldValue('taskId'))
        this.$refs.flow?.setFieldValue('randomId', this.riskid)
        this.isIni = true
      }

      this.identifyType = model.identifyType
      return false
    },
    // 新增风险事项
    addData(type) {
      // 如果有ID了，则直接赋值ID
      let identifyId = ''
      if (this.identifyId) {
        identifyId = '&identifyId=' + this.identifyId
      }
      const openurl = `/risk-identification-event-add-form?taskId=${this.$refs.flow?.getFieldValue(
        'taskId'
      )}&orgId=${this.auditOrgId}&versionId=${this.FxversionId}&orgName=${
        this.auditOrgName
      }&type=add&infoId=${this.riskid}${identifyId}`
      crossWindowWatcher.waitForChanged(openurl).then((refreshFlag) => {
        if (refreshFlag) {
          // 这里写或者调刷新的方法
          this.refreshAddDataTable()
        }
      })
    },
    selectData(type) {
      this.selectType = type
      if (type === 'update') {
        this.isAbandonment = 'NO'
      } else {
        this.isAbandonment = 'YES'
      }
      this.$refs.icRiskeventsel.openPicker()
    },
    validForm() {
      this.isSubmit = true
      return Promise.resolve(true)
    },
  },
}
</script>

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

.btnselect {
  position: relative;
  top: 4px;
  float: right;
  .batchselect {
    z-index: 100;
    margin-right: 80px;
  }
}
.rist_tasks_form {
  :global(.ant-calendar-picker) {
    width: 100%;
  }
  .type_td {
    border-right: none !important;
  }
}
.loading-div {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  flex-direction: column;
  z-index: 10;
  background: rgb(255 255 255 / 70%);
}
</style>
