<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :validate-form="validForm"
      class="evaluationPlanForm"
      @actionBtnClick="actionBtnClick"
      @saveproject="saveproject"
      @afterDispatch="afterDispatch"
    >
      <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">
              <a-select v-if="sourceId === -1 ? true : false" v-model="model.year">
                <a-select-option v-for="year in yearArry" :key="year + ''">
                  {{ year }}
                </a-select-option>
              </a-select>
              <span v-else>{{ model.year }}</span>
            </sd-form-item-td>
            <!-- 检查单位 -->
            <sd-form-item-td v-if="sourceId === -1 ? true : false" name="inspectUnitOpt" />
            <sd-form-item-td v-else name="inspectUnitOpt">
              <span>{{ model.inspectUnitName }}</span>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 评价名称 -->
            <sd-form-item-td name="evaluationName" />
            <sd-form-item-td name="evaluationCode">
              <a-input
                v-model="model.evaluationCode"
                :disabled="true"
                placeholder="系统自动生成"
              ></a-input>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 被评价单位 -->
            <sd-form-item-td name="evaluationUnitOpt">
              <!-- <audit-group-picker v-model="model.evaluationUnitOpt" /> -->
              <audit-group-picker
                v-model="model.evaluationUnitOpt"
                :root-node="{ code: 0, name: '内控机构', id: 0 }"
                :selectall="false"
                :top-node-text="'内控机构'"
                :treeparams="{
                  moduleId: 'icMtxVersion',
                }"
                :single="true"
              />
            </sd-form-item-td>
            <!-- 评价方式 -->
            <sd-form-item-td name="evaluationMode" />
          </tr>
          <tr>
            <!-- 评价类型 -->
            <sd-form-item-td
              name="evaluationType"
              component="a-checkbox-group"
              :input-props="{ disabled: sourceId !== -1 }"
            />
          </tr>
          <tr class="evaluationPlanFormtr">
            <!-- 评价区间 -->
            <sd-form-item-td
              label="评价区间"
              :name="['evaluationStartTime', 'evaluationEndTime']"
              :input-props="{ disabled: sourceId !== -1 }"
            />
            <!-- 评价周期 -->
            <sd-form-item-td
              label="评价实施周期"
              :name="['evaluationImplementationStart', 'evaluationImplementationEnd']"
            />
          </tr>
          <tr>
            <!-- 内容描述 -->
            <sd-form-item-td name="evaluationDesc" :colspan="3">
              <a-textarea v-model="model.evaluationDesc" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="3" />
          </tr>
          <tr>
            <!-- 创建人 -->
            <sd-form-item-td name="creatorName" />
            <!-- 创建日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
        </table>

        <table>
          <tr
            ><td :colspan="4">
              <sd-form-item name="icEvaluationPlanUnitList" :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.icEvaluationPlanUnitList"
                        :class="$style.deptPlanChild"
                        :label="null"
                        :read-only="!editable"
                        :addbuttonvisiable="false"
                        :fields="
                          [
                            {
                              caption: '序号',
                              name: 'sortNum',
                              dataType: 'number',
                            },
                          ].concat(Array.from(fields.icEvaluationPlanUnitList.attr.dync))
                        "
                        :columns="columns"
                        :flagpage="true"
                      >
                        <template v-slot:contactsOpt="{ field, text, index, value }">
                          <sd-user-picker
                            v-model="value[index].contactsOpt1"
                            :single="true"
                            :read-only="!editable"
                          />
                        </template>
                        <template v-slot:unitOpt="{ field, text, index, value }">
                          <audit-group-picker
                            v-model="value[index].unitOpt1"
                            :root-node="{ code: 0, name: '内控机构', id: 0 }"
                            :selectall="false"
                            :top-node-text="'内控机构'"
                            :treeparams="{
                              moduleId: 'icEvaluationPlan',
                            }"
                            :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: 'icMtxVersion',
            }"
            @change="depChange"
          />
        </div>
      </template>
    </sd-webflow>
  </div>
</template>

<script>
import { Modal } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import { getUserInfo } from '@/common/store-mixin'
import auditGroupPicker from '@product/iam/components/picker/audit-group-picker.vue'
import auditAdvancedGroup from '../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../components/audit-advanced-group-mixins'
import components from './_import-components/ic-evaluation-plan-form-import'
// 修改主子表的首行title名
export default {
  name: 'IcEvaluationPlanForm',
  metaInfo: {
    title: '审计计划信息',
  },
  components: {
    ...components,
    auditAdvancedGroup,
    auditGroupPicker,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      rootNode: {},
      childTableKey: 0, // 刷新子表组件
      inited: true,
      planExpand: true,
      FpdwExpand: true,
      expand: true,
      planId: null,
      columns: [
        {
          title: '序号',
          dataIndex: 'sortNum',
          width: '50px',
          customRender: (text, record, index) => `${index + 1}`,
        },
        {
          dataIndex: 'unitName',
          title: '单位名称',
          width: '120px',
          sdHidden: true,
        },
        { dataIndex: 'unitOpt' },
        {
          title: '联系人',
          dataIndex: 'contactsName',
          sdHidden: true,
        },
        { dataIndex: 'contactsOpt', title: '联系人' },
      ],
      yearArry: [],
      expressions: [],
      externalUnitIds: [],
      isSave: true, // 是否有保存操作
      icEvaluationPlanUnitList: [],
      sourceId: -1,
      unitOpt: [],
    }
  },
  computed: {
    // 计算随机key
    randomId() {
      let randomNum = Math.random()
      while (randomNum === 0) {
        randomNum = Math.random()
      }
      const time = new Date().getTime()
      return time + Math.ceil(randomNum * 1000000000)
    },
  },
  mounted() {
    // 日期下拉框初始化
    this.initDateSelect()
    let userInfo = getUserInfo()
    const params = {
      orgId: userInfo.deptId,
      moduleId: 'icMtxVersion',
    }
    axios({
      url: 'api/xcoa-mobile/v1/iamorg/getCurrentUserGroup',
      method: 'get',
    }).then((res) => {
      userInfo = res.data
      params.orgId = res.data.id
      axios({
        url: 'api/xcoa-mobile/v1/iamorg/findIamOrgId',
        method: 'post',
        params,
      }).then((res) => {
        // this.id = res.data
        const deptCode = userInfo.id.toString()
        const deptName = userInfo.name
        this.rootNode = { code: deptCode, name: deptName, id: res.data }
      })
    })
  },
  methods: {
    childchange() {
      return new Promise((resolve, reject) => {
        var List = this.$refs.flow.getFieldValue('icEvaluationPlanUnitList')
        if (List !== undefined) {
          List.forEach((l) => {
            if (l.unitOpt1 !== undefined && l.unitOpt1.length > 0) {
              l.unitOpt1[0].type = 'Group'
              l.unitId = l.unitOpt1[0].code
              l.unitName = l.unitOpt1[0].name
            }
            l.unitOpt = JSON.stringify(l.unitOpt1)
            l.contactsOpt = JSON.stringify(l.contactsOpt1)
            if (l.contactsOpt1 !== undefined && l.contactsOpt1.length > 0) {
              l.contactsAccount = l.contactsOpt1[0].code
              l.contactsName = l.contactsOpt1[0].name
            }
          })
          this.$refs.flow.setFieldValue('icEvaluationPlanUnitList', 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('icEvaluationPlanUnitList')
      if (List !== undefined) {
        List.forEach((l) => {
          l.unitOpt1 = JSON.parse(l.unitOpt)
          l.contactsOpt1 = JSON.parse(l.contactsOpt)
        })
      }
      this.$refs.flow.setFieldValue('icEvaluationPlanUnitList', List)
    },
    depChange(val) {
      let List = this.$refs.flow.getFieldValue('icEvaluationPlanUnitList')
      const nList = []
      val.forEach((l, index) => {
        let flag = true
        if (List !== undefined && List.length > 0) {
          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,
            unitOpt: JSON.stringify([l]),
            unitOpt1: [l],
            contactsOpt1: [],
          })
        }
        if (index === val.length - 1) {
          if (List === undefined) {
            List = []
          }
          List = List.concat(nList)
          this.$refs.flow.setFieldValue('icEvaluationPlanUnitList', List)
        }
      })
      // })
    },
    depSelect() {
      this.$refs.depSelect.openPicker()
    },
    // 保存操作，记录标识位
    saveproject(formdata) {
      this.isSave = true
      const selectedKeys = formdata.processFormData.processFormPropertyValues
      selectedKeys.forEach((item) => {
        if (item.name === 'evaluationCode') {
          this.$refs.flow.setFieldValue('evaluationCode', item.value)
        }
      })
    },
    /**
     * 提交后事件
     */
    afterDispatch() {
      // 提交也认为是保存
      // this.isSave = true
    },
    initData(model) {
      if (this.isSave) {
        if (this.$refs.flow) {
          if (this.$route.params?.id && this.$route.params?.id !== '0') {
            this.openchild()
            this.sourceId = this.$refs.flow?.getFieldValue('sourceId')
          } else {
            this.$refs.flow?.setFieldValue('sourceId', -1)
            const userInfo = getUserInfo()
            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 + '')
          }
          if (this.$refs.flow?.getFieldValue('evaluationUnitOpt') === undefined) {
            this.$refs.flow.setFieldValue('evaluationUnitOpt', [])
          }
          this.isSave = false
        }
      }
      return false
    },
    // 日期下拉框初始化
    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() {
      const child = this.$refs.flow.getFieldValue('icEvaluationPlanUnitList')
      if (child !== undefined && child.length !== 0) {
        let flag = true
        child.forEach((c) => {
          if (
            c.contactsOpt === '' ||
            c.contactsOpt === '[]' ||
            c.contactsOpt === null ||
            c.contactsOpt === undefined
          ) {
            flag = false
          }
          if (
            c.unitOpt === '' ||
            c.unitOpt === '[]' ||
            c.unitOpt === null ||
            c.unitOpt === 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('inspectUnitOpt') === undefined ||
              this.$refs.flow.getFieldValue('year') === undefined ||
              this.$refs.flow.getFieldValue('evaluationName') === undefined
            ) {
              this.$refs.flow.validateField('inspectUnitOpt').then((res) => {
                console.log(res)
              })
              this.$refs.flow.validateField('year').then((res) => {
                console.log(res)
              })
              this.$refs.flow.validateField('evaluationName').then((res) => {
                console.log(res)
              })
              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;
  }
}
:global(.evaluationPlanFormtr) {
  :global(.ant-input) {
    width: 150px;
  }
}
</style>
