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

        <table v-show="part1Expand">
          <tr>
            <!-- 案例名称 -->
            <sd-form-item-td name="title" />
            <!-- 案件类别 -->
            <sd-form-item-td name="caseType" />
          </tr>
          <tr>
            <!-- 案件描述 -->
            <sd-form-item-td name="caseDesc" :colspan="3">
              <a-textarea v-model="model.caseDesc" :auto-size="{ maxRows: 3, minRows: 3 }" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 发生年份 -->
            <!-- <td class="ant-form-item-label ant-form-item-label"
              ><label title="发生年份" class="">发生年份</label></td
            >
            <td>
              <a-date-picker
                v-model="defaultValyears"
                placeholder="请选择年"
                mode="year"
                :open="dataopen"
                format="YYYY"
                :allow-clear="true"
                @openChange="openChangeYear"
                @panelChange="panelChangeYear"
            /></td> -->
            <sd-form-item-td name="caseYear">
              <a-date-picker
                v-model="defaultValyears"
                placeholder="请选择年"
                mode="year"
                :open="dataopen"
                format="YYYY"
                :allow-clear="true"
                @openChange="openChangeYear"
                @panelChange="panelChangeYear"
              />
            </sd-form-item-td>
            <!-- 案例来源 -->
            <sd-form-item-td name="caseSource" />
          </tr>
          <tr>
            <!-- 经验与教训启示 -->
            <sd-form-item-td name="lessons" :colspan="3">
              <a-textarea v-model="model.lessons" :auto-size="{ maxRows: 3, minRows: 3 }" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 编制日期 -->
            <sd-form-item-td v-if="initParam()" name="releaseDate" />
          </tr>
          <tr>
            <!-- 创建单位 -->
            <sd-form-item-td name="createDeptName" />
          </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>
          <tr
            ><td :colspan="4">
              <sd-form-item name="riskCaseEventList" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="part2Expand"
                    :expand-str="'part2Expand'"
                    :group-label="'相关风险事项'"
                    @changedClick="changedClick"
                  >
                    <template>
                      <risk-identification-child-table
                        ref="docformMeasureRel"
                        v-model="model.riskCaseEventList"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :select-data="true"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.riskCaseEventList.attr.dync))
                        "
                        :columns="columns"
                        @select="measureRelSelect"
                      >
                      </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"
        :version-id="this.FxversionId"
        :types="'FK'"
        :org-id="this.orgId"
        :org-name="this.orgName + '风险库'"
        :single="false"
        :read-only="false"
        @change="fnqd"
      ></ic-measure-picker>
    </div>
  </div>
</template>

<script>
import moment from 'moment'
import { Modal } from '@/common/one-ui'
import { getUserInfo } from '@/common/store-mixin'
import icMeasurePicker from '@product/iam/components/ic-picker/ic-measure-picker.vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import CommonService from '../../core/api/common-service'
import riskService from '../risklib/risk-service'
import riskTasksService from '../task/risk-tasks-service'
import riskIdentificationChildTable from '../task/riskIdentification/components/risk-identification-child-table.vue'
import components from './_import-components/risk-case-form-import'
export default {
  name: 'RiskCaseForm',
  metaInfo: {
    title: '风险案例',
  },
  components: {
    ...components,
    icMeasurePicker,
    riskIdentificationChildTable,
    auditAdvancedGroup,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      defaultValyears: moment().format('YYYY'),
      part1Expand: true,
      part2Expand: true,
      dataopen: false,
      eventSelect: [],
      FxversionId: null,
      FxversionCode: null,
      orgId: null,
      orgName: null,
      columns: [
        { dataIndex: 'id', sdHidden: true },
        { dataIndex: 'parentId', sdHidden: true },
        { dataIndex: 'versionId', sdHidden: true },
        { dataIndex: 'riskCategoryId', sdHidden: true },
        { dataIndex: 'eventId', sdHidden: true },
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },

        { dataIndex: 'eventName' },
        { dataIndex: 'eventCode' },
        { dataIndex: 'riskCategoryPath' },
        { dataIndex: 'versionCode' },
      ],
    }
  },
  created() {
    // 获取当前用户所属风控机构的风险库
    CommonService.getCurrentUserCompany().then((res1) => {
      this.orgName = res1.name
      riskTasksService.findIamOrgId(res1.id, 'riskLibraryVersion').then((res2) => {
        if (res2.data) {
          this.orgId = res2.data.toString()
          riskService.getversion(this.orgId).then((res) => {
            if (res.data.id) {
              this.FxversionId = res.data.id.toString()
              this.FxversionCode = res.data.versionCode
            }
          })
        }
      })
    })
  },
  mounted() {
    const caseYear = this.$refs.flow.FlowData.processFormData.processFormPropertyValues.find(
      (item) => item.name === 'caseYear'
    )?.value
    if (this.$route.query.businessTypeId === '' || this.$route.query.businessTypeId === undefined) {
      this.defaultValyears =
        caseYear === ''
          ? this.defaultValyears
          : moment(new Date().setFullYear(caseYear)).format('YYYY')

      this.$refs.flow.setFieldValue('caseYear', caseYear + '') // 字段caseYear赋值字符串类型的值 add zhangtt 2023-2-24
    } else {
      this.$refs.flow.setFieldValue('caseYear', this.defaultValyears + '')
    }
  },
  methods: {
    // 点击选择框事件 弹出日期组件选择年
    openChangeYear(status) {
      if (status) {
        this.dataopen = true
      } else {
        this.dataopen = false
      }
    },
    // 选择年之后 关闭弹框
    panelChangeYear(value) {
      this.dataopen = false
      this.defaultValyears = moment(value).format('YYYY')
      this.$refs.flow.setFieldValue('caseYear', this.defaultValyears)
    },
    initParam(val) {
      var flow = this.$refs.flow
      if (flow === undefined) {
        return false
      }
      if (flow.getFieldValue('releaseDate') === undefined) {
        flow.setFieldValue('releaseDate', flow.getFieldValue('creationTime'))
      }
      return true
    },
    measureRelSelect() {
      if (this.FxversionId) {
        this.$refs.icRiskeventsel.openPicker()
      } else {
        Modal.info({
          content: '请配置机构对应的风险库',
        })
      }
    },
    fnqd(data) {
      const ids = []
      let iamAuditEvents = []
      if (this.$refs.flow.getFieldValue('riskCaseEventList')) {
        iamAuditEvents = this.$refs.flow.getFieldValue('riskCaseEventList')
      }
      data.forEach((i) => {
        let id = i.id.toString()
        if (id.indexOf('1000') > -1) {
          id = id.substring(4, id.length)
        }
        if (iamAuditEvents.findIndex((i) => i.eventId.toString() === id) === -1) {
          ids.push(parseInt(id))
        }
      })

      riskService.getFxlist(ids).then((data) => {
        if (data) {
          data.forEach((element) => {
            if (
              iamAuditEvents.findIndex(
                (i) => i.eventCode.toString() === element.eventCode.toString()
              ) === -1
            ) {
              const mmc = {}
              mmc.id = null
              mmc.riskCategoryPath = element.riskCategoryPath
              mmc.riskCategoryId = element.riskCategoryId.toString()
              mmc.versionId = parseInt(this.FxversionId)
              mmc.eventCode = element.eventCode
              mmc.eventName = element.eventName
              mmc.eventId = element.id
              mmc.versionCode = this.FxversionCode
              iamAuditEvents.push(mmc)
            }
          })
          this.visible = false
          this.$refs.flow.setFieldValue('riskCaseEventList', iamAuditEvents)
        }
      })
    },
    validForm() {
      return new Promise((resolve, reject) => {
        this.$refs.flow.setFieldValue('caseYear', this.defaultValyears)
        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;
  }
}
</style>
