<template>
  <el-dialog
    :visible.sync="dialogVisible"
    fullscreen
    append-to-body
    class="form-print-dialog"
    v-loading.fullscreen.lock="fullscreenLoading"
  >
    <div class="navbar-default box-shadow flex notprint">
      <el-page-header content="打印预览" @back="goBack"></el-page-header>
      <span>
        <el-button v-show="false" ref="printBtn" v-print="'#printFlow'">
          打印
        </el-button>
        <el-button
          icon="el-icon-printer"
          type="primary"
          :disabled="loading"
          @click="printProxy"
        >
          打印
        </el-button>
      </span>
    </div>
    <div id="printFlow" ref="printFlow" style="page-break-inside: avoid;">
      <div v-if="showPrintCount" id="print-count-content">
        <h3>打印次数：{{ printCount }}</h3>
      </div>
      <h2
        class="form-top-title"
        :style="{ '--statusBg': getCurrentStatusColorOrText('color') }"
      >
        <span class="status-icon"></span>
        <i class="status-text">
          {{ getCurrentStatusColorOrText('text') }}
        </i>
      </h2>
      <ht-online-form
        v-if="form.type == 'INNER'"
        ref="flowOnlineForm"
        v-loading="loading"
        class="online-form"
        :html="innerHtml"
        :data="data"
        :permission="permission"
        :extend-prop="recordData"
        :is-view="false"
      />
      <iframe
        v-else-if="form.type == 'FRAME'"
        name="flowFrameFormPrint"
        :src="form.formValue"
      ></iframe>
      <!-- 流程图 -->
      <ht-flow-chart
        v-if="showFlowImage && dialogVisible"
        ref="flowChart"
        :dialog=false
        :inst-id="instId"
        :bpmn-inst-id="instId"
        :def-id="flowDefId"
        class="print-component_content"
      />
      <process-record
        v-if="showHistory && dialogVisible"
        :inst-id="instId"
        :task-id="taskId"
        :refer-opinion="referOpinion"
        :node-type="nodeType"
        :def-id="flowDefId"
        :node-id="nodeId"
        :over-tool-tip="false"
        class="print-component_content"
      />
    </div>
  </el-dialog>
</template>
<script>
  import { mapState } from 'vuex'
  import ProcessRecord from '@/components/flow/processRecord.vue'
  import watermark from './watermark.js'
  import {
    getBpmPrintRecordByInstId,
    getWatermarkByInstId,
  } from '@/api/flow.js'
  import { getFormById } from '@/api/form.js'
  import PrintImage from './PrintImage.vue'
  import print from '@/assets/print'
  import { STATUS_COLOR } from '../form/const.js'
  export default {
    name: 'FormPrintDialog',
    directives: {
      print,
    },
    components: {
      PrintImage,
      ProcessRecord,
    },
    props: {
      form: Object,
      data: {
        type: Object,
        default: () => {
          return new Object()
        },
      },
      showPrintCount: {
        type: Boolean,
        default: false,
      },
      showFlowImage: {
        type: Boolean,
        default: false,
      },
      showHistory: {
        type: Boolean,
        default: false,
      },
      flowDefId: {
        type: String,
        default: '',
      },
      instId: {
        type: String,
        default: '',
      },
      taskId: {
        type: String,
        default: '',
      },
      referOpinion: {
        type: Boolean,
        default: true,
      },
      nodeType: {
        type: String,
        default: '',
      },
      nodeId: {
        type: String,
        default: '',
      },
      instanceStatus: {
        type: String,
        default: '',
      },
      recordData: {
        type: Object,
        default: () => {
          return {}
        },
      },
    },
    data() {
      return {
        dialogVisible: false,
        innerHtml: '',
        loading: false,
        permission: {},
        printCount: 0,
        watermarkSetting: null,
        fullscreenLoading: false,
      }
    },
    computed: {
      ...mapState('user', ['userInfo']),
      instStatus() {
        return this.instanceStatus
      },
    },
    created() {
      window.addEventListener('message', this.handleFrameMessagePrint)
    },
    beforeDestroy() {
      window.removeEventListener('message', this.handleFrameMessagePrint)
    },
    mounted() {
      window.temp1 = this
      getWatermarkByInstId(this.instId).then((data) => {
        this.watermarkSetting = data
      })
    },
    methods: {
      printProxy() {
        if (this.watermarkSetting) {
          watermark.watermark(
            {
              watermark_txt: this.watermarkSetting.content,
              watermark_color: this.watermarkSetting.color,
              watermark_type: this.watermarkSetting.type,
            },
            document.getElementById('printFlow')
          )
        }
        this.$refs['printBtn'].$el.click()
        setTimeout(() => {
          this.printCount++
          this.saveRecord()
        }, 200)
      },
      getFrameFormElement() {
        const frm = document.querySelectorAll("[name='flowFrameFormPrint']")[0]
        const frmControl = document.querySelectorAll("[name='iframeControl']")
        if (!frm && !frmControl) {
          this.$message.error('当前URL表单加载不正确。')
        }
        return frm
      },
      // 处理iframe表单发送过来的消息
      handleFrameMessagePrint(e) {
        if (
          !e ||
          !e.data ||
          !e.data.type ||
          e.data.type.startsWith?.('webpack')
        ) {
          return
        }
        const frm = this.getFrameFormElement()
        switch (e.data.type) {
          //调整iframe的高度
          case 'height': {
            frm.style.visibility = 'hidden'
            // 提前还原高度
            frm.setAttribute('height', 'auto')
            setTimeout(function () {
              frm.setAttribute('height', e.data.height)
              frm.style.visibility = 'visible'
              frm.dispatchEvent(new Event('mouseover'))
            }, 0)
            break
          }
        }
      },
      showDialog(formId) {
        const this_ = this
        if (formId) {
          const loading = this.$loading()
          getFormById(formId).then((resp) => {
            this_.convert2ReadOnly(resp.permission)
            this_.permission = resp.permission
            this_.innerHtml = resp.bpmForm.formHtml
            //处理表单的js脚本
            if (resp.bpmForm.diyJs) {
              try {
                this_.handlerJs(resp.bpmForm.diyJs)
              } catch (error) {
                this_.$message.error(
                  '表单JS脚本执行异常，打印失败，请校查配置JS脚本。'
                )
                this.$nextTick(() => {
                  loading.close()
                })
                return false
              }
            }
            this_.dialogVisible = true
            
            this.$nextTick(() => {
              if(this_.showFlowImage){
                this_.$refs['flowChart'].handleOpen()
              }
              loading.close()
            })
          })
        } else {
          this_.dialogVisible = true
          if(this_.showFlowImage){
            this_.$nextTick(() => {
              this_.$refs['flowChart'].handleOpen()
            })
          }
        }
        if (this.showPrintCount) {
          this.loadPrintCount()
        }
      },
      handlerJs(diyJs) {
        const userInfo = this.userInfo
        const currentUser = userInfo?.user
        let data = this.data
        let _this = this
        const $ = require('jquery')
        eval(diyJs)
      },
      goBack() {
        this.dialogVisible = false
      },
      flowPrint() {},
      convert2ReadOnly(permission) {
        const { fields, table } = permission
        for (let key in fields) {
          let obj = fields[key]
          for (let field in obj) {
            obj[field] = 'r'
          }
        }
        for (let key in table) {
          let obj = table[key]
          obj.add = false
          obj.del = false
        }
      },
      loadPrintCount() {
        getBpmPrintRecordByInstId(this.instId, this.nodeId).then((resp) => {
          this.printCount = resp ? resp.length + 1 : 1
        })
      },
      saveRecord() {
        this.$emit('save-record')
      },
      getCurrentStatusColorOrText(type) {
        const currentStatus = this.instStatus
        return STATUS_COLOR[currentStatus]?.[type]
      },
    },
  }
</script>
<style lang="scss">
  @media print {
    .notprint {
      display: none;
    }
    ::v-deep .form-table__wrap {
      width: 100% !important;
    }
    #print-count-content {
      display: flex;
      justify-content: flex-end;
    }
    .print-component_content {
      padding: 30px 20px;
    }
    ::v-deep .common-tools {
      display: none;
    }
    .print-component_content ::v-deep .cell > span {
      white-space: pre-wrap !important;
    }
    .print-component_content ::v-deep .el-table {
      height: 100% !important;
      max-height: 100% !important;
    }
    .print-component_content ::v-deep .el-table__body-wrapper {
      height: 100% !important;
      max-height: 100% !important;
    }

    ::v-deep .table_layout_wrap {
      margin: 0 !important;
    }
    .main-title{
      border: 1px solid black !important;
    }
    .main-field{
      border: 1px solid black !important;
    }
    .main-table{
      border: 1px solid black !important;
    }
  }
</style>
<style lang="scss" scoped>
  @mixin status-bg {
    mask: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI3OCIgaGVpZ2h0PSI2MCIgdmlld0JveD0iMCAwIDc4IDYwIj4NCiAgPHBhdGggaWQ9IuWNsOeroCIgZD0iTTM3LjM3Miw0MGwuODIxLS44MTNhMTUuNTg2LDE1LjU4NiwwLDAsMC0xLjM1Mi0uODYxLjY3NS42NzUsMCwwLDAtLjQzNSwwYy0uMDQ5LjA0OC0uMTQ1LjMzNS0uMDQ5LjQzYTEuMTM1LDEuMTM1LDAsMCwwLC40ODQuMTkxLDcuNTA4LDcuNTA4LDAsMCwxLDEuMDE0LjE5MWMtLjcyNS41NzMtLjkxOC41MjYtMS41NDYuMWEzLjExNywzLjExNywwLDAsMC0xLjUtLjcxNyw2LjUxNiw2LjUxNiwwLDAsMS0xLjc4Ny0uOTU2Yy0xLjgzNS0xLjA1Mi0zLjY3MS0yLjEtNS41NTQtMy4xMDgtMS45MzEtMS4xLTMuODY0LTIuMTUxLTUuOC0z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Mi4yNDctNS45ODktMy40NDItMS40NDktLjg2MS0yLjktMS43NjktNC40LTIuNTgycS0yLjEtMS4yMTQtNC4yNS0yLjM0M0ExOS41NzQsMTkuNTc0LDAsMCwwLDM3LjM3MSw0MFoiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC04LjI0OSAtMC4wNjMpIiBmaWxsPSIjYjhiOGI4Ii8+DQo8L3N2Zz4NCg==);
    mask-size: 100% 100%;
    mask-repeat: no-repeat;
    background-color: var(--statusBg);
    transform: rotate(-15deg);
  }
  
  iframe[name='flowFrameFormPrint'] {
    min-height: 300px;
    width: 100%;
    border: 0px;
  }
  .navbar-default {
    height: 100%;
    background-image: none;
    background: #fff;
    border-radius: 0px;
    box-shadow: 0px 2px 5px rgba(86, 96, 117, 0.15);
    border-bottom: 1px solid #ededed;
    justify-content: space-between;
    padding: 0 10px;
  }
  .navbar-default span {
    color: #666;
    font-size: 14px;
    line-height: 48px;
    font-weight: bold;
    margin-left: 20px;
  }
  .navbar-default ::v-deep .el-page-header__left {
    align-items: center;
  }
  .navbar-default ::v-deep .el-page-header__content {
    display: flex;
    align-items: center;
  }

  .navbar-default button {
    margin-right: 10px;
  }
  .form-print-dialog ::v-deep .el-dialog > .el-dialog__header {
    display: none;
  }

  .form-print-dialog ::v-deep .el-dialog > .el-dialog__body {
    padding-top: 10px;
    #print-count-content {
      display: flex;
      justify-content: flex-end;
    }
    .print-component_content {
      padding: 30px 20px;
      ::v-deep .cell > span {
        white-space: pre-wrap;
      }
    }
    .common-tools {
      display: none !important;
    }
  }
  #printFlow {
    width: 100%;
    height: auto;
  }
  ::v-deep .el-main {
    .formT_box {
      .form-table {
        width: 100%;
        .sub-table-header {
          th {
            border: 1px solid #f3f5f7;
            padding: 15px;
            background-color: #fafafa;
          }
        }
        tbody tr td {
          padding: 10px;
          border-right: 1px solid #ebeef5;
          border-bottom: 1px solid #ebeef5;
          box-sizing: border-box;
          text-overflow: ellipsis;
          vertical-align: middle;
          position: relative;
        }
      }
    }
  }
  .form-top-title {
    text-align: center;
    color: $base-dark-title-color;
    font-size: $base-font-size-large;
    margin: 24px 0 20px 0;
    height: 46px;
    line-height: 46px;
    position: relative;
    .status-icon {
      @include status-bg;
      position: absolute;
      display: inline-block;
      width: 78px;
      height: 60px;
      right: 44px;
      top: 3px;
      user-select: none;
    }
    .status-text {
      position: absolute;
      right: 53px;
      transform: rotate(15deg);
      top: 9px;
      color: var(--statusBg);
      font-size: $base-font-size-large;
      font-weight: 400;
      user-select: none;
    }
  }
</style>
