import Light from "light";
const QRCode = require("qrcode");
/**
 * 打印二维码
 */
function printQRCode(hashpath) {
    //93781 lighting工程不管是jsn项目还是纯h5项目都在控制台显示二维码
    let path = location.pathname;
    let env = __ENV__;

    if (path === "/"){
        path = "/index.html";
    }
    //H5永远打印！
    print(path);
    //plugins未配置时不报错
    if(env.plugins && env.plugins.toString().indexOf("miniapp")>-1 && (!Light.onlyFor || Light.onlyFor === "miniapp")) {
        if(path === "/index.html"){
            print("/app.miniapp.js");
        }else{
            print(path.replace(/\.html/ig, ".miniapp.js"));
        }
    }
    if(env.plugins && env.plugins.toString().indexOf("jsnative")>-1 && (!Light.onlyFor || Light.onlyFor === "jsn")){
        if(path === "/index.html"){
            print("/app.native.js");
        }else{
            print(path.replace(/\.html/ig, ".miniapp.js"));
        }
    }

    //128463当无法联网的环境下时，不再去请求平台接口来显示二维码
    function print(path) {
    //7721 工具编译成功后生成二维码的方式变更，不依赖于服务端
      let urlToScan = `http://${location.host}${path}${location.search}#${hashpath}`;
      QRCode.toDataURL(urlToScan, function (err, url) {
        console.log("LightView 扫码 URL: " + urlToScan);
        //91631 最新版本chrome浏览器的console无法打印二维码
        if(urlToScan.length>1000){
            console.error("当前url所含内容已超过二维码最大字符限制，参数过多时，建议通过其他方式传递")
        }else{
            if(urlToScan.length>500){
                console.warn("当前二维码所含内容过多，辨识度较低，参数过多时，建议通过其他方式传递")
            }
            console.log("%c ", "padding:75px 80px 75px;background:url(" + url + ") no-repeat;background-size:150px");
        }
      });
    }
}

/**
 * 计算节点的数量
 * @param node
 * @returns {number}
 */
function countNodes(node) {
    let count = 1;
    if(node.hasChildNodes()) {
        let cnodes = node.childNodes;
        for(let i=0; i<cnodes.length; i++) {
            count = count + countNodes(cnodes.item(i))
        }
    }
    return count;
}
/**
 * 计算节点的层数
 * @param node
 * @returns {number}
 */
function countLevels(node) {
    if(node.hasChildNodes()) {
        let cnodes = node.childNodes;

        let levels = [];
        cnodes.forEach(function (n) {
            levels.push(  1 + countLevels(n))
        })
        return Math.max(...levels)
    }else{
        return 1;
    }
}

Light.filter("route", function (from, to, next) {
    try {
        next();
        printQRCode(to.fullPath);

        //93785 lighting工程在展示当前视图的dom节点数量和最深的节点层次
        setTimeout(function () {
            let count = countNodes(document.body);
            let level = countLevels(document.body);
            console.log(`当前视图的DOM节点总数为：${count},最深的DOM节点层次为：${level}`);//
        },1000)
    }catch (e) {
        console.log(e)
    }
});

