import {
  autoConnect,
  disAutoConnect,
  hiprint,
  defaultElementTypeProvider,
} from '@afwenming123/vue-plugin-hiprint'
import { getConfigByNameAsync, runLogic } from '@vue2-client/services/api/common'
import hiPrintCss from '@vue2-client/base-client/components/common/XPrint/css/hiPrintCss'
import { uuid } from '@vue2-client/utils/util'

const hiPrintPlugin = {
  disAutoConnect,
  install: function (Vue, autoConnect = true, name = '$hiPrint') {
    if (!autoConnect) {
      disAutoConnect()
    }
    const globalVue = Vue.prototype || Vue.config.globalProperties
    globalVue[name] = hiprint
    /**
     * 预览打印，调起系统打印预览
     * provider 左侧拖拽元素
     * template 模版json字符串
     * args 打印数据data, options,
     */
    globalVue.$print = function (provider = defaultElementTypeProvider, template, ...args) {
      hiprint.init({
        // eslint-disable-next-line new-cap
        providers: [new provider()]
      })
      const hiprintTemplate = new hiprint.PrintTemplate({
        template: template,
      })
      hiprintTemplate.print(...args)
      return hiprintTemplate
    }
    /**
     * 单模版直接打印， 需客户端支持
     * provider 左侧拖拽项对象
     * template 模版json字符串
     * args 打印数据data, options,
     */
    globalVue.$print2 = function (provider = defaultElementTypeProvider, template, ...args) {
      hiprint.init({
        // eslint-disable-next-line new-cap
        providers: [new provider()]
      })
      const hiprintTemplate = new hiprint.PrintTemplate({
        template: template,
      })
      hiprintTemplate.print2(...args)
      return hiprintTemplate
    }
    /**
     * 通用打印方法
     * @param {string} templateName 模板名称
     * @param {object} printData 打印数据
     * @param {string} type 打印类型
     */
    const _commonPrint = async function (templateName, printData, type = 'B', customOption = {}) {
      return new Promise((resolve, reject) => {
        try {
          getConfigByNameAsync(templateName).then(async (template) => {
            if (!template) {
              this.$message.error(`${templateName} 打印模板不存在`)
              reject(new Error(`${templateName} 打印模板不存在`))
              return
            }
            if (template.dataLogicName) {
              const remoteData = await runLogic(template.dataLogicName, printData).catch(() => {
                this.$message.error(`${template.dataLogicName} 打印数据逻辑获取失败`)
                return {}
              })
              printData = Object.assign({}, printData, remoteData)
            }
            console.log('打印数据', printData)
            const printConfig = {
              callback: () => resolve(hiprintTemplate),
              styleHandler: () => hiPrintCss(),
              title: '打印测试',
              pageSize: {
                height: template.panels[0].height * 1000,
                width: template.panels[0].width * 1000
              },
              ...customOption
            }
            hiprint.init({
              // eslint-disable-next-line new-cap
              providers: [new defaultElementTypeProvider()]
            })
            const hiprintTemplate = new hiprint.PrintTemplate({
              template: template,
            })
            if (type === 'H') {
              resolve(hiprintTemplate.getHtml(printData).html())
            } else if (type === 'C') {
              hiprintTemplate.print2(printData, printConfig)
            } else {
              hiprintTemplate.print(printData, {}, printConfig)
            }
          }).catch((error) => {
            reject(error)
          })
        } catch (error) {
          reject(error)
        }
      })
    }

    /**
     * 浏览器打印
     */
    globalVue.$printB = async function (templateName, printData, customOption) {
      return _commonPrint(templateName, printData, 'B', customOption)
    }

    /**
     * 客户端打印
     */
    globalVue.$printC = async function (templateName, printData, customOption) {
      if (window.hiwebSocket.opened) {
        return _commonPrint(templateName, printData, 'C', customOption)
      } else {
        this.$message.error('请确保打印服务已经启动')
        return Promise.reject(new Error('客户端打印失败，未连接打印服务'))
      }
    }

    /**
     * 返回打印模板生成的 html
     */
    globalVue.$getHtml = async function (templateName, printData, customOption) {
      return _commonPrint(templateName, printData, 'H', customOption)
    }

    /**
     * 打印html
     */
    globalVue.$printHtml = async function (html, customOption = {}) {
      if (window.hiwebSocket.opened) {
        return window.hiwebSocket.send({
          title: '打印内容',
          html,
          imgToBase64: false,
          templateId: uuid(),
          id: uuid(),
          ...customOption
        })
      } else {
        this.$message.error('请确保打印服务已经启动')
        return Promise.reject(new Error('客户端打印失败，未连接打印服务'))
      }
    }
  }
}

window.hiprint = hiprint

export {
  autoConnect,
  disAutoConnect,
  hiprint,
  hiPrintPlugin,
  defaultElementTypeProvider,
}
