<template>
  <audit-form-top-banner>
    <div :class="$style.wrapContent">
      <sd-detail-form
        ref="form"
        page-id="audit/project/iamAuditProject"
        form-id="iamAuditProject"
        :record-id="this.$route.query.record ? parseInt(this.$route.query.record) : null"
        :class="[$style.form, 'readonlyform']"
      >
        <template v-slot="{ model, fields }">
          <table>
            <tr>
              <sd-form-item-td name="projectTitle">
                <span>{{ model.projectTitle }}</span>
              </sd-form-item-td>
              <sd-form-item-td name="auditType">
                <span>{{ fields.auditType.attr.displayValue }}</span>
              </sd-form-item-td>
            </tr>
            <tr class="auditprojectdetailname">
              <sd-form-item-td name="projectPrincipalName" label="项目负责人">
                <span>{{ model.projectPrincipalName }}</span>
              </sd-form-item-td>
              <sd-form-item-td name="projectCode">
                <span>{{ model.projectCode }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="auditedUnitNames" :colspan="3">
                <span>{{ model.auditedUnitNames }}</span>
              </sd-form-item-td>
              <!-- <sd-form-item-td name="auditBasis">
                <span>{{ fields.auditBasis.attr.displayValue }}</span>
              </sd-form-item-td> -->
            </tr>
            <tr>
              <sd-form-item-td name="auditMode">
                <span>{{ fields.auditMode.attr.displayValue }}</span>
              </sd-form-item-td>
              <sd-form-item-td
                v-if="model.auditType === '03' || model.auditType === '04'"
                name="auditedUser"
              >
                <span>{{ model.auditedUser }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td v-if="model.auditMode === '02'" name="externalUnitIds" :colspan="3">
                <span>{{ model.externalUnitNames }}</span>
              </sd-form-item-td>
            </tr>
            <!-- <tr>
              <sd-form-item-td name="auditObjective" :colspan="3">
                <span>{{ model.auditObjective }}</span>
              </sd-form-item-td>
            </tr> -->
            <tr>
              <sd-form-item-td name="projectContent" :colspan="3">
                <span>{{ model.projectContent }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="whetherFinance" :hidden="true">
                <span>{{ fields.whetherFinance.attr.displayValue }}</span>
              </sd-form-item-td>
              <sd-form-item-td name="whetherOverseas" :hidden="true">
                <span>{{ fields.whetherOverseas.attr.displayValue }}</span>
              </sd-form-item-td>
            </tr>
            <tr class="auditprojectdetailname">
              <sd-form-item-td name="whetherAuditCoverage">
                <span>{{ fields.whetherAuditCoverage.attr.displayValue }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="planStartTime">
                <span>{{ fields.planStartTime.attr.displayValue }}</span>
              </sd-form-item-td>
              <sd-form-item-td name="planEndTime">
                <span>{{ fields.planEndTime.attr.displayValue }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="planDays" :colspan="3">
                <span>{{ model.planDays }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="groupLeaderName" label="审计组长">
                <span>{{ model.groupLeaderName }}</span>
              </sd-form-item-td>
              <sd-form-item-td name="projectUser" lable="项目组员">
                <span>{{ userMember }}</span>
              </sd-form-item-td>
            </tr>
            <!-- <tr>
              <sd-form-item-td name="exPersonnelNum">
                <span>{{ model.exPersonnelNum }}</span>
              </sd-form-item-td>
              <sd-form-item-td name="predictedCost">
                <span>{{
                  model.predictedCost === undefined
                    ? model.predictedCost
                    : parseFloat(model.predictedCost).toFixed(2)
                }}</span>
              </sd-form-item-td>
            </tr> -->
            <tr>
              <sd-form-item-td name="attachment" :colspan="3">
                <template>
                  <sd-attachment
                    v-model="model.attachment"
                    :group-id="JSON.parse(fields.attachment.value).value"
                    :read-only="true"
                  />
                </template>
              </sd-form-item-td>
            </tr>
            <tr>
              <sd-form-item-td name="projectRemarks" :colspan="3">
                <span>{{ model.projectRemarks }}</span>
              </sd-form-item-td>
            </tr>
            <tr>
              <!-- 审计通知书 -->
              <sd-form-item-td name="noticeId" :colspan="3" :label="'审计通知书'">
                <template v-slot:read-and-edit="{ editable }">
                  <!-- <sd-attachment-ex -->
                  <XmSdAttachmentex
                    :key="noticeAttachmentKey"
                    ref="noticeAttachment"
                    v-model="model.noticeId"
                    :group-id="groupId"
                    :read-only="!editable"
                    :uploadable="false"
                    :temtype="temtype"
                    :temdataurl="temdataurl"
                    :is-open-file="false"
                    :custom-select-template-fun="selectTemplate"
                  />
                </template>
              </sd-form-item-td>
            </tr>
          </table>
        </template>
      </sd-detail-form>
      <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>
  </audit-form-top-banner>
</template>

<script>
import axios from '@/common/services/axios-instance'
import { Message } from 'ant-design-vue'
import moment from 'moment'
import loginService from '@/login/login-service'
import iamAuditNoticeTemplateSelect from '../notice/iam-audit-notice-template-select.vue'
import auditFormTopBanner from '@product/iam/components/audit-form-top-banner'
import XmAttachmentCus from '@product/iam/core/attachment/xm-attachment-cus'
import XmSdAttachmentex from './xm-sd-attachment-ex.vue'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import components from './_import-components/audit-project-detail-import'

export default {
  name: 'AuditProjectDetail',
  metaInfo: {
    title: '审计项目详情',
  },
  components: {
    ...components,
    XmSdAttachmentex,
    iamAuditNoticeTemplateSelect,
    auditFormTopBanner,
  },
  data() {
    return {
      userMember: '',
      visible: false,
      temdataurl: '',
      templateList: [],
      temtype: '03',
      groupId: '',
      noticeAttachmentKey: 0,
      projectInfo: null, // 项目信息
      projectId: '',
    }
  },
  mounted() {
    // debugger
    axios({
      url:
        `api/xcoa-mobile/v1/iamauditproject/getProjectUserList?projectId=` +
        this.$route.query.record,
      method: 'get',
    }).then((res) => {
      this.userMember = res.data.join(',')
    })
    // 获取一个随机的附件GroupId
    axios({
      url: `api/xcoa-mobile/v1/iamauditproject/getGroupId`,
      method: 'get',
    }).then((res) => {
      console.log('group-Id --------------', res.data)
      this.groupId = res.data
    })
  },
  created() {
    // 获取模板列表
    if (this.$route.query.projectId) {
      this.projectId = this.$route.query.projectId
      const ini = setInterval(() => {
        if (this.$refs.flow) {
          clearInterval(ini)
        }
      })
    } else if (this.$route.query.record) {
      this.projectId = this.$route.query.record
    } 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: {
    // 展示选择模板窗口
    selectTemplate() {
      // debugger
      // 获取模板列表
      if (this.$route.query.projectId) {
        this.projectId = this.$route.query.projectId
      } else if (this.$route.query.record) {
        this.projectId = this.$route.query.record
      }
      // 获取项目信息
      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.form.getFieldValue('auditedUnitNames')
      let auditedText = ''
      auditedText = auditedUnit
      // 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)
            })
        })
      })
    },
    close(flag) {
      crossWindowWatcher.notifyChange(this.$route.fullPath, flag)
      window.close()
    },
    getFormFieldValue(name) {
      const objArry = this.$refs.form.getFieldValue(name)
      if (objArry !== undefined) {
        if (objArry.length > 0) {
          let result = ''
          objArry.forEach((e) => {
            result += e.name + ','
          })
          return result.substr(0, result.length - 1)
        }
      }
      return ''
    },
  },
}
</script>

<style module lang="scss">
@import '@/webflow/sd-flow-form.scss';

.formDiv {
  padding: 22px;

  :global(.buttons_sd-detail-form_common) {
    :global(.ant-form-item-control-wrapper) {
      padding-top: 4%;
      padding-left: 24%;
    }
  }

  .tr_border {
    box-sizing: border-box;
    border-right: 1px solid #e8e8e8;
    border-left: 1px solid #e8e8e8;
  }

  :global(.title_sd-detail-form_common) {
    font-size: 1.5em;
    text-align: center;
  }

  :global(.buttons_sd-detail-form_common) {
    display: none;
  }
}

.close-btn,
.save-btn {
  position: absolute;
  top: 18px;
  font-size: 16px;
  font-weight: 400;
  color: #fff;
  cursor: pointer;
  border: none;
}

.close-btn {
  right: 15px;
}

.page {
  height: 100%;

  :global(.sd-frame-main) {
    height: 100%;
    padding: 10px;
    overflow: auto;
  }
}

.header {
  background: linear-gradient(to right, #3f9bff, #0e7df6);

  .header-title {
    display: inline;
    font-size: 25px;
    font-weight: 400;
    color: #fff;
  }
}

.wrapContent {
  padding-top: 20px;
}
:global .auditprojectdetailname > td.ant-form-item-label > label {
  white-space: break-spaces !important;
}
</style>
