import { onMounted } from 'vue'

export interface LODOPObject extends HTMLObjectElement {
  VERSION: string;
  CVERSION: string;
  SET_LICENSES: (companyName: string, licenseA: string, licenseB: string, licenseC: string) => void;
  GET_PRINTER_COUNT: () => number;
  GET_PRINTER_NAME: (index: number) => string;
  PRINT_INIT: (printName: string) => void;
  SET_PRINTER_INDEX: (printerName: string) => void | string | number | boolean;
  SET_PRINT_MODE: (mode: string, value: boolean) => void;
  On_Return: (id: string, value: string) => void;
  On_Return_Remain: boolean;
  SEND_PRINT_RAWDATA: (data: string) => void;
  ADD_PRINT_PDF: (x: number, y: number, width: string, height: string, url: string) => void;
  GET_VALUE: (valueType: string, valueIndex: string | unknown) => string;
  PRINT: () => string;
  PRINTA: () => string;
}

export interface CLodopObject {
  CVERSION: string;
  GET_STATUS: () => number;
  GET_VALUE: (valueType: string, valueIndex: string | unknown) => string;
}

declare global {
  interface Window {
    LODOP: new () => LODOPObject;
    CLODOP: CLodopObject;
    getCLodop: () => LODOPObject;
  }
}

export default function useLodop() {
  let CLodopJsState: 'loading' | 'complete' | null = null
  let CLodopIsLocal = false
  let CreatedOKLodopObject: LODOPObject | null = null
  // 检查是否需要使用 CLODOP
  const checkNeedCLodop = (): boolean => {
    try {
      const ua = navigator.userAgent
      if (ua.match(/Windows\sPhone/i)) return true
      if (ua.match(/iPhone|iPod|iPad/i)) return true
      if (ua.match(/Android/i)) return true
      if (ua.match(/Edge\D?\d+/i)) return true

      const verTrident = ua.match(/Trident\D?\d+/i)
      const verIE = ua.match(/MSIE\D?\d+/i)
      let verOPR = ua.match(/OPR\D?\d+/i)
      let verFF = ua.match(/Firefox\D?\d+/i)
      const x64 = ua.match(/x64/i)
      if (!verTrident && !verIE && x64) return true
      else if (verFF) {
        verFF = verFF[0].match(/\d+/)
        if ((verFF && parseInt(verFF[0]) >= 41) || x64) return true
      } else if (verOPR) {
        verOPR = verOPR[0].match(/\d+/)
        if (verOPR && parseInt(verOPR[0]) >= 32) return true
      } else if (!verTrident && !verIE) {
        let verChrome = ua.match(/Chrome\D?\d+/i)
        if (verChrome) {
          verChrome = verChrome[0].match(/\d+/)
          if (verChrome && parseInt(verChrome[0]) >= 41) return true
        }
      }
      return false
    } catch (err) {
      return true
    }
  }
  const needCLodop = checkNeedCLodop()
  const showMsg = (msg: string) => {
    ElMessageBox.alert(msg, '提示', {
      dangerouslyUseHTMLString: true,
      closeOnClickModal: false,
      center: true,
    })
  }
  // 初始化 LODOP
  const initLodop = () => {
    if (CLodopJsState == 'loading' || CLodopJsState == 'complete') return
    CLodopJsState = 'loading'
    const head =
      document.head ||
      document.getElementsByTagName('head')[0] ||
      document.documentElement
    const JS1 = document.createElement('script')
    const JS2 = document.createElement('script')

    if (window.location.protocol == 'https:') {
      JS1.src = 'https://localhost.lodop.net:8443/CLodopfuncs.js'
      JS2.src = 'https://localhost.lodop.net:8444/CLodopfuncs.js'
    } else {
      JS1.src = 'http://localhost:8000/CLodopfuncs.js'
      JS2.src = 'http://localhost:18000/CLodopfuncs.js'
    }
    JS1.onload = JS2.onload = function () {
      CLodopJsState = 'complete'
    }
    JS1.onerror = JS2.onerror = function () {
      CLodopJsState = 'complete'
    }
    head.insertBefore(JS1, head.firstChild)
    head.insertBefore(JS2, head.firstChild)
    CLodopIsLocal = !!(JS1.src + JS2.src).match(/\/\/localho|\/\/127.0.0./i)
  }
  const getCLodop = (oOBJECT: LODOPObject | null, oEMBED: LODOPObject | null): LODOPObject | null => {
    const strFontTag = '<font _#_>打印控件'
    const strLodopInstall =
      strFontTag +
      '未安装!点击这里<a href=http://www.c-lodop.com/download/CLodop_Setup_for_Win64NT_6.623EN.zip target=_self>执行安装</a>'

    const strLodopUpdate =
      strFontTag +
      '需要升级!点击这里<a href=install_lodop32.exe target=_self>执行升级</a>'

    const strLodop64Install =
      strFontTag +
      '未安装!点击这里<a href=install_lodop64.exe target=_self>执行安装</a>'

    const strLodop64Update =
      strFontTag +
      '需要升级!点击这里<a href=install_lodop64.exe target=_self>执行升级</a>'

    const strCLodopInstallA =
      '<font >Web打印服务CLodop未安装启动，点击下列按钮执行安装<br><a href=http://www.c-lodop.com/download/lodop6.226_Clodop6.623.zip target=_self>安装32位</a> <a href=http://www.c-lodop.com/download/CLodop_Setup_for_Win64NT_6.623EN.zip target=_blank>安装64位</a><br>'

    const strCLodopInstallB =
      '（若此前已安装过，可点这里直接<a href=CLodop.protocol:setup target=_self>再次启动</a>）'

    const strCLodopUpdate =
      '<font >Web打印服务CLodop需升级!点击这里<a href=CLodop_Setup_for_Win32NT.exe target=_self>执行升级</a>'

    const strLodop7FontTag = '<font >Web打印服务Lodop7'
    const strLodop7HrefX86 =
      '点击这里<a href=https://www.c-lodop.com/download/Lodop7.105_Linux_X86_64_CN.deb.zip target=_self>下载安装</a>(下载后解压，点击lodop文件开始执行)'

    const strLodop7HrefARM =
      '点击这里<a href=https://www.c-lodop.com/download/Lodop7.105_Linux_ARM64_CN.deb.zip target=_self>下载安装</a>(下载后解压，点击lodop文件开始执行)'

    const strLodop7Install_X86 =
      strLodop7FontTag + '未安装启动，' + strLodop7HrefX86
    const strLodop7Install_ARM =
      strLodop7FontTag + '未安装启动，' + strLodop7HrefARM
    const strLodop7Update_X86 = strLodop7FontTag + '需升级，' + strLodop7HrefX86
    const strLodop7Update_ARM = strLodop7FontTag + '需升级，' + strLodop7HrefARM
    const strInstallOK = '，成功后请刷新本页面或重启浏览器。</font>'
    let LODOP: LODOPObject | null = null
    try {
      const isWinIE =
        /MSIE/i.test(navigator.userAgent) ||
        /Trident/i.test(navigator.userAgent)
      const isWinIE64 = isWinIE && /x64/i.test(navigator.userAgent)
      const isLinuxX86 =
        /Linux/i.test(navigator.userAgent) && /x86_64/i.test(navigator.userAgent)
      const isLinuxARM =
        /Linux/i.test(navigator.userAgent) && /aarch64/i.test(navigator.userAgent)

      if (needCLodop || isLinuxX86 || isLinuxARM) {
        try {
          LODOP = window.getCLodop()
        } catch (err) {
          console.error(err)
        }
        if (!LODOP && CLodopJsState !== 'complete') {
          if (CLodopJsState == 'loading')
            alert('网页还没下载完毕，请稍等一下再操作.')
          else alert('未曾加载Lodop主JS文件，请先调用loadCLodop过程.')
          return null
        }
        let strAlertMessage
        if (!LODOP) {
          if (isLinuxX86) strAlertMessage = strLodop7Install_X86
          else if (isLinuxARM) strAlertMessage = strLodop7Install_ARM
          else
            strAlertMessage =
              strCLodopInstallA + (CLodopIsLocal ? strCLodopInstallB : '')
          showMsg(strAlertMessage + strInstallOK)
          return null
        } else {
          if (isLinuxX86 && LODOP.CVERSION < '7.0.4.3')
            strAlertMessage = strLodop7Update_X86
          else if (isLinuxARM && LODOP.CVERSION < '7.0.4.3')
            strAlertMessage = strLodop7Update_ARM
          else if (window.CLODOP.CVERSION < '4.1.6.1')
            strAlertMessage = strCLodopUpdate

          if (strAlertMessage) showMsg(strAlertMessage + strInstallOK)
        }
      } else {
        //==如果页面有Lodop插件就直接使用,否则新建:==
        if (oOBJECT || oEMBED) {
          if (isWinIE) LODOP = oOBJECT
          else LODOP = oEMBED
        } else if (!CreatedOKLodopObject) {
          LODOP = document.createElement('object') as unknown as LODOPObject
          LODOP.setAttribute('width', '0')
          LODOP.setAttribute('height', '0')
          LODOP.setAttribute(
            'style',
            'position:absolute;left:0px;top:-100px;width:0px;height:0px;',
          )
          if (isWinIE)
            LODOP.setAttribute(
              'classid',
              'clsid:2105C259-1E0C-4534-8141-A753534CB4CA',
            )
          else LODOP.setAttribute('type', 'application/x-print-lodop')
          document.documentElement.appendChild(LODOP)
          CreatedOKLodopObject = LODOP
        } else LODOP = CreatedOKLodopObject
        //==Lodop插件未安装时提示下载地址:==
        if (!LODOP || !LODOP.VERSION) {
          showMsg(
            (isWinIE64 ? strLodop64Install : strLodopInstall) + strInstallOK,
          )

          return null
        }
        if (LODOP.VERSION < '6.2.2.6') {
          showMsg(
            (isWinIE64 ? strLodop64Update : strLodopUpdate) + strInstallOK,
          )
        }
      }

      if (location.host.indexOf('jomalls.com') !== -1) {
        LODOP.SET_LICENSES('', '90D9E6991E35971D8FC86B525F637C8A9F9', '', '')
      } else {
        LODOP.SET_LICENSES('', 'A9F23BF819622E36A8775E717685989E9FC', '', '')
      }
      return LODOP
    } catch (err) {
      alert('getLodop出错:' + err)
    }
    return null
  }
  onMounted(() => {
    initLodop()
  })
  return {
    getCLodop,
  }
}
