<template>
  <div>
    <sd-webflow ref="flow" :removed-tabs="['sdRelatedDoc']" :class="$style.schemeform">
      <template v-slot:form="{ model, fields, FlowData }">
        <table>
          <tr>
            <!-- 文件标题 -->
            <sd-form-item-td name="fileTitle" :colspan="3" />
            <!-- id -->
            <sd-form-item-td name="id" :hidden="true" />
            <!-- 文件编号 -->
            <sd-form-item-td name="fileCode" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <a-input
                  v-if="editable"
                  v-model="model.fileCode"
                  placeholder="自动生成"
                  read-only
                ></a-input>
                <span v-else>{{ model.fileCode }}</span>
              </template>
            </sd-form-item-td>
          </tr>

          <tr>
            <!-- 被审计单位 -->
            <sd-form-item-td
              name="auditedUnit"
              :colspan="3"
              :input-props="{ defaultValue: units }"
            />
            <!-- 被审计单位IDS -->
            <sd-form-item-td name="auditedUnitIds" :hidden="true" />
            <!-- 文号 -->
            <sd-form-item-td name="docNum" :colspan="3" />
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="fileExplain" :colspan="7">
              <template v-slot>
                <a-textarea
                  v-model="model.fileExplain"
                  :auto-size="{ minRows: 3, maxRows: 3 }"
                ></a-textarea>
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 审计方案 -->
            <sd-form-item-td name="schemeId" :colspan="7">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment-ex
                  :key="schemeAttachmentKey"
                  ref="schemeAttachment"
                  v-model="model.schemeId"
                  :group-id="JSON.parse(fields.schemeId.value).value"
                  :read-only="!editable"
                  :uploadable="false"
                  :clean-copy="FlowData.attrs && FlowData.attrs['we-doc$cleanCopy']"
                  :temtype="temtype"
                  :temdataurl="temdataurl"
                  :is-open-file="false"
                  :custom-select-template-fun="selectTemplate"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 附件 -->
            <sd-form-item-td name="attachment" :colspan="7">
              <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="creatorName" :colspan="3" />
            <!-- 项目id -->
            <sd-form-item-td name="projectId" :hidden="true" />
            <!-- 编制日期 -->
            <sd-form-item-td v-if="initparams(model)" name="creationTime" :colspan="3" />
          </tr>
        </table>
      </template>
    </sd-webflow>
    <a-modal
      :visible="visible"
      destroy-on-close
      width="800px"
      title="选择模板"
      @cancel="hiddenModal"
      @ok="autoTaoDaFile"
    >
      <iam-audit-scheme-template-select
        ref="templateSelect"
        :project-id="projectId + ''"
        :template-list="templateList"
      ></iam-audit-scheme-template-select>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import { Message } from 'ant-design-vue'
import AuditService from './iam-audit-scheme-service'
import iamAuditSchemeTemplateSelect from './iam-audit-scheme-template-select.vue'
import components from './_import-components/iam-audit-scheme-form-import'
import sdAttachmentEx from '@/common/components/sd-attachment-ex.vue'
import axios from '@/common/services/axios-instance'
import loginService from '@/login/login-service'

export default {
  name: 'IamAuditSchemeForm',
  metaInfo: {
    title: 'IamAuditSchemeForm',
  },
  components: {
    iamAuditSchemeTemplateSelect,
    ...components,
  },
  data() {
    return {
      temtype: '02',
      projectId: '',
      temdataurl: '',
      units: [],
      flag: true,
      visible: false,
      schemeAttachmentKey: 0,
      templateList: [],
      projectInfo: null, // 项目信息
    }
  },
  mounted() {
    if (this.$refs.flow.flowData.processFormData.beanId != null) {
      this.projectId = this.$refs.flow.getFieldValue('projectId')
    } else {
      this.projectId = JSON.parse(this.$route.query.extParams).projectId
      this.$refs.flow.setFieldValue('projectId', this.projectId)
    }
    this.temdataurl =
      `api/xcoa-mobile/v1/iamtemplate/findTemplate?projectId=` +
      this.projectId +
      `&templateType=` +
      this.temtype
    // 获取模板列表
    axios.get(this.temdataurl).then((res) => {
      this.templateList = res.data
    })
  },
  methods: {
    initparams(model) {
      if (this.flag) {
        if (this.projectId === '') {
          this.projectId = model.projectId
        }
        this.fngetunit(model)
        this.flag = false
      }
      return true
    },
    fngetunit(model) {
      axios({
        url: 'api/xcoa-mobile/v1/page/wp/audit/project/iamAuditProject?id=' + this.projectId,
        method: 'get',
      }).then((res) => {
        this.projectInfo = res.data.pageFormData.pageFieldInfos
        // 如果已经获取过，则不重新获取直接退出
        if (model.id !== undefined && model.id !== null) return
        const obj = res.data.pageFormData.pageFieldInfos.find(
          (item) => item.name === 'auditedUnitIds'
        )
        if (obj !== null) {
          if (obj.value !== undefined) {
            const units = JSON.parse(obj.value)
            const newunits = []
            if (units.length === 1) {
              units.forEach((item) => {
                item.id = item.code
              })
              this.units = units
              setTimeout(() => {
                this.$refs.flow.setFieldValue('auditedUnit', this.units)
              }, 1000)
            }
          }
        }
        const projectTitle = res.data.pageFormData.pageFieldInfos.find(
          (item) => item.name === 'projectTitle'
        )
        const fileTitle = this.$refs.flow.getFieldValue('fileTitle')
        if (fileTitle === undefined) {
          setTimeout(() => {
            this.$refs.flow.setFieldValue('fileTitle', projectTitle.value + '审计方案')
          }, 1000)
        }
      })
    },
    // actionBtnClick(evt, { button, FlowData }) {
    //   if (button.fakeId === 'save' || button.fakeId === 'workflow-push') {
    //     // 保存前先生成文件编号
    //     evt.waitUntil(
    //       new Promise((resolve, reject) => {
    //         this.handleBeforeAdd(null, (res) => {
    //           if (res) {
    //             evt.preventDefault()
    //           }
    //           resolve()
    //         })
    //       })
    //     )
    //   }
    // },

    handleBeforeAdd(val, callback) {
      const fileCode = this.$refs.flow.getFieldValue('fileCode')
      if (fileCode && fileCode !== '') {
        callback(false)
      } else {
        // 生成文件编号
        const params = {
          projectId: this.projectId,
          valueCode: 'fileCode',
          serviceName: 'iamAuditSchemeService',
          infix: 'FA',
        }

        AuditService.getFileCode(params).then((res) => {
          this.$refs.flow.setFieldValue('fileCode', res.data)
          callback(false)
        })
      }
    },

    // 展示选择模板窗口
    selectTemplate() {
      this.visible = true
    },
    // 隐藏选择模板窗口
    hiddenModal() {
      this.$refs.schemeAttachment.copyLoading = false
      this.visible = false
    },

    // 自动套打文档内容
    autoTaoDaFile() {
      let tmpName = null
      const selectTmp = this.$refs.templateSelect.checkedTemp
      if (!selectTmp.id) {
        Message.info('请选择模板', 1)
      } else {
        // 设置加载中状态
        this.$refs.templateSelect.spinning = true
        axios
          .get(`api/xcoa-mobile/v1/attachment-extend/attachments-info-perm/${selectTmp.attachment}`)
          .then((res) => {
            tmpName = res.data[0].name
            axios
              .post(
                `api/xcoa-mobile/v1/attachment-extend/attachment-copy/${res.data[0].code}/${this.$refs.schemeAttachment.groupId}?catNum=-1&fromTemplate=1`
              )
              .then((res) => {
                // 执行套打
                this.taodafile(tmpName)
              })
          })
      }
    },
    taodafile(fileName) {
      const indiDocX = this.$refs.schemeAttachment
      // 计算套打内容
      const auditedUnit = this.$refs.flow.getFieldValue('auditedUnit')
      let auditedText = ''
      auditedUnit.forEach((item) => {
        auditedText += item.name
      })
      // 项目名称
      const projectTitle = this.projectInfo.find((item) => {
        return item.name === 'projectTitle'
      })
      // 找到组长及组员
      const userListJson = this.projectInfo.find((item) => {
        return item.name === 'iamProjectUserList'
      })
      const zzuser = []
      const zyuser = []
      const userList = JSON.parse(userListJson.value)
      userList.forEach((item) => {
        // 组长
        if (item.userType === '05') {
          zzuser.push(item.userName)
        }
        if (item.userType === '03') {
          zyuser.push(item.userName)
        }
      })
      // 审计期间
      const startTime = this.projectInfo.find((item) => {
        return item.name === 'auditperiodStart'
      })
      const endTime = this.projectInfo.find((item) => {
        return item.name === 'auditperiodEnd'
      })
      // 更新完附件列表之后，才自动套打
      indiDocX.getFileList().then((res) => {
        var userFile = indiDocX.slCtl.Content.Control.getFileByName(fileName)
        loginService.updateRefreshToken().then(() => {
          indiDocX.markBusy(fileName)
          indiDocX.updateActivedAtt?.(userFile.code, true)
          indiDocX.slCtl.Content.Control.UpdateRegion(
            fileName,
            {
              项目名称: projectTitle.value,
              被审计单位: auditedText,
              审计期间:
                moment(startTime.value).format('YYYY年MM月DD日') +
                '至' +
                moment(endTime.value).format('YYYY年MM月DD日'),
              审计组长: zzuser.join(','),
              审计组员: zyuser.join(','),
              当前日期: moment().format('YYYY年MM月DD日'),
            },
            '',
            {
              IsMaximization: 'false',
              Status: '-1',
              WaterMark: indiDocX.waterMark(userFile, 'UpdateRegion'),
            },
            indiDocX.pluginInfo()
          )
            ?.finally(() => {
              indiDocX.updateActivedAtt?.(userFile.code, false)
              indiDocX.getFileList()
              indiDocX.markBusy(fileName, false)
              this.hiddenModal()
            })

            .catch(() => {
              indiDocX.markBusy(userFile, false)
            })
        })
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.schemeform {
  :global(.divider_sd-attachment-ex_common) {
    border-top: none;
  }
}
</style>
