<template>
  <el-dialog
    v-if="dialogVisible"
    title="打印模式"
    :visible.sync="dialogVisible"
    width="480px"
    append-to-body
  >
    <div>
      <el-form
        :model="printForm"
        label-width="100px"
        :inline="false"
        size="normal"
        label-position="left"
      >
        <el-form-item v-if="this.formData.action != 'batch'" label="打印模式:">
          <el-radio v-model="printForm.mode" label="noTemplate">
            直接打印
          </el-radio>
          <el-radio v-model="printForm.mode" label="officeTemplate">
            批量套打
          </el-radio>
        </el-form-item>
        <el-form-item v-if="this.formData.action == 'batch'" label="打印模式:">
          <el-radio v-model="printForm.mode" label="officeTemplate">
            批量套打
          </el-radio>
        </el-form-item>
        <el-form-item
          v-if="printForm.mode == 'officeTemplate'"
          label="选择模板:"
        >
          <el-select
            v-model="printForm.template"
            style="width: 100%"
            size="mini"
          >
            <el-option
              v-for="item in printTemplateList"
              :key="item.alias"
              :label="item.name"
              :value="item.alias"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="
            printForm.mode == 'officeTemplate' &&
            fileJson &&
            fileJson.auth == 'w' &&
            printForm.template != ''
          "
          label="下载文件:"
        >
          <el-radio
            v-if="selectTemplate.printType == 'word'"
            v-model="printForm.fileType"
            label="word"
          >
            word文件
          </el-radio>
          <el-radio
            v-if="selectTemplate.printType == 'excel'"
            v-model="printForm.fileType"
            label="excel"
          >
            excel文件
          </el-radio>
          <el-radio v-model="printForm.fileType" label="pdf">pdf文件</el-radio>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer">
      <el-button
        @click="
          dialogVisible = false
          printForm.mode = 'noTemplate'
        "
      >
        取消
      </el-button>
      <el-button
        v-if="printForm.mode == 'noTemplate'"
        type="primary"
        @click="handlePrint"
      >
        打印
      </el-button>
      <template
        v-if="printForm.mode == 'officeTemplate' && printForm.template != ''"
      >
        <el-button
          v-if="this.formData.action != 'batch'"
          @click="openWordPrint('preview')"
        >
          预览
        </el-button>
        <el-button
          v-if="fileJson && fileJson.auth != 'r'"
          type="primary"
          @click="openWordPrint('download')"
        >
          下载
        </el-button>
      </template>
    </div>
  </el-dialog>
</template>

<script>
  const { saveAs } = require('file-saver')
  import utils from '@/utils'
  export default {
    name: 'HtTemplateBatchPrintDialog',
    data() {
      return {
        dialogVisible: false,
        init: true,
        printForm: {
          mode: 'noTemplate', // noTemplate, formTemplate, officeTemplate
          template: '',
          fileType: 'pdf',
          extra: {
            printCount: false,
            history: false,
            flowImage: false,
          },
        },
        formData: {},
        formBoData: {},
        fileJson: {},
        printTemplateList: [],
        selectTemplate: {},
      }
    },
    watch: {
      'printForm.mode': {
        handler: function (newVal) {
          if (this.printForm.mode == 'noTemplate') {
            this.$set(this, 'selectTemplate', {})
          } else {
            this.printForm.fileType = 'pdf'
            const templateAlias = this.printForm.template
            this.$set(
              this,
              'selectTemplate',
              this.printTemplateList.filter(
                (item) => templateAlias == item.alias
              )[0] || {}
            )
            if (this.selectTemplate.hasOwnProperty('fileJson')) {
              this.fileJson = JSON.parse(this.selectTemplate.fileJson)[0]
            }
          }
        },
      },
      'printForm.template': {
        handler: function (newVal) {
          if (this.printForm.mode == 'noTemplate') {
            this.$set(this, 'selectTemplate', {})
          } else {
            this.printForm.fileType = 'pdf'
            this.$set(
              this,
              'selectTemplate',
              this.printTemplateList.filter(
                (item) => newVal == item.alias
              )[0] || {}
            )
            if (this.selectTemplate.hasOwnProperty('fileJson')) {
              this.fileJson = JSON.parse(this.selectTemplate.fileJson)[0]
            }
          }
        },
      },
      printTemplateList: {
        handler(list) {
          if (list && list.length && list.length === 1) {
            this.printForm.template = list[0].alias
          }
        },
        immediate: true,
        deep: true,
      },
    },
    methods: {
      showDialog(formData) {
        this.formData = formData
        if (this.formData.action == 'batch') {
          this.printForm.mode = 'officeTemplate'
        }
        let { printTemplateVal, boDefAlias } = formData
        this.fetchPrintTemplateByBoAlias(printTemplateVal, boDefAlias)
        this.dialogVisible = true
      },
      closeDialog() {
        this.dialogVisible = false
      },
      openWordPrint(action) {
        if (!this.fileJson) {
          this.$message.error('当前模板不存在，请检查模板配置')
          return
        }
        //批量打印则需要调用批量打印方法
        if (this.formData.action == 'batch') {
          let data = {
            ids: this.formData.ids,
            printType: this.printForm.fileType,
            formWordPrintId: this.selectTemplate.id,
            boAlias: this.formData.boDefAlias,
            formKey: this.formData.formKey,
          }
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          this.$requestConfig
            .batchWordPrint(data)
            .then(({ data, headers }) => {
              const fileName = this.getFileName(headers)
              const blob = new Blob([data])
              saveAs(blob, fileName)
            })
            .finally(() => {
              loading.close()
            })
        } else {
          let formAlias = this.formData.formKey //表单别名
          let dataDefAlias = this.formData.boDefAlias //数据建模别名
          let pkVal = this.formData.id
          const instId = this.formData.instId
          this.$requestConfig
            .getDataTemplateForm(formAlias, dataDefAlias, pkVal)
            .then((resp) => {
              this.formBoData = resp.data
              const data = {
                id: this.selectTemplate.id,
                boData: JSON.stringify(this.formBoData),
                fileId: this.fileJson.id,
                printType: this.printForm.fileType,
                procInstId: instId,
              }
              const this_ = this
              this.$requestConfig.formWordPrint(data).then(async (resp) => {
                if (!resp.state) {
                  this_.$message.error('文档渲染失败')
                } else {
                  let accessToken = this.$requestConfig.getTokenOnly()
                  const url = `${window.context.portal}/onlinePreview?fileId=${resp.value}&token=${accessToken}`
                  if (action == 'preview') {
                    window.open(url)
                  } else if (action == 'download') {
                    this.downloadFile(resp.value)
                  }
                }
              })
            })
            .catch((error) => {
              this.$message.error('获取表单数据失败')
            })
        }
      },
      /**
       * 获取文件名
       * @param {*} headers 请求头
       */
      getFileName(headers) {
        const name = decodeURIComponent(
          headers['content-disposition'].split(';')[1].split('filename=')[1]
        )
        if(name && name != ''){
          return name
        }
        const unit = name.split('.')[1]
        if (this.formData.formName && unit) {
          return (
            this.formData.formName +
            '_' +
            utils.formatDateYear(new Date()) +
            '.' +
            unit
          )
        } else {
          return name
        }
      },
      downloadFile(file) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        this.$requestConfig
          .download(file)
          .then(({ data, headers }) => {
            if (data && headers) {
              // 附件下载
              const fileName = this.getFileName(headers)

              const blob = new Blob([data])
              saveAs(blob, fileName)
            }
          })
          .catch((err) => {
            this.$toast.fail(`附件下载失败：${err}`)
          })
          .finally(() => {
            loading.close()
          })
      },
      handlePrint() {
        const { mode } = this.printForm
        if (mode === 'noTemplate') {
          this.$emit('wordPrint', this.formData)
        }
        this.dialogVisible = false
      },
      fetchPrintTemplateByBoAlias(printTemplateVal, boDefAlias) {
        this.$requestConfig.getPrintTemplateByBoAlias(boDefAlias).then(
          (resp) => {
            if (resp.value && resp.value.length)
              this.printTemplateList = resp.value.filter((item) =>
                printTemplateVal.includes(item.alias)
              )
          },
          (error) => {
            console.log(error)
          }
        )
      },
    },
  }
</script>

<style lang="scss" scoped>
  .print-dialog_header {
    display: flex;
    justify-content: space-between;
  }
  ::v-deep .el-dialog__body {
    padding: 24px;

    .el-form-item {
      margin-bottom: 16px;
    }
  }
  ::v-deep .el-dialog__footer {
    text-align: right;
    padding: 16px 20px;
    border-top: 1px solid #ebebeb;
  }
</style>
