// lodopUtils.js
var CreatedOKLodopObject, CLodopIsLocal, CLodopJsState;
let CLODOP = null;
let needCLodop = false;

// CLodop 云打印服务主机
const hostList = [
  'localhost:8000',
  'localhost:18000',
  'localhost:8001'
];

// 安装提示
const LODOP_INSTALL_GUIDE = {
  DOWNLOAD_URL: 'https://www.lodop.net/download.html',
  WIN_INSTALL_MSG: '请先下载和安装 Lodop 打印控件，\n 下载地址：https://www.lodop.net/download.html',
  OTHER_OS_MSG: '对不起，目前仅支持在 Windows 系统下进行打印操作'
};

//判断是否需要CLodop(那些不支持插件的浏览器)
function checkNeedCLodop() {
    try {
        var 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;

        var verTrident = ua.match(/Trident\D?\d+/i);
        var verIE = ua.match(/MSIE\D?\d+/i);
        var verOPR = ua.match(/OPR\D?\d+/i);
        var verFF = ua.match(/Firefox\D?\d+/i);
        var x64 = ua.match(/x64/i);
        if ((!verTrident) && (!verIE) && (x64))
            return true;
        else if (verFF) {
            verFF = verFF[0].match(/\d+/);
            if ((verFF[0] >= 41) || (x64))
                return true;
        } else if (verOPR) {
            verOPR = verOPR[0].match(/\d+/);
            if (verOPR[0] >= 32)
                return true;
        } else if ((!verTrident) && (!verIE)) {
            var verChrome = ua.match(/Chrome\D?\d+/i);
            if (verChrome) {
                verChrome = verChrome[0].match(/\d+/);
                if (verChrome[0] >= 41)
                    return true;
            }
        }
        return false;
    } catch (err) {
        return true;
    }
}

//加载引用CLodop的主JS,用双端口8000和18000(以防其中一个被占)
function loadCLodop() {
    if (CLodopJsState == "loading" || CLodopJsState == "complete") return;
    CLodopJsState = "loading";
    var head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
    var JS1 = document.createElement("script");
    var JS2 = document.createElement("script");
    JS1.src = "http://localhost:8000/CLodopfuncs.js?priority=1";
    JS2.src = "http://localhost:18000/CLodopfuncs.js";
    JS1.onload  = JS2.onload  = function()    {CLodopJsState = "complete";}
    // eslint-disable-next-line no-unused-vars
    JS1.onerror = JS2.onerror = function(evt) {CLodopJsState = "complete";}
    head.insertBefore(JS1, head.firstChild);
    head.insertBefore(JS2, head.firstChild);
    CLodopIsLocal = !!((JS1.src + JS2.src).match(/\/\/localho|\/\/127.0.0./i));
}

/**
 * 检查是否已安装 Lodop
 */
function checkLodopInstall() {
  try {
    const LODOP = window.getLodop();
    if (!LODOP && typeof LODOP !== 'object') return false;
    if (!LODOP.VERSION) return false;
    return true;
  } catch (err) {
    console.error('检查 Lodop 安装状态出错:', err);
    return false;
  }
}

/**
 * 显示安装提示信息
 */
function showInstallMessage(message) {
  if (window.$message) {
    window.$message.error(message);
  } else {
    alert(message);
  }
  return null;
}

/**
 * 获取LODOP对象主过程
 * @param {boolean} requirePrint 是否需要打印功能
 * @returns {object|null} LODOP对象或null
 */
function getLodop(oOBJECT, oEMBED, requirePrint = false) {
    let LODOP;
    try {
        // 判断是否需要 CLodop
        needCLodop = checkNeedCLodop();
        
        var ua = navigator.userAgent;
        var isIE = !!(ua.match(/MSIE/i)) || !!(ua.match(/Trident/i));
        
        if (needCLodop) {
            try {
                // eslint-disable-next-line no-undef
                LODOP = getCLodop();
                // eslint-disable-next-line no-empty
            } catch (err) {}
            
            if (!LODOP && CLodopJsState !== "complete") {
                if (CLodopJsState == "loading") {
                    if (requirePrint) {
                        return showInstallMessage("网页还没下载完毕，请稍等一下再操作.");
                    }
                    return null;
                } else {
                    loadCLodop();
                    if (requirePrint) {
                        return showInstallMessage(LODOP_INSTALL_GUIDE.WIN_INSTALL_MSG);
                    }
                    return null;
                }
            }
            
            if (!LODOP && requirePrint) {
                return showInstallMessage(LODOP_INSTALL_GUIDE.WIN_INSTALL_MSG);
            }
        } else {
            var is64IE = isIE && !!(ua.match(/x64/i));
            //如果页面有Lodop就直接使用,否则新建
            if (oOBJECT || oEMBED) {
                if (isIE)
                    LODOP = oOBJECT;
                else
                    LODOP = oEMBED;
            } else if (!CreatedOKLodopObject) {
                LODOP = document.createElement("object");
                LODOP.setAttribute("width", 0);
                LODOP.setAttribute("height", 0);
                LODOP.setAttribute("style", "position:absolute;left:0px;top:-100px;width:0px;height:0px;");
                if (isIE)
                    LODOP.setAttribute("classid", "clsid:2123C269-1E0C-4534-8141-A75355220B4CL");
                else
                    LODOP.setAttribute("type", "application/x-print-lodop");
                document.documentElement.appendChild(LODOP);
                CreatedOKLodopObject = LODOP;
            } else
                LODOP = CreatedOKLodopObject;
        }

        return LODOP;
    } catch (err) {
        console.error('获取打印对象出错:', err);
        if (requirePrint) {
            return showInstallMessage('初始化打印对象失败，请检查打印服务是否正常运行');
        }
        return null;
    }
}

/**
 * 检查打印服务状态
 */
function checkPrinterService() {
  const LODOP = getLodop(null, null, true);
  if (!LODOP) return false;
  
  try {
    const printers = LODOP.GET_PRINTER_LIST();
    return printers && printers.length > 0;
  } catch (err) {
    console.error('检查打印服务状态出错:', err);
    return false;
  }
}

/**
 * 获取默认打印机名称
 */
function getDefaultPrinter() {
  const LODOP = getLodop(null, null, true);
  if (!LODOP) return '';
  
  try {
    return LODOP.GET_DEFAULT_PRINTER_NAME();
  } catch (err) {
    console.error('获取默认打印机出错:', err);
    return '';
  }
}

/**
 * 获取打印机列表
 */
function getPrinterList() {
  const LODOP = getLodop(null, null, true);
  if (!LODOP) return [];
  
  try {
    return LODOP.GET_PRINTER_LIST();
  } catch (err) {
    console.error('获取打印机列表出错:', err);
    return [];
  }
}

export {
    getLodop,
    checkPrinterService,
    getDefaultPrinter,
    getPrinterList
};

