<template>
  <a-modal
    :destroy-on-close="true"
    :footer="null"
    dialog-class="sd-web-print"
    width="210mm"
    :get-container="() => this.$el"
    :visible="isPrinting"
    @cancel="close"
  >
    <div slot="title" :class="$style.header">
      <a-button :class="$style.printbtn" type="primary" @click="print">打印</a-button>
    </div>
    <sd-print-container :default-print-blocks="webflow.defaultPrintBlocks">
      <sd-print-form :flow-data="webflow.flowData" :data-order="100">
        <template v-slot="scope">
          <slot name="form" v-bind="scope" />
        </template>
      </sd-print-form>
      <sd-webflow-print-block key="sd-opinion-log" title="审批意见" :data-order="200">
        <sd-opinion-log-print />
      </sd-webflow-print-block>
      <sd-webflow-print-block key="sd-process-info" title="流转记录" :data-order="300">
        <sd-process-info />
      </sd-webflow-print-block>
      <sd-webflow-print-block key="sd-inform-log" title="知会记录" :data-order="400">
        <sd-inform-log />
      </sd-webflow-print-block>
      <sd-webflow-print-block key="sd-reminder-log" title="催办记录" :data-order="500">
        <sd-reminder-log />
      </sd-webflow-print-block>
      <sd-webflow-print-block key="sd-modify-log" title="修改记录" :data-order="600">
        <sd-modify-log />
      </sd-webflow-print-block>
      <sd-webflow-print-block key="sd-relate-doc" title="关联文件" :data-order="700">
        <sd-relate-doc read-only />
      </sd-webflow-print-block>
      <sd-webflow-print-block key="sd-flowchart" title="流程图" :data-order="800">
        <sd-flowchart
          id="printflowchart"
          :mode="webflow.flowData.mode"
          @tracingInfoUpdate="zoomFlowChart"
        />
      </sd-webflow-print-block>
      <slot name="print-content-bottom" :FlowData="webflow.flowData"></slot>
    </sd-print-container>
  </a-modal>
</template>

<script>
import Vue from 'vue'
import { Message } from 'ant-design-vue'
import axios from '@/common/services/axios-instance'
import pickValues from '@/common/services/pick-values'
import sdListPickerVue from '@/common/components/sd-list-picker.vue'
import attachmentIdToBase64 from '@/common/services/attachment-id-to-base-64'
import loginService from '@/login/login-service'
import components from './_import-components/sd-we-doc-print-import'

export default {
  name: 'SdWeDocPrint',
  components,
  props: {
    flowData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      isPrinting: false,
    }
  },
  methods: {
    run() {
      let resolve1
      return axios
        .get(
          `api/framework/v1/print-template/doctype/${this.webflow.getFieldValue(
            'businessTypeId'
          )}/template`
        )
        .then((res) => {
          if (res?.data?.length) {
            const list = res.data
            let p = Promise.resolve(list[0].attachment)
            if (list.length > 1) {
              p = pickValues(sdListPickerVue, {
                optionValue: 'attachment',
                optionLabel: 'templateName',
                single: true,
                loadListData: () => list,
                singleColumn: true,
              }).then((templates) => {
                if (!templates || templates.length === 0) return false
                return Promise.resolve(templates[0].attachment)
              })
            }
            return p.then((groupid) => {
              if (groupid) {
                axios
                  .get(`api/framework/v1/attachment-extend/attachments-info/${groupid}`)
                  .then((res) => {
                    if (res.data.length) {
                      const f = res.data[0]
                      this.getPrintData().then((printData) => {
                        const prefix = `${location.origin}${location.pathname}api`
                        let plugin
                        if (this.sdPlatform.isXC) {
                          plugin = import(
                            /* webpackChunkName: "wps" */ '../../../lib-external/wps.js'
                          )
                        } else {
                          plugin = import(
                            /* webpackChunkName: "indidocx" */ '../../../lib-external/IndiDocX.js'
                          )
                        }
                        plugin.then((pluginName) => {
                          const slCtl = pluginName.default.createInstance().slCtl
                          slCtl
                            .checkInstall({})
                            .then((flag) => {
                              if (flag) {
                                slCtl.Content.Control.PrintDocument(
                                  f.name,
                                  {
                                    FileServerUrl: `${prefix}/framework/v1/task-form-process/download-attachments/${f.code}?fileName=${f.name}`,
                                    DeleteLocalFile: 'true',
                                    NeedUpdate: 'false',
                                  },
                                  printData,
                                  {
                                    refresh_token: `${prefix}/refresh|${
                                      loginService.getTokens().refresh_token
                                    }`,
                                    sid: 'test',
                                    getActivationUrl: `${prefix}/framework/v1/dict-manager/dictvalues?keyId=INDIDOCX`,
                                  }
                                ).then(resolve1())
                              } else {
                                // eslint-disable-next-line prefer-promise-reject-errors
                                return Promise.reject()
                              }
                            })
                            .catch(() => {
                              Message.warn('未检测到控件,请先确认控件已正常安装')
                              resolve1()
                            })
                        })
                      })
                    } else {
                      Message.warn('没有找到打印模板文件')
                      resolve1()
                    }
                  })
              } else {
                resolve1()
              }
              return new Promise((resolve, reject) => {
                resolve1 = resolve
              })
            })
          } else {
            this.show()
          }
        })
    },
    getPrintData() {
      // 找到所有的签字图片id
      const signatures = []
      this.webflow.FlowData.processFormData.processFormPropertyValues
        .filter((item) => item.dataType === 'OpinionView')
        .forEach((item) => {
          this.webflow
            .getFieldValue(item.name)
            .filter((yj) => !yj.preview)
            .forEach((yj) => {
              if (yj.operator?.attrs?.signature) {
                if (!signatures.includes(yj.operator.attrs.signature)) {
                  signatures.push(yj.operator.attrs.signature)
                }
              }
            })
        })
      // 将签字图片id换成base64
      const map = {}
      let p = Promise.resolve(map)
      if (signatures.length) {
        p = Promise.all(signatures.map((id) => attachmentIdToBase64(id))).then((base64s) => {
          base64s.forEach((base64, index) => {
            map[signatures[index]] = base64.replace(/data.+?;base64,/, '')
          })
          return map
        })
      }
      return p.then((map) => {
        return this.webflow.getDisplayValues().then((data) => {
          this.webflow.FlowData.processFormData.processFormPropertyValues.forEach((item) => {
            if (item.dataType === 'OpinionView') {
              data[item.name] = this.webflow
                .getFieldValue(item.name)
                .filter((yj) => !yj.preview)
                .map((yj) => {
                  yj.content.signDate = Vue.filter('sdDateFormat')(yj.content.signDate)
                  yj.content.signUserName =
                    map[yj.operator?.attrs?.signature] || yj.content.signUserName
                  return yj.content
                })
              if (data[item.name].length === 0) {
                data[item.name] = ''
              }
            }
          })
          return data
        })
      })
    },
    show() {
      this.isPrinting = true
      document.body.classList.add('sd-printing')
    },
    close() {
      this.isPrinting = false
      setTimeout(() => {
        // 500ms 是等待动画播放完成
        document.body.classList.remove('sd-printing')
      }, 500)
    },
    print() {
      window.print()
    },
    zoomFlowChart(svgData) {
      this.$nextTick(() => {
        const svgWidth = svgData.getBoundingClientRect().width
        const modalWidth = document.getElementsByClassName('sd-web-print')[0].offsetWidth
        if (svgWidth > modalWidth) {
          const zoomNum = Math.floor((modalWidth / svgWidth) * 100) / 100 - 0.1
          document.getElementById('printflowchart').style.zoom = zoomNum
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$ie-left-margin: 15cm;
$page-margin: 17mm;
:global .sd-printing {
  .sd-web-print {
    // 覆盖style标签里面的样式
    /* stylelint-disable-next-line  */
    top: 0 !important;
    :global .ant-modal-content {
      height: 100vh;
      .ant-modal-body {
        max-height: calc(100vh - 65px);
        padding: 0;
      }
    }
  }
  :local(.header) {
    .ant-btn {
      z-index: 99;
      margin-right: 10px;
    }
  }
}

// 隐藏ie默认的页眉页脚
@page {
  margin: $page-margin (-$ie-left-margin);
}

@media screen {
  :global #sd-body .sd-web-print {
    .ant-modal-body {
      padding: $page-margin;
    }
  }
}

@media print, screen and (width: 800px) {
  @page {
    margin: $page-margin;
  }

  // 直接打印时的提示
  body:not(:global(.sd-printing)) {
    &::after {
      position: relative;
      top: 200px;
      display: block;
      font-size: $font-size-base * 3;
      text-align: center;
      content: '请使用页面上的“打印”按钮';
    }
    > div {
      display: none;
    }
  }
  :global(.browser-ie.sd-printing .sd-web-print .ant-modal-content) {
    position: static;
    padding: 0 $page-margin;
  }
  :global .sd-printing {
    /* stylelint-disable-next-line */
    overflow: auto !important;
    .sd-web-print {
      .ant-modal-content {
        position: absolute;
        top: 0;
        right: 0;
        left: 0;
        height: auto;
        border: none;
        box-shadow: none;
        .ant-modal-body {
          max-height: none;
          overflow: visible;
        }
      }
    }
    :local(.select-printbtn) {
      display: none;
    }
    /* stylelint-disable-next-line */
    .panel_sd-webflow-panel_webflow {
      height: auto;
      /* stylelint-disable-next-line */
      .skeleton-box_sd-webflow-panel_webflow,
      .ant-layout-header,
      .ant-layout-content,
      .ant-modal-header,
      .ant-modal-mask,
      .ant-modal-close {
        display: none;
      }

      .ant-modal-wrap,
      .ant-modal {
        position: static;
        overflow: visible;
      }
      /* stylelint-disable-next-line */
      .webflow_sd-webflow_webflow {
        display: block;
        height: auto;
      }
    }
  }
}
</style>
