<template>
  <el-dialog
    title="打印模式"
    :visible.sync="dialogVisible"
    width="60%"
    append-to-body
  >
    <span>
      <el-form
        :model="printForm"
        label-width="120px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="打印模式">
          <el-radio
            v-model="printForm.mode"
            label="noTemplate"
            @change="clearTempalte"
          >
            直接打印
          </el-radio>
          <el-radio
            v-model="printForm.mode"
            label="formTemplate"
            @change="clearTempalte"
          >
            表单模板
          </el-radio>
          <el-radio
            v-model="printForm.mode"
            label="officeTemplate"
            @change="clearTempalte"
          >
            套打
          </el-radio>
        </el-form-item>
        <el-form-item v-if="printForm.mode == 'formTemplate'" label="选择模板">
          <el-select v-model="printForm.template" size="mini">
            <el-option
              v-for="item in data.filter(
                (item) => !!item.id && item.isMain == 'Y'
              )"
              :key="item.id"
              :label="item.fileName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="printForm.mode == 'officeTemplate'"
          label="选择模板"
        >
          <el-select v-model="printForm.template" size="mini">
            <el-option
              v-for="item in data.filter((item) => !!item.fileId)"
              :key="item.fileId"
              :label="item.fileName"
              :value="item.fileId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="
            printForm.mode === 'noTemplate' || printForm.mode === 'formTemplate'
          "
          label="附加打印"
        >
          <el-checkbox
            v-model="printForm.extra.printCount"
            label="打印次数"
            :indeterminate="false"
          ></el-checkbox>
          <el-checkbox
            v-model="printForm.extra.history"
            label="审批历史"
            :indeterminate="false"
          ></el-checkbox>
          <el-checkbox
            v-model="printForm.extra.flowImage"
            label="流程图"
            :indeterminate="false"
          ></el-checkbox>
        </el-form-item>
      </el-form>

      <!-- <ht-table
        v-if="dialogVisible"
        :data="data"
        :page-result="pageBean"
        :selectable="false"
        :no-header="true"
        @load="loadData"
      >
        <template #toolbar>
          <el-button size="small" @click="notTemplatePrint" type="primary">
            不使用模板
          </el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </template>
        <ht-table-column prop="fileName" label="模板名"></ht-table-column>
        <ht-table-column prop="createTime" label="创建时间"></ht-table-column>
        <ht-table-column label="模板类型">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.printType === 'word'"
              type="primary"
              size="mini"
            >
              word模板
            </el-tag>
            <el-tag v-if="scope.row.printType === 'excel'" type="info">
              excel模板
            </el-tag>
            <el-tag
              v-else-if="scope.row.printType === 'form'"
              type="success"
              size="mini"
            >
              表单模板
            </el-tag>
          </template>
        </ht-table-column>
        <ht-table-column prop="fileName" label="是否主版本">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.isMain === 'Y'" type="primary">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </template>
        </ht-table-column>
        <ht-table-column label="操作">
          <template #default="{ row }">
            <el-button
              v-if="row.printType == 'word'"
              icon="el-icon-printer"
              size="mini"
              @click="openWordPrint(row, 'download')"
            >
              打印
            </el-button>
            <el-button
              v-if="row.printType == 'word'"
              icon="el-icon-view"
              size="mini"
              @click="openWordPrint(row, 'preview')"
            >
              预览
            </el-button>
            <el-button
              v-if="row.printType == 'form'"
              icon="el-icon-document"
              size="mini"
              @click="openPreview(row)"
            >
              打印预览
            </el-button>
          </template>
        </ht-table-column>
      </ht-table> -->
    </span>
    <div slot="footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button @click="showPrintRecord">查看打印记录</el-button>
      <el-button
        v-if="
          printForm.mode == 'noTemplate' || printForm.mode == 'formTemplate'
        "
        type="primary"
        @click="handlePrint"
      >
        打印
      </el-button>
      <template v-if="printForm.mode == 'officeTemplate'">
        <el-button
          v-if="selectTemplate.allowPreview"
          type="primary"
          @click="openWordPrint('preview')"
        >
          预览
        </el-button>
        <el-button
          v-if="selectTemplate.allowDownload"
          type="primary"
          @click="openWordPrint('download')"
        >
          下载
        </el-button>
      </template>
    </div>
    <form-print-dialog
      ref="formPrintDialog"
      :data="formData"
      :show-print-count="printForm.extra.printCount"
      :show-flow-image="printForm.extra.flowImage"
      :show-history="printForm.extra.history"
      :inst-id="procInstId"
      :refer-opinion="referOpinion"
      :node-type="nodeType"
      :node-id="nodeId"
      :task-id="taskId"
      :form="form"
      :record-data="recordData"
      :instance-status="instanceStatus"
      @save-record="saveRecord"
    ></form-print-dialog>
    <print-record-dialog
      ref="printRecordDialog"
      :inst-id="procInstId"
      :node-id="nodeId"
      :def-id="defId"
    ></print-record-dialog>
  </el-dialog>
</template>

<script>
  import FormPrintDialog from './FormPrintDialog.vue'
  import { wordPrint } from '@/api/form.js'
  import { downloadFile, getFileById } from '@/api/portal.js'
  import { savePrintRecord } from '@/api/flow.js'
  import PrintRecordDialog from './PrintRecordDialog.vue'
  import { mapGetters, mapState } from 'vuex'
  const { saveAs } = require('file-saver')
  export default {
    name: 'FormPrint',
    components: { FormPrintDialog, PrintRecordDialog },
    props: {
      form: Object,
      data: {
        type: Array,
        default: () => {
          return new Array()
        },
      },
      formData: {
        type: Object,
        default: () => {
          return new Object()
        },
      },
      permission: {
        type: Object,
        default: () => {
          return new Object()
        },
      },
      nodeId: {
        type: String,
        default: '',
      },
      defId: {
        type: String,
        default: '',
      },
      procInstId: {
        type: String,
        default: '',
      },
      formId: {
        type: String,
        default: '',
      },
      instId: {
        type: String,
        default: '',
      },
      referOpinion: {
        type: Boolean,
        default: true,
      },
      nodeType: {
        type: String,
        default: '',
      },
      taskId: {
        type: String,
        default: '',
      },
      defKey: {
        type: String,
        default: '',
      },
      formKey: {
        type: String,
        default: '',
      },
      instanceStatus: {
        type: String,
        default: '',
      },
      recordData: {
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    data() {
      return {
        pageBean: {
          page: 1,
          pageSize: 20,
          total: 0,
        },
        dialogVisible: false,
        init: true,
        printForm: {
          mode: 'noTemplate', // noTemplate, formTemplate, officeTemplate
          template: '',
          extra: {
            printCount: false,
            history: false,
            flowImage: false,
          },
        },
        selectTemplate: {},
      }
    },
    computed: {
      ...mapGetters('user', ['accessToken']),
      ...mapState('matter', ['processNodes']),
    },
    watch: {
      'printForm.template': {
        handler: function (newVal, oldVal) {
          if (this.printForm.mode == 'noTemplate') {
            this.$set(this, 'selectTemplate', {})
          }
          this.$set(
            this,
            'selectTemplate',
            this.data.filter(
              (item) => newVal == item.id || newVal == item.fileId
            )[0] || {}
          )
        },
      },
    },
    methods: {
      getPageBean() {
        return this.pageBean
      },
      showDialog() {
        if (this.dialogVisible) {
          return
        }
        this.init = true
        this.$store.dispatch('matter/getProcessNodes', this.defId)
        this.$emit('loadTempalte', null, (hasData) => {
          this.$nextTick(() => {
            this.init = false
          })
          // if (hasData) {
          this.dialogVisible = true
          // } else {
          //   this.$emit('printCurForm')
          // }
        })
      },
      closeDialog() {
        this.dialogVisible = false
      },
      notTemplatePrint() {
        this.dialogVisible = false
        this.$nextTick(() => {
          this.$emit('printCurForm')
        })
      },
      loadData(param, cb) {
        if (this.init) {
          cb()
          return
        }
        this.$emit('loadTempalte', param, cb)
      },
      openWordPrint(action) {
        const data = {
          id: this.selectTemplate.templateId,
          boData: JSON.stringify(this.formData),
          fileId: this.selectTemplate.fileId,
          // subject: this.selectTemplate.fileName,
          // scriptStr: this.selectTemplate.scriptStr || '',
          // flowOpinions: [],
          defId: this.defId,
          nodeId:
            this.nodeId ||
            (this.processNodes.find((node) => node.type === 'start')
              ? this.processNodes.find((node) => node.type === 'start').nodeId
              : ''),
          // formKey: this.formKey,
          procInstId: this.procInstId,
        }
        const this_ = this
        wordPrint(data).then(async (resp) => {
          if (!resp.state) {
            this_.$message.error('文档渲染失败')
          } else {
            let fileName = this.selectTemplate.fileName
            if (!fileName || !fileName.includes('.')) {
              let file = await getFileById(data.fileId)
              fileName = fileName + '.' + file.extensionName
            }
            const url = `${this.$file.previewUrl}?fileId=${resp.value}&token=${this.accessToken}`
            if (action == 'preview') {
              window.open(url)
            } else if (action == 'download') {
              downloadFile(resp.value, fileName)
            }
          }
        })
      },
      openPreview(row) {
        this.$refs['formPrintDialog'].showDialog(row.formId)
      },
      createObjectURL(content) {
        if (
          window.navigator.userAgent.indexOf('Chrome') >= 1 ||
          window.navigator.userAgent.indexOf('Safari') >= 1
        ) {
          return window.webkitURL.createObjectURL(content)
        } else {
          return window.URL.createObjectURL(content)
        }
      },
      clearTempalte() {
        this.printForm.template = ''
      },
      handlePrint() {
        const { mode } = this.printForm
        if (mode === 'noTemplate') {
          this.openPreview({ formId: this.formId })
          // if (this.formId) {
          //   this.openPreview({ formId: this.formId })
          // } else {
          //   let config = {
          //     showPrintCount: this.printForm.extra.printCount,
          //     showFlowImage: this.printForm.extra.flowImage,
          //     showHistory: this.printForm.extra.history,
          //   }
          //   this.$emit('printCurForm', config)
          // }
        } else if (mode === 'formTemplate') {
          //表单打印
          if (!this.printForm.template) {
            this.$message.warning('请选择打印模板')
            return
          }
          const formTemplate = this.data.filter(
            (item) => item.id == this.printForm.template
          )[0]
          if (formTemplate) {
            const { formId } = formTemplate
            this.openPreview({ formId })
          }
        }
        this.saveRecord()
      },
      saveRecord() {
        const data = {
          procDefKey: this.defKey,
          procDefName: '',
          procDefId: this.defId,
          procInstId: this.procInstId,
          nodeId:
            this.nodeId ||
            (this.processNodes.find((node) => node.type === 'start')
              ? this.processNodes.find((node) => node.type === 'start').nodeId
              : ''),
        }
        //暂时改成不是套打模板就不保存打印记录
        if (this.printForm.mode == 'noTemplate') {
          data['formKey'] = this.formKey
          data['templateName'] = '不使用模板'
        } else if (this.printForm.mode == 'formTemplate') {
          const formTemplate = this.data.filter(
            (item) => item.id == this.printForm.template
          )[0]
          if (formTemplate) {
            data['formKey'] = formTemplate['formKey']
            data['templateName'] = formTemplate['fileName']
          }
        } else if (this.printForm.mode == 'officeTemplate') {
          // 不需要处理
        }
        //套打已经在后端处理
        if (this.printForm.mode !== 'officeTemplate') {
          savePrintRecord(data).then(() => {})
        }
      },
      showPrintRecord() {
        this.$refs['printRecordDialog'].showDialog()
      },
    },
  }
</script>

<style lang="scss" scoped>
  .print-dialog_header {
    display: flex;
    justify-content: space-between;
  }
</style>
