<template>
  <div>
    <sd-webflow
      ref="flow"
      :removed-tabs="['sdRelatedDoc']"
      :validate-form="validForm"
      @saveproject="saveproject"
    >
      <template v-slot:form="{ model, fields, FlowData }">
        <table>
          <tr v-if="model.flowState === '结束'">
            <sd-form-item-td name="fileTitle" />
            <sd-form-item-td name="fileCode" />
          </tr>
          <tr v-else>
            <!-- 文件标题 -->
            <!-- <td v-if="savecontent()" class="ant-form-item-label">
            <label class="ant-form-item-required">文件标题</label>
          </td>
          <td>
            <span> {{ model.fileTitle }}</span>
          </td> -->
            <sd-form-item-td v-if="savecontent()" name="fileTitle" />
            <!-- 文件编号 -->
            <sd-form-item-td name="fileCode">
              <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="auditedUnitMember"> </sd-form-item-td>

            <!-- 文书编号 -->
            <sd-form-item-td name="docNum" />
            <sd-form-item-td name="projectId" :hidden="true" />
          </tr>
          <tr>
            <!-- 说明 -->
            <sd-form-item-td name="noticeExplain" :colspan="3">
              <a-textarea v-model="model.noticeExplain" :rows="3" />
            </sd-form-item-td>
          </tr>
          <tr>
            <!-- 审计通知书 -->
            <sd-form-item-td name="noticeId" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment-ex
                  :key="noticeAttachmentKey"
                  ref="noticeAttachment"
                  v-model="model.noticeId"
                  :group-id="JSON.parse(fields.noticeId.value).value"
                  :read-only="!editable"
                  :uploadable="false"
                  :temtype="temtype"
                  :temdataurl="temdataurl"
                  :is-open-file="false"
                  :clean-copy="FlowData.attrs && FlowData.attrs['we-doc$cleanCopy']"
                  :custom-select-template-fun="selectTemplate"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <!-- <tr v-if="false">
            <sd-form-item-td name="isEmail" />
            <sd-form-item-td v-if="model.isEmail !== '1'" name="emailAddr" />
            <td v-if="model.isEmail === '1'" class="ant-form-item-label">
              <label class="ant-form-item-required">邮件通知地址</label>
            </td>
            <td v-if="model.isEmail === '1'">
              <a-form-model-item
                :rules="[
                  {
                    required: true,
                    trigger: ['change', 'blur'],
                  },
                ]"
                prop="emailAddr"
                name="emailAddr"
              >
                <a-input v-model.trim="model.emailAddr" />
              </a-form-model-item>
            </td>
          </tr> -->
          <tr v-if="false">
            <!-- 邮件通知 -->
            <sd-form-item-td name="isEmail" />
            <!-- 邮件通知地址 -->
            <sd-form-item-td name="emailAddr" />
          </tr>

          <tr>
            <!-- 附件 -->
            <sd-form-item-td v-if="initparams(model)" name="attachment" :colspan="3" />
          </tr>
          <tr>
            <!-- 编制人员 -->
            <sd-form-item-td name="creatorName" />
            <!-- 编制日期 -->
            <sd-form-item-td name="creationTime" />
          </tr>
        </table>
      </template>
    </sd-webflow>
    <a-modal
      :visible="visible"
      destroy-on-close
      width="800px"
      title="选择模板"
      @cancel="hiddenModal"
      @ok="autoTaoDaFile"
    >
      <iam-audit-notice-template-select
        ref="templateSelect"
        :project-id="projectId + ''"
        :template-list="templateList"
      ></iam-audit-notice-template-select>
    </a-modal>
  </div>
</template>

<script>
import loginService from '@/login/login-service'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import moment from 'moment'
import { Message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import iamAuditNoticeTemplateSelect from './iam-audit-notice-template-select.vue'
import components from './_import-components/audit-notice-form-import'

export default {
  name: 'AuditNoticeForm',
  metaInfo: {
    title: '审计通知书',
  },
  components: {
    iamAuditNoticeTemplateSelect,
    ...components,
  },
  data() {
    return {
      temtype: '03',
      // projectId: this.$route.query.projectId ? this.$route.query.projectId : null,
      projectId: '',
      temdataurl: '',
      auditedUnitMember: [],
      fileTitle: '',
      flag: true,
      visible: false,
      noticeAttachmentKey: 0,
      templateList: [],
      projectInfo: null, // 项目信息
      // mode: null,
      // recodeId: this.$route.query.record ? parseInt(this.$route.query.record) : null,
    }
  },
  created() {
    // 获取模板列表
    // if (this.$route.query.projectId) {
    //   this.projectId = this.$route.query.projectId
    // 获取模板列表
    if (this.$route.query.extParams) {
      this.projectId = JSON.parse(this.$route.query.extParams).projectId
      const ini = setInterval(() => {
        if (this.$refs.flow) {
          this.$refs.flow.setFieldValue('projectId', this.projectId)
          clearInterval(ini)
        }
      })
    } else {
      return
    }

    this.temdataurl =
      `api/xcoa-mobile/v1/iamtemplate/findTemplate?projectId=` +
      this.projectId +
      `&templateType=` +
      this.temtype
    // 获取模板列表
    axios.get(this.temdataurl).then((res) => {
      this.templateList = res.data
    })
    // 获取项目信息
    axios({
      url: 'api/xcoa-mobile/v1/page/wp/audit/project/iamAuditProject?id=' + this.projectId,
      method: 'get',
    }).then((res) => {
      this.projectInfo = res.data.pageFormData.pageFieldInfos
    })
  },
  methods: {
    // 页面加载完成后
    // sdFormReady() {
    //   this.mode = this.$refs.flow.formData.pageFormData.pageFieldInfos.find(
    //     (item) => item.name === 'noticeExplain'
    //   ).readonly
    //     ? 'VIEW'
    //     : 'EDIT'
    // },
    // // 保存
    // saveForm() {
    //   this.$refs.flow.saveBtnClick()
    // },
    // saved() {
    //   Message.success('保存成功', 1).then((res) => {
    //     this.close(true)
    //   })
    // },
    // close(flag) {
    //   crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
    //   window.close()
    // },
    getTemplate() {
      // 获取模板列表
      // if (this.$route.query.projectId) {
      //   this.projectId = this.$route.query.projectId
      if (this.$route.query.extParams) {
        this.projectId = JSON.parse(this.$route.query.extParams).projectId
        this.$refs.flow.setFieldValue('projectId', this.projectId)
      } else {
        this.projectId = this.$refs.flow.getFieldValue('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
      })
      // 获取项目信息
      axios({
        url: 'api/xcoa-mobile/v1/page/wp/audit/project/iamAuditProject?id=' + this.projectId,
        method: 'get',
      }).then((res) => {
        this.projectInfo = res.data.pageFormData.pageFieldInfos
      })
      return true
    },
    savecontent() {
      if (this.fileTitle !== '') {
        this.$refs.flow.setFieldValue('fileTitle', this.fileTitle)
      }
      return true
    },
    validForm() {
      // 自定义校验，适用于多个字段联合校验，支持promise
      this.$refs.flow.setFieldValue('fileTitle', this.fileTitle)
      return Promise.resolve(true)
    },
    initparams(model) {
      if (this.flag) {
        this.setAuditUnit(model)
        this.setFileTitle(model)
        this.flag = false
      }

      return true
    },
    // 获取被审计单位
    setAuditUnit(model) {
      const params = {
        projectId: this.projectId,
      }

      const auditedUnitMember = model.auditedUnitMember
      if (
        auditedUnitMember === null ||
        auditedUnitMember === '' ||
        auditedUnitMember === undefined
      ) {
        if (this.projectId) {
          axios({
            url: 'api/xcoa-mobile/v1/iamauditnotice/findAuditUnit',
            method: 'post',
            params,
          }).then((res) => {
            model.auditedUnitMember = res.data
          })
        }
      }
    },
    // 获取文件标题 “项目名称”+“审计通知书”
    setFileTitle(model) {
      const params = {
        projectId: this.projectId,
      }
      const fileTitle = model.fileTitle
      if (fileTitle === null || fileTitle === '' || fileTitle === undefined) {
        if (this.projectId) {
          axios({
            url: 'api/xcoa-mobile/v1/iamauditnotice/findFileTitle',
            method: 'post',
            params,
          }).then((res) => {
            this.fileTitle = res.data
          })
        }
      } else {
        this.fileTitle = model.fileTitle
      }
    },
    saveproject(formdata) {
      const selectedKeys = formdata.processFormData.processFormPropertyValues
      selectedKeys.forEach((item) => {
        if (item.name === 'fileCode') {
          this.$refs.flow.setFieldValue('fileCode', item.value)
        }
      })
    },
    // 展示选择模板窗口
    selectTemplate() {
      // 获取模板列表
      // if (this.$route.query.projectId) {
      //   this.projectId = this.$route.query.projectId
      if (this.$route.query.extParams) {
        this.projectId = JSON.parse(this.$route.query.extParams).projectId
      } else {
        this.projectId = this.$refs.flow.getFieldValue('projectId')
      }
      // 获取项目信息
      axios({
        url: 'api/xcoa-mobile/v1/page/wp/audit/project/iamAuditProject?id=' + this.projectId,
        method: 'get',
      }).then((res) => {
        this.projectInfo = res.data.pageFormData.pageFieldInfos
      })

      // 获取模板列表
      this.temdataurl =
        `api/xcoa-mobile/v1/iamtemplate/findTemplate?projectId=` +
        this.projectId +
        `&templateType=` +
        this.temtype

      axios.get(this.temdataurl).then((res) => {
        this.templateList = res.data
        this.visible = true
      })
    },
    // 隐藏选择模板窗口
    hiddenModal() {
      this.$refs.noticeAttachment.copyLoading = false
      this.visible = false
    },

    // 自动套打文档内容
    autoTaoDaFile() {
      debugger
      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.noticeAttachment.groupId}?catNum=-1&fromTemplate=1`
              )
              .then((res) => {
                // 执行套打
                this.taodafile(tmpName)
              })
          })
      }
    },
    taodafile(fileName) {
      debugger
      const indiDocX = this.$refs.noticeAttachment
      // 计算套打内容
      const auditedUnit = this.$refs.flow.getFieldValue('auditedUnitMember')
      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 fzzuser = []
      const zyuser = ['']
      const userList = JSON.parse(userListJson.value)
      userList.forEach((item) => {
        // 组长
        if (item.userType === '05') {
          zzuser.push(item.userName)
        }
        // 副组长
        if (item.userType === '01') {
          fzzuser.push(item.userName)
        }
        // 主审
        if (item.userType === '02') {
          zyuser.splice(0, 1, item.userName)
        }
        // 成员
        if (item.userType === '03') {
          zyuser.push(item.userName)
        }
      })
      // 审计机关
      const auditUnit = this.projectInfo.find((item) => {
        return item.name === 'unitName'
      })
      // 被审计人员
      const auditedUser = this.projectInfo.find((item) => {
        return item.name === 'auditedUser'
      })
      // 计划年度
      const planYear = this.projectInfo.find((item) => {
        return item.name === 'planYear'
      })
      // 审计期间开始
      const auditperiodStart = this.projectInfo.find((item) => {
        return item.name === 'auditperiodStart'
      })
      //  审计期间结束
      const auditperiodEnd = this.projectInfo.find((item) => {
        return item.name === 'auditperiodEnd'
      })
      console.log('---更新完')
      // 更新完附件列表之后，才自动套打
      indiDocX.getFileList().then((res) => {
        var userFile = indiDocX.slCtl.Content.Control.getFileByName(fileName)
        // userFile.code = userFile.Unid
        loginService.updateRefreshToken().then(() => {
          indiDocX.markBusy(fileName)
          indiDocX.updateActivedAtt?.(userFile.code, true)
          indiDocX.slCtl.Content.Control.UpdateRegion(
            fileName,
            {
              审计期间开始: moment(auditperiodStart.value).format('YYYY年MM月DD日'),
              审计期间开始1: moment(auditperiodStart.value).format('YYYY年MM月DD日'),
              审计期间结束: moment(auditperiodEnd.value).format('YYYY年MM月DD日'),
              被审计单位: auditedText,
              被审计单位1: auditedText,
              计划年度: planYear.value,
              被审计人员: auditedUser.value,
              被审计人员1: auditedUser.value,
              被审计人员2: auditedUser.value,
              审计组长: zzuser.join(','),
              审计副组长: fzzuser.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)
              this.hiddenModal()
              setTimeout(() => {
                indiDocX.getFileList()
              }, 0)
              indiDocX.markBusy(fileName, false)
            })

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

<style module lang="scss">
@use '@/common/design' as *;
// @import '@/webflow/sd-flow-form.scss';
// .first-tr {
//   td {
//     background: #fff !important;
//     border: none !important;
//   }
// }
// .lawapply {
//   :global(.buttons_sd-attachment-ex_common > .ant-btn-primary) {
//     display: none;
//   }
// }
</style>
