<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :validate-form="validForm"
      :class="$style.ristTasksForm"
      @actionBtnClick="actionBtnClick"
      @saveproject="saveproject"
    >
      <template v-slot:form="{ model, fields }">
        <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="id" /> -->
            <!-- 随机ID -->
            <!-- <sd-form-item-td name="sourceId" /> -->
          </tr>
          <tr>
            <!-- 计划年度 -->
            <sd-form-item-td name="year">
              <template v-slot:read-and-edit="{ editable }">
                <a-select v-if="!isTaskWork && editable" v-model="model.year">
                  <a-select-option v-for="year in yearArry" :key="year + ''">
                    {{ year }}
                  </a-select-option>
                </a-select>
                <span v-if="isTaskWork || !editable">{{ model.year }}</span>
              </template>
            </sd-form-item-td>
            <!-- 发起机构 -->
            <sd-form-item-td name="inspectUnitOpt" :hidden="true"> </sd-form-item-td>
            <sd-form-item-td name="inspectUnitId" :hidden="true"> </sd-form-item-td>
            <sd-form-item-td name="inspectUnitName" label="发起机构">
              <template v-slot:read-and-edit="{ editable }">
                {{ model.inspectUnitName }}
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 任务名称 -->
            <sd-form-item-td name="dutieName" />
            <!-- 任务编号 -->
            <sd-form-item-td name="dutieCode">
              <template v-slot:read-and-edit="{ editable }">
                {{ model.dutieCode }}
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 任务开始时间 -->
            <sd-form-item-td name="dutieStartDate"> </sd-form-item-td>
            <!-- 任务结束时间 -->
            <sd-form-item-td name="dutieEndDate" range-after="dutieStartDate" />
          </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"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 任务描述 -->
            <sd-form-item-td name="dutieDesc" :colspan="3">
              <a-textarea v-model="model.dutieDesc" :auto-size="{ maxRows: 3, minRows: 3 }" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 任务类型 -->
            <sd-form-item-td
              name="dutieType"
              component="a-checkbox-group"
              :colspan="model.dutieType && model.dutieType.includes('RISK_ASSESSMENT') ? 1 : 3"
              :input-td-attrs="{
                class:
                  model.dutieType && model.dutieType.includes('RISK_ASSESSMENT')
                    ? ''
                    : $style.typeTd,
              }"
              @change="dutieTypeChange"
            />
            <!-- 风险准则 -->
            <sd-form-item-td
              name="riskCriteria"
              :hidden="
                model.dutieType && model.dutieType.includes('RISK_ASSESSMENT') ? false : true
              "
            >
              <template v-slot:read-and-edit="{ editable }">
                <a-select
                  v-if="editable"
                  v-model="riskCriteriaObj"
                  :options="riskCriteriaDict"
                  not-found-content="当前发起机构未配置可用风险准则"
                  @change="riskCriteriaChange"
                ></a-select>
                <span v-else>{{ model.riskCriteria }}</span>
              </template>
            </sd-form-item-td>
            <!-- 风险准则 -->
            <sd-form-item-td name="riskCriteriaId" :hidden="true" />
          </tr>
          <tr v-if="isTaskWork">
            <!-- 创建人 -->
            <sd-form-item-td name="creatorOpt" />
            <!-- 创建日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
          <tr v-if="!isTaskWork">
            <!-- 创建人 -->
            <sd-form-item-td name="creatorName">
              <template v-slot:read-and-edit>
                {{ model.creatorName }}
              </template>
            </sd-form-item-td>
            <!-- 创建日期 -->
            <sd-form-item-td name="creationTime">
              <template v-slot:read-and-edit>
                {{ model.creationTime | sdDateFormat('YYYY-MM-DD') }}
              </template>
            </sd-form-item-td>
          </tr>
        </table>

        <table>
          <tr
            ><td :colspan="4">
              <sd-form-item name="riskDutieUnitList" :label="null">
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="FpdwExpand"
                    :expand-str="'FpdwExpand'"
                    :group-label="'分派单位'"
                    @changedClick="changedClick"
                  >
                    <template>
                      <template>
                        <div :class="$style.wrapper">
                          <div v-show="FpdwExpand && editable" :class="$style.btnselect">
                            <a-button type="link" :class="$style.batchselect" @click="depSelect">
                              <a-icon type="check-circle" :theme="'filled'" />选择
                            </a-button>
                          </div>
                        </div>
                      </template>
                      <xm-child-table
                        ref="tabaData"
                        v-model="model.riskDutieUnitList"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :addbuttonvisiable="false"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.riskDutieUnitList.attr.dync))
                        "
                        :columns="columns"
                        :flagpage="true"
                      >
                        <!-- 联系单位 -->
                        <template v-slot:unitDeptMember="{ field, text, index, value }">
                          <audit-group-picker
                            v-model="value[index].unitDeptMemberObj"
                            :root-node="{ code: 0, name: '内控机构', id: 0 }"
                            :selectall="false"
                            :top-node-text="'内控机构'"
                            :treeparams="{
                              moduleId: 'iamOrg2',
                            }"
                            :single="true"
                            :read-only="!editable"
                          />
                        </template>
                        <!-- 联系人 -->
                        <template v-slot:contactsUserMember="{ field, text, index, value }">
                          <sd-user-picker
                            v-model="value[index].contactsUserMemberObj"
                            :single="true"
                            :read-only="!editable"
                          />
                        </template>
                      </xm-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item>
            </td>
          </tr>
        </table>

        <!-- 选择人员组件 -->
        <div v-show="false">
          <audit-group-picker
            ref="depSelect"
            v-model="unitOpt"
            :single="false"
            :read-only="false"
            :root-node="{ code: 0, name: '风控机构', id: 0 }"
            :selectall="false"
            :top-node-text="'风控机构'"
            :treeparams="{
              moduleId: 'iamOrg2',
            }"
            @change="depChange"
          />
        </div>
      </template>
    </sd-webflow>
  </div>
</template>

<script>
import moment from 'moment'
import riskService from '@product/iam/risk/risklib/risk-service'
import { Modal, message } from '@/common/one-ui'
import { getUserInfo } from '@/common/store-mixin'
import auditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
import auditAdvancedGroup from '@product/iam/components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '@product/iam/components/audit-advanced-group-mixins'
import riskIdentificationService from './riskIdentification/risk-identification-service'
import riskTasksService from './risk-tasks-service'
import components from './_import-components/risk-tasks-form-import'
// 修改主子表的首行title名
export default {
  name: 'RiskTasksForm',
  metaInfo: {
    title: '风险任务',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    auditGroupPicker,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      errorText: null, // 是否有错误提示
      childTableKey: 0, // 刷新子表组件
      inited: true,
      planExpand: true,
      FpdwExpand: true,
      expand: true,
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'unitName',
          title: '单位名称',
          width: '120px',
          sdHidden: true,
        },
        { dataIndex: 'unitDeptMember', title: '单位名称' },
        {
          title: '联系人',
          dataIndex: 'contactsName',
          sdHidden: true,
        },
        { dataIndex: 'contactsUserMember', title: '联系人' },
        {
          dataIndex: 'dutieId',
          sdHidden: true,
        },
        {
          dataIndex: 'unitId',
          sdHidden: true,
        },
        {
          dataIndex: 'unitCode',
          sdHidden: true,
        },
        {
          dataIndex: 'contactsId',
          sdHidden: true,
        },
        {
          dataIndex: 'contactsAccount',
          sdHidden: true,
        },
        {
          dataIndex: 'contactsName',
          sdHidden: true,
        },
      ],
      yearArry: [],
      expressions: [],
      riskCriteriaDict: [],
      isSave: true, // 是否有保存操作
      riskDutieUnitList: [],
      isTaskWork: false,
      unitOpt: [],
      riskCriteriaObj: null, // 风险准则
      auditOrgid: null,
    }
  },
  mounted() {
    // 日期下拉框初始化
    this.initDateSelect()
  },
  methods: {
    // 风险准则变化时
    riskCriteriaChange(val, option) {
      this.$refs.flow.setFieldValue('riskCriteriaId', val + '')
      this.$refs.flow.setFieldValue(
        'riskCriteria',
        this.riskCriteriaDict.find((item) => item.value === val).label
      )
    },
    // 任务类型变化时触发
    dutieTypeChange(val, option) {
      if (!val) val = []
      if (val.includes('RISK_ASSESSMENT')) {
        this.$refs.flow.FlowData.processFormData.processFormPropertyValues.find((item) => {
          return item.name === 'riskCriteria'
        }).required = true
      } else {
        this.$refs.flow.FlowData.processFormData.processFormPropertyValues.find((item) => {
          return item.name === 'riskCriteria'
        }).required = false
        // 不为必填时，清空风险准则及ID
        this.riskCriteriaObj = null
        this.$refs.flow.setFieldValue('riskCriteria', null)
        this.$refs.flow.setFieldValue('riskCriteriaId', null)
      }
    },
    // 初始化表单字典
    initFormDict(depId) {
      riskTasksService.getRiskCriteria(depId).then((res) => {
        if (!res.data) return
        this.riskCriteriaDict = res.data.map((item) => {
          return {
            label: item.criteriaCode,
            value: item.id + '',
          }
        })
      })
    },
    // 子表变化时
    childchange() {
      return new Promise((resolve, reject) => {
        var List = this.$refs.flow.getFieldValue('riskDutieUnitList')
        if (List !== undefined) {
          List.forEach((l) => {
            if (l.unitDeptMemberObj !== undefined && l.unitDeptMemberObj.length > 0) {
              l.unitDeptMemberObj[0].type = 'Group'
              l.unitId = l.unitDeptMemberObj[0].code
              l.unitName = l.unitDeptMemberObj[0].name
            }
            l.unitDeptMember = JSON.stringify(l.unitDeptMemberObj)
            l.contactsUserMember = JSON.stringify(l.contactsUserMemberObj)
            if (l.contactsUserMemberObj !== undefined && l.contactsUserMemberObj.length > 0) {
              l.contactsAccount = l.contactsUserMemberObj[0].code
              l.contactsName = l.contactsUserMemberObj[0].name
            }
          })
          this.$refs.flow.setFieldValue('riskDutieUnitList', List)
        }
        var opt = this.$refs.flow.getFieldValue('evaluationUnitOpt')
        if (opt !== undefined && opt.length > 0) {
          opt[0].type = 'Group'
          if (opt[0].props?.ORG_ID) {
            opt[0].code = opt[0].props.ORG_ID
          }
          this.$refs.flow.setFieldValue('evaluationUnitOpt', opt)
        }
        resolve(true)
        return true
      })
    },
    openchild() {
      var List = this.$refs.flow.getFieldValue('riskDutieUnitList')
      if (List !== undefined) {
        List.forEach((l) => {
          l.unitDeptMemberObj = JSON.parse(l.unitDeptMember)
          l.contactsUserMemberObj = JSON.parse(l.contactsUserMember)
        })
      }
      this.$refs.flow.setFieldValue('riskDutieUnitList', List)
    },
    depChange(val) {
      let List = this.$refs.flow.getFieldValue('riskDutieUnitList')
      const nList = []
      val.forEach((l, index) => {
        let flag = true
        if (List !== undefined) {
          if (List.findIndex((i) => i.unitId === l.props.ORG_ID.toString()) > -1) {
            flag = false
          }
        }
        if (flag) {
          l.type = 'Group'
          if (l.props.ORG_ID) {
            l.code = l.props.ORG_ID.toString()
          }
          nList.push({
            id: null,
            unitName: l.name,
            unitId: l.code,
            unitDeptMember: JSON.stringify([l]),
            unitDeptMemberObj: [l],
            contactsUserMemberObj: [],
          })
        }
        if (index === val.length - 1) {
          if (List === undefined) {
            List = []
          }
          List = List.concat(nList)
          this.$refs.flow.setFieldValue('riskDutieUnitList', List)
        }
      })
      // })
    },
    depSelect() {
      this.$refs.depSelect.openPicker()
    },
    // 保存操作，记录标识位
    saveproject(formdata) {
      this.isSave = true
    },
    initData(model) {
      if (this.isSave) {
        if (this.$refs.flow) {
          const userInfo = getUserInfo()
          // 获取可用风险准则
          // 如果是分派任务，则直接取发起机构ID
          // 如果是起草，则取当前登录人ID
          let depId = this.$refs.flow?.getFieldValue('inspectUnitId')
          if (!depId) {
            depId = userInfo.deptId
          }
          this.initFormDict(parseFloat(depId))
          // 获取风险准则结束
          this.riskCriteriaObj = this.$refs.flow?.getFieldValue('riskCriteriaId')
          // 判断增加准则的必填
          this.dutieTypeChange(this.$refs.flow?.getFieldValue('dutieType'))
          this.openchild()
          this.isTaskWork = !!this.$refs.flow?.getFieldValue('isTaskWork')
          // 创建人和创建时间赋值 creationTime creatorName
          if (!this.$refs.flow?.getFieldValue('creatorName')) {
            this.$refs.flow?.setFieldValue('creatorName', userInfo.name)
            this.$refs.flow?.setFieldValue('creatorId', userInfo.id)
            this.$refs.flow?.setFieldValue('creatorOpt', [
              {
                code: userInfo.account,
                name: userInfo.name,
                type: 'User',
              },
            ])
            this.$refs.flow?.setFieldValue('creatorAccount', userInfo.account)
            this.$refs.flow?.setFieldValue('creationTime', moment(new Date()))
          }
          // 分派任务不重新赋值年份和组织结构
          if (!this.isTaskWork) {
            // 主任务的创建人和创建时间不可编辑，不显示必填星号
            this.$refs.flow.flowData.processFormData.processFormPropertyValues.find((item) => {
              return item.name === 'creatorName'
            }).required = false
            this.$refs.flow.flowData.processFormData.processFormPropertyValues.find((item) => {
              return item.name === 'creationTime'
            }).required = false
            // 获取当前人所属机构公司
            riskIdentificationService.getCompany().then((res) => {
              if (res.data) {
                this.$refs.flow?.setFieldValue('inspectUnitId', res.data.id)
                this.$refs.flow?.setFieldValue('inspectUnitName', res.data.name)
                // 检查是否能获取风险机构
                this.checkOrg(res.data.id)
                this.initFormDict(parseFloat(res.data.id))
              }
            })
            const unit = [
              {
                code: userInfo.deptId.toString(),
                id: userInfo.deptId,
                name: userInfo.deptName.indexOf('/')
                  ? userInfo.deptName.split('/').pop()
                  : userInfo.deptName,
                props: { code: userInfo.deptId.toString() },
                type: 'GROUP',
              },
            ]
            this.$refs.flow?.setFieldValue('inspectUnitOpt', unit)
            const nowYear = new Date().getFullYear()
            this.$refs.flow?.setFieldValue('year', nowYear + '')
          }

          this.isSave = false
        }
      }
      return false
    },
    // 检查风险机构
    checkOrg(deptId) {
      riskIdentificationService
        .findIamOrgId(deptId)
        .then((res) => {
          // 获取风控库版本
          this.errorText = null
          if (res.data) {
            return riskService.getversion(parseFloat(res.data))
          }
        })
        .then((res) => {
          if (!res.data.id) {
            message.info('当前所属机构未设置风险库版本，请联系管理员', 3)
            this.errorText = '当前所属机构未设置风险库版本，请联系管理员'
          } else {
            this.errorText = null
          }
        })
        .catch(() => {
          message.info('未获取到当前组织所属风险机构，请联系管理员', 3)
          this.errorText = '未获取到当前组织所属风险机构，请联系管理员'
        })
    },
    // 日期下拉框初始化
    initDateSelect() {
      const nowYear = new Date().getFullYear()
      this.yearArry.push(nowYear)
      for (let i = 1; i < 6; i++) {
        this.yearArry.push(nowYear - i)
      }
      for (let i = 1; i < 11; i++) {
        this.yearArry.push(nowYear + i)
      }
      this.yearArry.sort()
      if (this.$refs.flow.getFieldValue('planYear') === undefined) {
        this.$refs.flow.setFieldValue('planYear', nowYear + '')
      }
    },

    validForm() {
      if (this.errorText) {
        return Promise.resolve(false)
      }
      // 防止创建人员变化，重新赋值 start
      const cUser = this.$refs.flow?.getFieldValue('creatorOpt')
      this.$refs.flow?.setFieldValue('creatorName', cUser[0].name)
      this.$refs.flow?.setFieldValue('creatorAccount', cUser[0].code)
      // 防止创建人员变化，重新赋值 end
      const child = this.$refs.flow.getFieldValue('riskDutieUnitList')
      if (child !== undefined && child.length !== 0) {
        let flag = true
        child.forEach((c) => {
          if (
            c.contactsUserMember === '' ||
            c.contactsUserMember === '[]' ||
            c.contactsUserMember === null ||
            c.contactsUserMember === undefined
          ) {
            flag = false
          }
          if (
            c.unitDeptMember === '' ||
            c.unitDeptMember === '[]' ||
            c.unitDeptMember === null ||
            c.unitDeptMember === undefined
          ) {
            flag = false
          }
        })
        if (flag) {
          return Promise.resolve(true)
        } else {
          Modal.warning({
            title: '提示',
            content: '请完善分派单位中的单位和人员信息!',
          })
          this.flag = false
          return Promise.resolve(false)
        }
      } else {
        return Promise.resolve(true)
      }
    },
    actionBtnClick(evt, btn) {
      this.childchange()
      if (btn.button.buttonId.indexOf('save') > -1) {
        evt.waitUntil(
          new Promise((resolve, reject) => {
            if (this.$refs.flow.getFieldValue('year') === undefined) {
              this.$refs.flow.validateField('year')
              evt.preventDefault()
              resolve()
            } else {
              resolve()
            }
          })
        )
      }
    },
  },
}
</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;
  }
}
</style>
