<template>
  <div>
    <sd-webflow ref="flow" :removed-tabs="['sdRelatedDoc']" @actionBtnClick="actionBtnClick">
      <template v-slot:form="{ model, fields, FlowData }">
        <table :class="$style.lawapply">
          <tr>
            <sd-form-item-td label="报告标题" 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 label="报告文号" name="reportNumber"> </sd-form-item-td>
            <sd-form-item-td name="issueDate" />
          </tr>
          <tr>
            <sd-form-item-td name="auditedUnit" />
            <!-- <sd-form-item-td name="reportType" :input-props="{ defaultValue: '02' }" /> -->
            <sd-form-item-td name="reportType">
              <span>
                {{ reportType }}
              </span>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td label="审计报告" name="reportAttachment" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <!-- <sd-attachment-ex
                  :key="reportAttachmentKey"
                  ref="reportAttachment"
                  v-model="model.reportAttachment"
                  :group-id="JSON.parse(fields.reportAttachment.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"
                  :class="lawapply"
                /> -->

                <sd-attachment
                  v-model="model.reportAttachment"
                  :group-id="JSON.parse(fields.reportAttachment.value).value"
                  :read-only="!editable"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="workPaper" :colspan="3">
              <template v-slot:read-and-edit="{ editable }">
                <sd-attachment
                  v-model="model.workPaper"
                  :group-id="JSON.parse(fields.workPaper.value).value"
                  :read-only="!editable"
                />
              </template>
            </sd-form-item-td>
          </tr>
          <tr>
            <sd-form-item-td name="drawUpName" />

            <sd-form-item-td name="drawUpTime" />
          </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>
        </table>

        <table>
          <tr v-if="false"
            ><td :colspan="4">
              <sd-form-item
                name="iamAuditReportFeedbackList"
                :label="null"
                :input-td-attrs="{ class: 'feedbackEntities' }"
              >
                <template v-slot:read-and-edit="{ editable }">
                  <audit-advanced-group
                    :expand="expand"
                    :expand-str="'expand'"
                    :group-label="'被审计单位反馈情况'"
                    @changedClick="changedClick"
                  >
                    <template>
                      <xm-child-table
                        :key="key"
                        ref="childTable"
                        v-model="model.iamAuditReportFeedbackList"
                        label=""
                        :read-only="!editable"
                        :fields="childFields"
                        :columns="childColumns"
                        modal-width="800px"
                      >
                        <!-- <template v-slot:feedbackExplain="{ field, text, value, index }">
                          <a-textarea v-model="value[index].feedbackExplain" :rows="3" />
                        </template> -->
                        <!-- input-form 表示这部分是子表组件的form插槽 -->
                        <!-- <template v-slot:form="{ model, fields }">
                          <table :class="$style.xmTable">
                            <tr>
                              <!- - 反馈日期 -- >
                              <sd-form-item-td name="feedbackDate">
                                <template v-slot:read-and-edit="{ editable }">
                                  <a-date-picker
                                    v-model="model.feedbackDate"
                                    style="width: 100%;"
                                  />
                                </template>
                              </sd-form-item-td>
                            </tr>
                            <tr>
                              <!- - 简要说明 -- >
                              <sd-form-item-td name="feedbackExplain">
                                <template v-slot:read-and-edit="{ editable }">
                                  <a-textarea
                                    v-model="model.feedbackExplain"
                                    :auto-size="{ minRows: 3, maxRows: 3 }"
                                  ></a-textarea>
                                </template>
                              </sd-form-item-td>
                            </tr>
                            <tr>
                              <! -- 附件 -- >
                              <sd-form-item-td name="attachment">
                                <sd-attachment
                                  v-model="model.attachment"
                                  :group-id="JSON.parse(fields.attachment.value).value"
                                />
                              </sd-form-item-td>
                            </tr>
                          </table>
                        </template> -->
                      </xm-child-table>
                    </template>
                  </audit-advanced-group>
                </template>
              </sd-form-item></td
            >
          </tr>
        </table>
      </template>
    </sd-webflow>
    <a-modal
      :visible="visible"
      destroy-on-close
      width="1200px"
      title="选择报告模板及审计发现"
      :confirm-loading="confirmLoading"
      @cancel="hiddenModal"
      @ok="autoTaoDaFile"
    >
      <iam-audit-report-template-select
        ref="templateSelect"
        :project-id="projectId + ''"
        :template-list="templateList"
      ></iam-audit-report-template-select>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
import axios from '@/common/services/axios-instance'
import loginService from '@/login/login-service'
import { Message, Modal } from 'ant-design-vue'
// import sdAttachmentEx from '@/common/components/sd-attachment-ex.vue'
import auditAdvancedGroup from '../../../../components/audit-advanced-group.vue'
import auditAdvancedGroupMixins from '../../../../components/audit-advanced-group-mixins'
import iamAuditReportTemplateSelect from './iam-audit-report-template-select.vue'
import AuditService from './iam-audit-report-service'
import components from './_import-components/iam-audit-report-form-import'

function changeNumToHan(num) {
  var arr1 = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']
  var arr2 = [
    '',
    '十',
    '百',
    '千',
    '万',
    '十',
    '百',
    '千',
    '亿',
    '十',
    '百',
    '千',
    '万',
    '十',
    '百',
    '千',
    '亿',
  ]
  if (!num || isNaN(num)) return '零'
  var english = num.toString().split('')
  var result = ''
  for (var i = 0; i < english.length; i++) {
    var desi = english.length - 1 - i // 倒序排列设值
    result = arr2[i] + result
    var arr1index = english[desi]
    result = arr1[arr1index] + result
  }
  result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十') // 将【零千、零百】换成【零】 【十零】换成【十】
  result = result.replace(/零+/g, '零') // 合并中间多个零为一个零
  result = result.replace(/零亿/g, '亿').replace(/零万/g, '万') // 将【零亿】换成【亿】【零万】换成【万】
  result = result.replace(/亿万/g, '亿') // 将【亿万】换成【亿】
  result = result.replace(/零+$/, '') // 移除末尾的零
  // 将【一十】换成【十】
  result = result.replace(/^一十/g, '十')
  return result
}

// 修改主子表的首行title名
export default {
  name: 'IamAuditReport',
  metaInfo: {
    title: '审计报告信息',
  },
  components: {
    ...components,
    // sdAttachmentEx,
    auditAdvancedGroup,
    iamAuditReportTemplateSelect,
  },
  mixins: [auditAdvancedGroupMixins],
  data() {
    return {
      temtype: '06',
      temdataurl: '',
      key: 1,
      expand: true,
      operNum: 1,
      childFields: [],
      childColumns: [
        {
          title: '序号',
          dataIndex: 'xh',
          customRender: (text, record, index) => `${index + 1}`,
          width: '80px',
        },
        {
          title: '反馈日期',
          dataIndex: 'feedbackDate',
          width: '200px',
        },
        {
          title: '简要说明',
          dataIndex: 'feedbackExplain',
          dataType: 'tinymce',
        },
        {
          title: '附件',
          dataIndex: 'attachment',
          dataType: 'attachment',
        },
      ],
      projectId: null, // 项目ID
      templateList: [],
      visible: false,
      reportAttachmentKey: 0,
      projectTitle: '',
      startTime: '',
      endTime: '',
      confirmLoading: false,
      reportType: '',
    }
  },
  mounted() {
    // console.log('1------', this.$route.query.extParams)
    if (this.$route.query.extParams) {
      if (JSON.parse(this.$route.query.extParams).reportType) {
        this.$refs.flow.setFieldValue(
          'reportType',
          JSON.parse(this.$route.query.extParams).reportType
        )
      }
    }
    const reportType = this.$refs.flow.getFieldValue('reportType')
    if (reportType === '02') {
      this.reportType = '正式报告'
    }
    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)
    }

    if (
      this.$refs.flow.getFieldValue('fileTitle') === null ||
      this.$refs.flow.getFieldValue('fileTitle') === '' ||
      this.$refs.flow.getFieldValue('fileTitle') === undefined
    ) {
      Promise.all([
        AuditService.getProjectInfoById(this.projectId),
        AuditService.getAuditedUnitById(this.projectId),
      ]).then((res) => {
        this.$refs.flow.setFieldValue('fileTitle', res[0].data.projectTitle + '审计报告')
        if (!this.$refs.flow.getFieldValue('auditedUnit')) {
          this.$refs.flow.setFieldValue('auditedUnit', res[1].data)
        }
        // 记录准备开始与实施结束与项目名称
        this.projectTitle = res[0].data.projectTitle
        this.startTime = moment(res[0].data.prepareStartTime).format('YYYY年MM月DD日')
        this.endTime = moment(res[0].data.executeEndTime).format('YYYY年MM月DD日')
      })
    }

    const child = this.$refs.flow.flowData.processFormData.processFormPropertyValues.find(
      (item) => {
        return item.name === 'iamAuditReportFeedbackList'
      }
    )
    if (child) {
      this.childFields = this.getFields(child.attr.dync)
      this.key++
    }
    this.childFields.forEach((item) => {
      if (item.dataType === 'attachment') {
        item.value = '{"value":"' + Math.round(Math.random() * 100000000000000000).toString() + '"}'
      }
    })
    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: {
    // validForm() {
    // return this.$refs.childTable.valid().then((res) => {
    //   // 校验动态子表
    //   debugger
    //   if (res) {
    //     // 校验动态子表
    //     return Promise.resolve(true)
    //   } else {
    //     return Promise.resolve(false)
    //   }
    // })
    // },
    // 展示选择模板窗口
    selectTemplate() {
      this.visible = true
    },
    // 隐藏选择模板窗口
    hiddenModal() {
      this.$refs.reportAttachment.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
        this.confirmLoading = 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.reportAttachment.groupId}?catNum=-1&fromTemplate=1`
              )
              .then((res) => {
                // 执行套打
                this.taodafile(tmpName)
              })
          })
      }
    },
    taodafile(fileName) {
      const indiDocX = this.$refs.reportAttachment
      // 拼接套打内容
      const selectFind = this.$refs.templateSelect.$refs.sjzlTable.getSelectedRows()
      const auditedUnit = this.$refs.flow.getFieldValue('auditedUnit')
      let auditedText = ''
      auditedUnit.forEach((item) => {
        auditedText += item.name
      })
      const contentText = []
      selectFind.forEach((item, index) => {
        contentText.push(
          '（' +
            changeNumToHan(index + 1) +
            '）' +
            item.findTitle +
            '\r\n' +
            '发现描述：' +
            item.findDesc +
            '\r\n' +
            '管理建议：' +
            item.suggestion +
            '\r\n'
        )
      })
      // 更新完附件列表之后，才自动套打
      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,
            {
              审计发现内容: contentText.join(''),
              开始时间: this.startTime,
              结束时间: this.endTime,
              被审计单位: auditedText,
              项目名称: this.projectTitle,
              当前日期: 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.confirmLoading = false
              this.hiddenModal()
            })

            .catch(() => {
              indiDocX.markBusy(userFile, false)
              this.confirmLoading = false
            })
        })
      })
    },

    // 增加序号列
    getFields(fields) {
      const xh = [
        {
          caption: '序号',
          dataType: 'string',
          index: 0,
          mobileVisible: true,
          name: 'xh',
        },
      ]
      fields.reverse()
      fields = fields.filter((item) => {
        return item.name !== 'projectId'
      })

      return [...xh, ...fields]
    },
    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 {
        // 生成文件编号
        AuditService.getFileCode(this.projectId).then((res) => {
          this.$refs.flow.setFieldValue('fileCode', res.data)
          callback(false)
        })
      }
    },
    // 批量导入
    batchInport() {
      this.handleBeforeAdd(null, (res) => {
        if (!res) {
          Modal.info({
            title: '提示',
            content: '导入功能尚未开发!',
          })
        }
      })
    },
    // 标题格式化
    formatterTitle(val, length) {
      var resultArry = []
      let title = ''
      let result = ''
      if (val === undefined || val === '' || val === '[]') {
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      } else {
        try {
          JSON.parse(val).forEach((e) => {
            result += e.name + ','
          })
        } catch (e) {
          result = val
        }
        if (result.lastIndexOf(',') > 0) {
          result = result.substr(0, result.length - 1)
        }
        title = result
        if (result.length > length) {
          result = result.substr(0, length) + '...'
        }
        resultArry.push(title)
        resultArry.push(result)
        return resultArry
      }
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.xm-table {
  :global(td.ant-form-item-label) {
    width: 15%;
  }
}

.lawapply {
  :global(.buttons_sd-attachment-ex_common > .ant-btn-primary) {
    display: none;
  }
}
</style>
