var pageSize = 10;
var RECOMMONDCODE = "remmondCode";
//cookie名称
var COOKIE_USERCODE = "CUSTCD";
var COOKIE_CUSTOMERCODE = 'CustomerCode'
var COOKIE_SESSIONID = "GACCESSTOKENKEY";
var COOKIE_REFRESH_TOKEN_HASH = "GREFRESHTOKENHASH";
var COOKIE_EXPIRATION_TIME = "GEXPIRATIONTIME";
var globalIndex = '';
var isNeedCheck = false
var tsvDataList = [];
var progressRate = '';
var signInWeChatObj = {};
var meviyItemImageUrlMap = {}
var cookieDomain = '.misumi.com.cn'
if (window.location.host.indexOf('misumi.com.cn') === -1) {
    cookieDomain = ''
}
var bodyHeight
var bodyWidth

// 判断是否为鸿蒙
function isHarmony() {
    if (navigator.userAgent.toLowerCase().indexOf("openharmony") > -1) {
        return true;
    } else {
        return false;
    }
}

// 听云报错兼容处理  使用代理监听 调用不存在的函数 ---start---
function safeFunctionWrapper(obj, functionName) {
    let originalFunction = obj[functionName];

    const functionHandler = {
        apply: function (target, thisArg, argumentsList) {
            if (typeof target === 'function') {
                return target.apply(thisArg, argumentsList);
            } else {
                console.log(`${functionName} 函数未定义，这里进行兼容处理。`);
            }
        }, set: function (target, prop, value) {
            if (prop === functionName) {
                console.log(`检测到尝试修改 ${functionName} 函数`);
                originalFunction = value;
                return true;
            }
            return false;
        }, get: function (target, prop) {
            if (prop === functionName) {
                return originalFunction;
            }
            return target[prop];
        }
    };

    obj[functionName] = new Proxy(originalFunction || function () {
    }, functionHandler);
}

safeFunctionWrapper(window, 'changeNetWork');
safeFunctionWrapper(window, 'onAndroidBack');
// 听云报错兼容处理  使用代理监听 调用不存在的函数 ---end---

addMeta('viewport', 'width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui,viewport-fit=cover')
//引入弹层插件
loadJs_(`${location.origin}/static/html/js/popup.js`, function () {
})

function addMeta(name, content) {//手动添加mate标签
    let meta = document.createElement('meta');
    meta.content = content;
    meta.name = name;
    document.getElementsByTagName('head')[0].appendChild(meta);
}

//全局监听 img 图片错误直接置空
document.addEventListener("error", function (e) {
    var elem = e.target;
    if (elem.tagName.toLowerCase() == 'img') {
        if (elem.src.indexOf('/image/upload/f_auto') > -1) {
            if (elem.src.match(/\/image\/upload\/(\S*\/)v1\//)) {
                var imgstr2 = elem.src.match(/\/image\/upload\/(\S*\/)v1\//)[1]
                elem.src = elem.src.replace(imgstr2, '')
            } else {
                try {
                    $(e.target).removeAttr('src')
                } catch (e) {
                    // error
                }
            }
        } else {
            try {
                $(e.target).removeAttr('src')
            } catch (e) {
                // error
            }
        }

    }
}, true);

//通用方法

function getValue(url) {
    //获取最后一个/的位置
    var site = url.lastIndexOf("\/");
    //截取最后一个/后的值
    return url.substring(site + 1, url.length);
}

//定义一个靠右的悬浮窗
function createDom() {
    let openAppHtml = '<img src="/static/html/images/openApp.png" alt="米思米闪购商城APP" style="width: 54px;height: 63px;display: block">'
    var btnApp = document.createElement('div')
    btnApp.id = "open-app";
    btnApp.style.position = "fixed";
    btnApp.style.width = '54px';
    btnApp.style.height = '63px';
    btnApp.style.top = '210px'
    btnApp.style.right = '8px'
    // btnApp.style.background="red";
    btnApp.style.zIndex = "111111"
    btnApp.innerHTML = openAppHtml;
    var count = window.location.href.split('/').length - 1;
    btnApp.onclick = function () {
        if (count == 3) {
            //埋点：诱导APP下载
            sensors.track("RecommendAPP", {source_page: "首页", button_name: "APP图标"});
            window.location.href = jumpUrl + "/static/html/page/downOropenApp.html"
            // window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.misumi_ec.cn.misumi_ec";
        } else {
            //埋点：诱导APP下载
            sensors.track("RecommendAPP", {source_page: "其他", button_name: "APP图标"});
            window.location.href = jumpUrl + "/static/html/page/downOropenApp.html"
            // window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.misumi_ec.cn.misumi_ec";
        }
    }
    return btnApp
}

function initDialog() {
    let demo = $("#open-app");
    let contW = $("#open-app").width();
    let contH = $("#open-app").height();
    let startX, startY, sX, sY, moveX, moveY, disX, disY;
    let winW = $(window).width();
    let winH = $(window).height();
    demo.on({
        touchstart: function (e) {
            startX = e.originalEvent.targetTouches[0].pageX;
            startY = e.originalEvent.targetTouches[0].pageY;
            sX = $(this).offset().left;
            sY = $(this).offset().top;
            leftX = startX - sX;
            rightX = winW - contW + leftX;
            // topY = startY - sY+70;
            // bottomY = winH - contH + topY - 120;
            //动态修改距离顶部和底部的距离(除去顶部和底部的距离)
            let topDom = $(".open-btn").height();
            let bottomDom = $(".bottomDivParent").height();
            topY = startY - sY + topDom;
            bottomY = winH - contH + topY - topDom - bottomDom;
        }, touchmove: function (e) {
            e.preventDefault();
            moveX = e.originalEvent.targetTouches[0].clientX;
            moveY = e.originalEvent.targetTouches[0].clientY;
            if (moveX < leftX) {
                moveX = leftX;
            }
            if (moveX > rightX) {
                moveX = rightX;
            }
            if (moveY < topY) {
                moveY = topY;
            }
            if (moveY > bottomY) {
                moveY = bottomY;
            }
            $(this).css({
                "left": moveX + sX - startX, "top": moveY + sY - startY,
            });
        }, touchend: function (e) {
            $(this).css({
                "left": "", "top": moveY + sY - startY, "right": "8px"
            });
        }
    });
}


function reigisterPerfectSc() {
    sensors.track('CompleteCompanyInfoView', {source_page: '注册成功页-完善企业信息'});
    sensors.track('FinishRegisterPageClick', {button_name: '完善企业信息'})
}

//获取url参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var search = decodeURIComponent(window.location.search);
    var r = search.substr(1).match(reg); //匹配目标参数
    if (r != null) return r[2];
    return null; //返回参数值
}

//解决微信支付地址
function getFromPage(url) {
    url = decodeURIComponent(url || location.href);
    var index = url.indexOf("?");
    return url.slice(index).replace(/(\?|&|\b)fromPage=/ig, "");
}

// 解析url中的参数
function parseUrlQuery(search) {
    search = (search || location.search || "").substr(1); // 拿到参数项，去掉问号
    search = decodeURIComponent(search);

    return search.split("&").filter(item => item).reduce((obj, item) => {

        var newItem = []
        var keyPostion = item.indexOf('=')
        newItem[0] = item.substring(0, keyPostion)
        newItem[1] = item.substring(keyPostion + 1)
        // let [key, value] = item.split("="); // 分隔为属性和值两部分
        let [key, value] = newItem // 分隔为属性和值两部分
        if (key in obj) { // 如果当前的key已经存在，那么这个值就要转变为数组
            if (Array.isArray(obj[key])) {
                obj[key].push(value)
            } else {
                obj[key] = [obj[key], value];
            }
        } else {
            obj[key] = value;
        }

        return obj;
    }, {})
}

function parseUrlQueryAfterDecode(search) {
    search = (search || location.search || "").substr(1); // 拿到参数项，去掉问号
    // search = decodeURIComponent(search);

    return search.split("&").filter(item => item).reduce((obj, item) => {

        var newItem = []
        var keyPostion = item.indexOf('=')
        newItem[0] = item.substring(0, keyPostion)
        newItem[1] = decodeURIComponent(item.substring(keyPostion + 1))
        // let [key, value] = item.split("="); // 分隔为属性和值两部分
        let [key, value] = newItem // 分隔为属性和值两部分
        if (key in obj) { // 如果当前的key已经存在，那么这个值就要转变为数组
            if (Array.isArray(obj[key])) {
                obj[key].push(value)
            } else {
                obj[key] = [obj[key], value];
            }
        } else {
            obj[key] = value;
        }
        return obj;
    }, {})
}

var jumpUrl = "";
var curWwwPath = window.document.location.href;

var pathName = window.document.location.pathname;

var pathNameParam = window.document.location.pathname + window.location.search;

var pos = curWwwPath.indexOf(pathName);


//   判断是否弹出未绑定手机号弹窗
function checkBindPhone(callback) {
    if (curWwwPath.toString().indexOf('settingPrivacyPolicy.html') != -1 || curWwwPath.toString().indexOf('loginNew.html') != -1 || curWwwPath.toString().indexOf('register.html') != -1 || curWwwPath.toString().indexOf('loginBind.html') != -1 || curWwwPath.toString().indexOf('myInfoSet.html') != -1 || curWwwPath.toString().indexOf('lpLogin.html') != -1) {

    } else {
        loadCss_('/static/html/js/dist/css/framework7.ios.css');
        loadCss_('/static/html/css/build/login.bundle.css');
        loadJs_('/static/html/js/dist/framework7.min.js', function () {
            loadJs_('/static/html/js/dist/f7Init.js', function () {
                loadJs_('/static/html/js/flexible.js', function () {
                    openNoBindPhoneModal(callback)
                })
            })

        })

    }
}

//悬浮窗代码 end
//获取主机地址，如： http://localhost:8083

var jumpUrl = curWwwPath.substring(0, pos);


/**
 * 获取upr页面的路径
 * @param htmlPath 页面路径，比如 cart.html
 * @param data 要传递的数据（这个是会放入url中的）
 * @returns {string|*}
 */
function getUprPagePath(htmlPath, data) {
    if (!htmlPath) return curWwwPath;
    var path = "/static/html/page/" + htmlPath;
    var query = "";
    if (data) {
        var params = Object.keys(data).reduce((paramsArr, key) => {
            var param = `${key}=${data[key]}`;
            paramsArr.push(param);
            return paramsArr;
        }, []);

        query = "?" + encodeURIComponent(params.join('&'));
    }

    return jumpUrl + path.replace(/\/\//g, "/") + query;
}

function getUprPagePathNew(htmlPath, data) {
    if (!htmlPath) return curWwwPath;
    var path = "/static/html/page/" + htmlPath;
    var query = "";
    if (data && JSON.stringify(data) != '{}') {
        var params = Object.keys(data).reduce((paramsArr, key) => {
            var param = `${key}=${encodeURIComponent(data[key])}`;
            paramsArr.push(param);
            return paramsArr;
        }, []);

        query = "?" + params.join('&');
    }
    return jumpUrl + path.replace(/\/\//g, "/") + query;
}

// 打开内部链接
function openUrl(url) {
    let href = url;
    if (isProduce) {
        if (url == "accountUpGrade") {
            href = "https://wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE";
        } else if (url == "accountBindGrade") {
            href = "https://wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE_WITH_EXISTED_CUSTOMER_CODE";
        }
    } else {
        if (url == "accountUpGrade") {
            href = "https://stg0-wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE";
        } else if (url == "accountBindGrade") {
            href = "https://stg0-wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE_WITH_EXISTED_CUSTOMER_CODE";
        }
    }

    // 这里由于safari,对window.open有限制，要先打开一个空白页, 再通过修改location.href实现
    let otherWindow = window.open("about:blank", "_blank");
    if (otherWindow && !otherWindow.closed) {
        otherWindow.location = href; // 确保 otherWindow 不是 null 并且没有被关闭
    }
}

/**
 * 跳转upr页面
 * @param htmlPath 页面路径，比如 cart.html
 * @param data 要传递的数据（这个是会放入url中的）
 * @param isOpen 是否打开新标签
 * @returns {Window|*}
 */
function jumpUprPage(htmlPath, data, isOpen) {
    var url = getUprPagePath(htmlPath, data);
    // 微信小程序环境 登录注册都跳转微信小程序页面
    if (isMiniProgram()) {
        let backUrl = encodeURIComponent((data && data.back_url) || window.location.href)
        let sourcePage = data ? data.sourcePage ? data.sourcePage : '' : ''
        if (htmlPath === 'loginNew.html') {
            jumpUprPage('vx_return.html?to=login&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
        if (htmlPath === 'register.html') {
            jumpUprPage('vx_return.html?to=MZRE&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
        if (htmlPath === 'enterpriseInfoPrefect.html') {
            jumpUprPage('vx_return.html?to=MZIE&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
        if (htmlPath === 'enterpriseJoin.html') {
            jumpUprPage('vx_return.html?to=MZJE&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
    }
    if (isOpen) {
        return window.open(url);
    } else {
        window.location.href = url;
    }
}

function jumpUprPageNew(htmlPath, data, isOpen) {
    var url = getUprPagePathNew(htmlPath, data);
    // 微信小程序环境 登录注册都跳转微信小程序页面
    if (isMiniProgram()) {
        let backUrl = encodeURIComponent((data && data.back_url) || window.location.href)
        let sourcePage = data ? data.sourcePage ? data.sourcePage : '' : ''
        if (htmlPath === 'loginNew.html') {
            jumpUprPage('vx_return.html?to=login&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
        if (htmlPath === 'register.html') {
            jumpUprPage('vx_return.html?to=MZRE&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
        if (htmlPath === 'enterpriseInfoPrefect.html') {
            jumpUprPage('vx_return.html?to=MZIE&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
        if (htmlPath === 'enterpriseJoin.html') {
            jumpUprPage('vx_return.html?to=MZJE&returnUrl=' + backUrl + '&sourcePage=' + sourcePage)
            return
        }
    }
    if (isOpen) {
        return window.open(url);
    } else {
        window.location.href = url;
    }
}

//验证是否是手机号
function isPoneAvailable(telNum) {
    var myreg = /^[1][3,4,6,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(telNum)) {
        return false;
    } else {
        return true;
    }
}

//判断是否为空
function isNull(str) {
    if (str == undefined || str == "undefined" || str == null || str == "null" || str == "" || JSON.stringify(str) == "{}") {
        if (parseInt(str) == 0) {
            return false;
        }
        return true;
    } else {
        return false;
    }
}

// 判断数据是否为null 或 undefined
function isUndefined(variable) {
    return variable === undefined || variable === null;
}

//商品列表计算折扣日
function showcampainEndDate(campainEndDate) {
    var reg = /^\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}$/;
    var regExp = new RegExp(reg);
    if (regExp.test(campainEndDate)) {
        return "SALE " + campainEndDate.substring(5) + "为止";
    }
    return "";
}

//提交表单验证
//验证规则checkList参考
// checkList=[
//     {iptValue:companyName,message:'请输入企业名称'},
//     {iptValue:Code,message:'请输入客户编码',},
//     {iptValue:Email,message:'请输入邮箱地址',regrule:/^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/,regMessage:'请输入正确的邮箱地址'},
//     {iptValue:Name,message:'请输入联系人姓名'}
// ]
function iptCheckFun(checkList) {
    let flag = null;
    try {
        checkList.forEach(function (item, index) {
            //跳出条件(如需加其他条件，继续加else if情况)
            if (!(item.iptValue.trim().replace(/\s/g, ""))) {   //为空情况  layer:"V"
                new MessageAlert({icon: "error", msg: item.message, delay: 3000})
                flag = false;
                throw new Error();
            } else if (item.regrule) {      //正则判断
                if (!item.regrule.test(item.iptValue)) {
                    if (item.layer == '1') {
                        new MessageAlert({icon: "error", msg: item.regMessage, delay: 3000, layer: 'V'})
                    } else {
                        new MessageAlert({icon: "error", msg: item.regMessage, delay: 3000,})
                    }
                    flag = false;
                    throw new Error();
                } else {
                    flag = true;
                }
            } else {
                flag = true
            }
        });
    } catch (e) {
    }
    return flag
}

//计算库存品
function calshipType(shipType) {
    var returnCalTrip = "";
    if (shipType == "1") {
        returnCalTrip = '库存品';
    } else if (shipType == "2") {
        returnCalTrip = '库存安排中';
    }
    return returnCalTrip;
}

//计算发货日
function caldaysToShip(daysToShip) {
    var returnCaldaysToShip = "-";
    if (isNull(daysToShip)) {
        return returnCaldaysToShip;
    }
    if (daysToShip == 0) {
        returnCaldaysToShip = "当天出货";
    } else if (daysToShip > 0 && daysToShip < 99) {
        returnCaldaysToShip = daysToShip + "天";
    } else if (daysToShip == 99) {
        returnCaldaysToShip = "每次进行询价";
    } else {
        returnCaldaysToShip = daysToShip + "天";
    }
    return returnCaldaysToShip;
}

//计算库存品及发货日
function calshipTypeAnddaysToShip(shipType, daysToShip) {
    var returnCalTrip = "";
    if (shipType == "1") {
        returnCalTrip = '库存品';
    } else if (shipType == "2") {
        returnCalTrip = '库存安排中';
    }
    if (daysToShip == 0 || daysToShip == "") {
        returnCalTrip += "当天出货";
    } else if (daysToShip == undefined) {
        returnCalTrip += "--";
    } else if (daysToShip > 0 && daysToShip < 99) {
        returnCalTrip += daysToShip + "天";
    } else if (daysToShip == 99) {
        returnCalTrip += "每次进行询价";
    } else {
        returnCalTrip += daysToShip + "天";
    }

    return returnCalTrip;
}

//初始化获取session中的userInfo信息
var userInfo = {};
if (!isNull(localStorage.getItem("userInfo"))) {
    userInfo = JSON.parse(localStorage.getItem("userInfo"));
}

//vona2接口拼接
function needString() {
    // var userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    return ''

}

function noNeedString() {
    // var userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    return ''

}

// 用户数据
var customerInfo = {};
if (!isNull(localStorage.getItem("customerInfo"))) {
    customerInfo = JSON.parse(localStorage.getItem("customerInfo"));
}

// session数据
var loginCheckSession = {};
if (!isNull(localStorage.getItem("loginCheckSession"))) {
    loginCheckSession = JSON.parse(localStorage.getItem("loginCheckSession"));
}
//loading 初始化
var loading_Class = function () {
    this.showLoading = function (noPanel) {
        if ($('body').find(".loadingParent").length == 0) {
            var loadingHtml = '';
            loadingHtml += '<div class="loadingParent">';
            if (noPanel) {

            } else {
                loadingHtml += '<div class="loading"></div>';
            }
            loadingHtml += '<div class="loadingDiv"><img style="width:75%" src="/static/html/images/imgsNew/loading.gif"/></div>';
            loadingHtml += '</div>';
            $("body").css("overflow", "hidden");
            $('body').append(loadingHtml);
        }
    }
    this.closeLoading = function () {
        $('body').find(".loadingParent").remove();
        $("body").css("overflow-x", "hidden");
        $("body").css("overflow-y", "auto");
    }
}

var loadingClass = new loading_Class();

function isPC() {
    return navigator.userAgent.match(/(iPhone|iPod|SymbianOS|Windows Phone|BlackBerry|webOS|iPad|Android|ios|openharmony)/i) ? false : true
}

$(function () {
    bodyHeight = $(document).height();
    //屏幕宽度
    bodyWidth = $(document).width();
    // 悬浮窗代码 start
    try {
        if (window.parent.document.getElementById('open-app') || pathName == "/static/html/page/downOropenApp.html" || sessionStorage.getItem('routeFlag') || parseUrlQueryAfterDecode().systemId == 'meviy_china' || parseUrlQueryAfterDecode().routeFlag == 'APP' || window.location.href.indexOf('college') > 0 || window.location.href.indexOf('upload.html') > 0 || window.location.href.indexOf('qrcode.html') > 0 || window.location.href.indexOf('www.') > 0 || (isWeiXin() && window.navigator.userAgent.toLowerCase().match(/miniProgram/i) == 'miniprogram')) {
        } else {
            if (isHarmony()) {
                return
            }
            document.querySelector('body').append(createDom())
        }
    } catch (err) {

    }
    //初始化app浮窗拖拽事件
    try {
        initDialog()

    } catch (err) {

    }
    $.removeCookie("GREFRESHTOKENHASH", {path: "/static/html/page", domain: cookieDomain})
    $.removeCookie("GACCESSTOKENKEY", {path: "/static/html/page", domain: cookieDomain})
    $.removeCookie("GREFRESHTOKENHASH", {path: "/static/html/page/activity", domain: cookieDomain})
    $.removeCookie("GACCESSTOKENKEY", {path: "/static/html/page/activity", domain: cookieDomain})
    // 对于非mobile环境下，跳转pc网站
    if (isPC() && !isWeiXin()) {
        // jsp页面跳转至对应页面
        var replaceUrl = ''
        var isJSP = window.location.href.indexOf('.html') === -1
        if (isProduce) {
            replaceUrl = isJSP ? window.location.href.replace(window.location.host, 'www.misumi.com.cn') : window.location.href
        } else {
            // replaceUrl = isJSP ? window.location.href.replace('localhost:8080', 'stg0-www.misumi.com.cn') : window.location.href
            replaceUrl = isJSP ? window.location.href.replace(window.location.host, 'stg0-www.misumi.com.cn') : window.location.href
        }
        if (isJSP) {
            window.location.replace(replaceUrl)
        }
    }
    if (window.location.href.indexOf("/html/page/case/") > -1) {
        getSpecialCase();
    }
    if (isCasePageAndSpecialCase(pathName) && isNull(userInfo.sessionId)) {
        // $("body").html("")
        localStorage.setItem('redirect', JSON.stringify({from: 'caseList', url: pathName}))
        // loginObj.showLoginDialog();
        judgeIsLogin();
        // window.location.href = '/static/html/page/case/caseList.html'
    }

    // 微信小程序环境重置history.go，解决重定向回到M站返回按钮不生效
    if (isMiniProgram()) {
        history.oldGo = history.go
        history.go = function (params) {
            history.oldGo(params)
            if (history.length === 1) {
                window.location.href = '/'
            }
        }
    }
})


function isCasePageAndSpecialCase(path) {
    //if this page is case block
    if (path.indexOf("/html/page/case/") <= 0) {
        return false;
    }
    var index = path.lastIndexOf("\/");
    var id = path.substring(index + 1, path.length).replace('.html', '');
    id = id.replace("No", "");
    //if this product can be show for common customer
    return JSON.parse(localStorage.getItem("caseList-sp"))[id] === 's';
}

function getSpecialCase() {
    $.ajaxSettings.async = false;
    $.getJSON("/static/html/page/case/case1/caseJson/caseList-sp.json", function (data) {
        localStorage.setItem("caseList-sp", JSON.stringify(data));
    });
    $.ajaxSettings.async = true;
}

// 为安卓/ios 接口调用生成随机的全局方法
function buildGlobalMethod(fn, methodName) {
    methodName = methodName || "method_" + (Math.random().toString(16).slice(2, 8)) + (Date.now());
    window[methodName] = function (code, result) {
        fn && fn(code, result);
        window[methodName] = null; // 释放函数引用
        delete window[methodName]; // 删除变量
    };
    return methodName;
}

// function caseOnLoad() {
//     if(isCasePageAndSpecialCase(pathName) && isNull(userInfo.sessionId)){
//         $("body").html("")
//         loginObj.showLoginDialog();
//     }
// }

// 判断数据是否为null 或 undefined
function isUndefined(variable) {
    return variable === undefined || variable === null;
}

//价格格式化 添加前委分隔符并保留2魏小数
function priceFormat(num) {
    if (isNull(num)) {
        if ("0" == num) {

        } else {
            return "-";
        }
    }
    if (num == "-") {
        return "-";
    }
    num = parseFloat(num);
    num = num.toFixed(2);
    num = num.toString().split("."); // 分隔小数点
    var arr = num[0].split("").reverse(); // 转换成字符数组并且倒序排列
    var res = [];
    for (var i = 0, len = arr.length; i < len; i++) {
        if (i % 3 === 0 && i !== 0) {
            res.push(","); // 添加分隔符
        }
        res.push(arr[i]);
    }
    res.reverse(); // 再次倒序成为正确的顺序
    if (num[1]) { // 如果有小数的话添加小数部分
        res = res.join("").concat("." + num[1]);
    } else {
        res = res.join("");
    }
    return res;
}


//打开客服
function onLineChat(pageName, btn, seriesCode, noLogin) {
    if (pageName == 'orderList') {
        sensors.track('CommonClick', {
            button_type: "下单领积分-非通常账号", button_name: "在线客服", current_page: '我的订单', content: '积分抽奖'
        });
    } else if (pageName == 'orderListkf') {
        sensors.track('CommonClick', {
            button_type: "无法参与抽奖弹窗", button_name: "在线客服", current_page: '我的订单', content: '积分抽奖'
        });
    } else {
        //埋点：首页点击(客服)
        sensors.track('PersonalPageClick', {
            button_type: '右上', button_name: '在线客服'
        });
    }

    if (!noLogin) {
        userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
        if (isNull(userInfo) || isNull(userInfo.sessionId)) {
            loginObj.showLoginDialog();
            return;
        }
    }

    if (!isNull(pageName)) {
        var sendBtn = "liveChat";
        if (!isNull(btn)) {
            sendBtn = btn;
        }
        sendGa("action", "", pageName, sendBtn);
    }
    var param = "?";
    if (!isNull(userInfo) && !isNull(userInfo.customerCode)) {
        param += "customCode=" + userInfo.customerCode;
    } else {
        param += "customCode=custCode";
    }
    if (param.length > 0) {
        param += "&";
    }
    if (!isNull(userInfo) && !isNull(userInfo.customerName)) {
        param += "customName=" + userInfo.customerName;
    } else {
        param += "customName=null";
    }
    if (param.length > 0) {
        param += "&";
    }
    if (!isNull(userInfo) && !isNull(userInfo.userName)) {
        param += "userName=" + userInfo.userName;
    } else {
        param += "userName=";
    }
    if (param.length > 0) {
        param += "&";
    }
    if (!isNull(userInfo) && !isNull(userInfo.userCode)) {
        param += "userCode=" + userInfo.userCode;
    } else {
        param += "userCode=";
    }
    //CN_NT-439 个人用户时传menu=4_1_3_6
    if (!isNull(userInfo) && isNull(userInfo.customerName)) {
        if (param.length > 0) {
            param += "&";
        }
        param += "menu=1_3_6";
//		param += "menu=4_1_3_6";
    }
    //CN_NT-439
    if (!isNull(seriesCode)) {
        if (param.length > 0) {
            param += "&";
        }
        param += "series_cd=" + seriesCode;
    }

    window.open(jumpUrl + "/static/html/page/onlineChat.html" + param);

    if (pageName == 'productInfo' || pageName == 'complexProductDetail' || pageName == 'notopenProductDetail') {
        productDetailButtonClick('底部栏', '客服');
    } else if (pageName == 'Topbar') {
        // 神策-HomePageClick-首页点击
        sensors.track("HomePageClick", {button_type: "顶部栏", button_name: "在线客服"});
    }
}

var Toast = function (config) {
    this.context = config.context == null ? $('body') : config.context; //上下文
    this.message = config.message; //显示内容
    this.time = config.time == null ? 3000 : config.time; //持续时间
    this.left = config.left; //距容器左边的距离
    this.top = config.top; //距容器上方的距离
    this.img = config.img == true ? (config.path ? config.path : '') + '../images/bindWechact/success.png' : '';
    this.init();
}
var msgEntity;
Toast.prototype = {
    //初始化显示的位置内容等
    init: function () {
        $("#toastMessage").remove();
        //设置消息体
        var msgDIV = new Array();
        msgDIV.push('<div id="toastMessage">');
        if (this.img) {
            msgDIV.push('<img src=' + this.img + '>')
        }
        msgDIV.push('<span>' + this.message + '</span>');
        msgDIV.push('</div>');
        msgEntity = $(msgDIV.join('')).appendTo(this.context);
        //设置消息样式
        var left = this.left == null ? this.context.width() / 2 - msgEntity.find('span').width() / 2 - 15 : this.left;
        var top = this.top == null ? '50%' : this.top;
        msgEntity.css({
            'border-radius': '4px',
            position: 'fixed',
            top: top,
            'z-index': '999999',
            left: left,
            'background-color': 'black',
            color: 'white',
            'font-size': '14px',
            padding: '5px 10px',
            margin: '5px'
        });
        msgEntity.find('img').css({
            'width': '20px', 'height': '20px', 'margin-bottom': '-4px', 'margin-right': '10px'
        })
        msgEntity.hide();
    }, //显示动画
    show: function () {
        msgEntity.fadeIn(this.time / 2);
        msgEntity.fadeOut(this.time / 2);
    }, showWechat: function () {
        msgEntity.show();
        msgEntity.fadeOut(this.time / 2);
    }

}

/**
 * 获取订单状态
 * @param {Object} itemList
 * @param {Object} payLineDate
 */
function getOrderState(itemList, payLineDate) {
    var orderStateHtml = "";
    var chinaStatus = ["a1", "a2", "a3", "z", "1", "3", "4", "x", "f"]
    var orderState = "-";
    setOrderState:
        for (var i = 0; i < chinaStatus.length; i++) {
            for (var j = 0; j < itemList.length; j++) {
                if (!isNull(itemList[j].status) && chinaStatus[i] == itemList[j].status) {
                    if (chinaStatus[i] == "1") {
                        orderState = "处理中";
                    } else if (chinaStatus[i] == "3") {
                        orderState = "订购完成";
                    } else if (chinaStatus[i] == "4") {
                        orderState = "发货完成";
                    } else if (chinaStatus[i] == "f") {
                        orderState = "失败";
                    } else if (chinaStatus[i] == "z") {
                        orderState = "确认中";
                    } else if (chinaStatus[i] == "x") {
                        orderState = "已取消";
                        //					} else if (chinaStatus[i] == "1") {
                        //						orderState = "处理中";
                        //					} else if (chinaStatus[i] == "w") {
                        //						orderState = "等待付款";
                    } else if (chinaStatus[i] == "a1") {
                        orderState = "等待承认";
                    } else if (chinaStatus[i] == "a2") {
                        orderState = "否认";
                    } else if (chinaStatus[i] == "a3") {
                        orderState = "退回";
                    }
                    break setOrderState;
                }
            }
        }
    var isAllw = true;
    for (var j = 0; j < itemList.length; j++) {
        if (itemList[j].status != "w") {
            isAllw = false;
            break;
        }
    }
    if (isAllw) {
        if (!isNull(payLineDate) && (new Date(payLineDate).getTime() > new Date().getTime())) {
            orderState = "等待付款";
        } else {
            orderState = "超过有效期"
        }

    }
    if (orderState != "-") {
        return orderState;
    }
    return orderState;
}

/**
 * karte 页面信息
 * @param {Object} screenName 屏幕名称
 * @param {Object} titleName 页面标题
 */
function sendKarte(screenName, titleName) {
    // var object = {
    //     screen: screenName,
    //     title: titleName
    // };
    // var option = {
    //     reset_past_actions: true,
    //     close_actions: true
    // };
    // tracker.view(object, option);
}


/**
 * karte 用户信息
 */
function karteTrackerUser(iusercode, icustomerCode) {
    // var object = {
    //     user_id: iusercode,
    //     toku_cd: icustomerCode
    // }
    // tracker.user(object);
}

/**
 * karte 事件 购买
 * @param {Object} date            购买时间
 * @param {Object} amount        实际金额
 * @param {Object} unitPrice    参考价格
 * @param {Object} totalCount    数量
 * @param {Object} categoryCode    分类编号
 * @param {Object} seriesCode    商品编号
 * @param {Object} brandCode    品牌编号
 */
function karteTrackerEventBuy(date) {
    // var orderDate = [];
    // for (var i = 0; i < date.orderItemList.length; i++) {
    //     orderDate.push({
    //         buyDate: date.orderDateTime,
    //         amount: date.orderItemList[i].totalPrice,
    //         unitPrice: date.orderItemList[i].standardUnitPrice,
    //         totalCount: date.orderItemList[i].quantity,
    //         seriesCode: date.orderItemList[i].seriesCode,
    //         brandCode: date.orderItemList[i].brandCode
    //     });
    // }
    // var object = {
    //     orderSeriesList: orderDate
    // };

    // tracker.track('buy', object);
}

/**
 * karte 事件 浏览详情页
 * @param {Object} icategoryName    分类名称
 * @param {Object} icategoryCode    分类编号
 * @param {Object} iseriesName        商品名称
 * @param {Object} iseriesCode        商品编号
 * @param {Object} ibrandName        品牌名称
 * @param {Object} ibrandCode        品牌编号
 * @param {Object} iunitPrice        参考价格
 */
function karteTrackerEventVisitDetail(icategoryName, icategoryCode, iseriesName, iseriesCode, ibrandName, ibrandCode, iunitPrice) {
    // var object = {
    //     categoryName: icategoryName,
    //     categoryCode: icategoryCode,
    //     seriesName: iseriesName,
    //     seriesCode: iseriesCode,
    //     brandName: ibrandName,
    //     brandCode: ibrandCode,
    //     unitPrice: iunitPrice
    // };
    // tracker.track('visit_detail', object);
}

/**
 * karte 事件 检索结果
 * @param {Object} ikeyWord        检索关键词
 * @param {Object} iseriesCnt    检索结果产品数量
 * @param {Object} itotalCnt    检索结果产品+分类+品牌总数量
 */
function karteTrackerEventKwSearch(ikeyWord, iseriesCnt, itotalCnt) {
    // var object = {
    //     keyWord: ikeyWord,
    //     seriesCnt: iseriesCnt,
    //     totalCnt: itotalCnt
    // };
    // tracker.track('kwsearch', object);
}

/**
 * karte 事件 浏览购物车
 * @param {Object} icartItems    购物车列表
 * @param {Object} revenue        总价
 */
function karteTrackerVisitCart(icartItems, irevenue) {
    // var cartItemsArray = [];
    // for (var i = 0; i < icartItems.length; i++) {
    //     cartItemsArray.push({
    //         seriesName: icartItems[i].productName,
    //         seriesCode: icartItems[i].seriesCode,
    //         brandName: icartItems[i].brandName,
    //         brandCode: icartItems[i].brandCode,
    //         itemPrice: icartItems[i].unitPrice,
    //         itemPriceSt: icartItems[i].totalPrice,
    //         itemNum: icartItems[i].quantity,
    //         shipmentDate: icartItems[i].daysToShip
    //     });
    // }
    // var object = {
    //     count: icartItems.length,
    //     revenue: irevenue,
    //     cartItems: cartItemsArray
    // };
    // tracker.track('visit_cart', object);
}

/**
 * karte 事件 浏览收藏夹
 * @param {Object} ipartItems    我的零件表列表
 */
function karteTrackerVisitPart(ipartItems) {
    // var partItemsArray = [];
    // for (var i = 0; i < ipartItems.length; i++) {
    //     partItemsArray.push({
    //         seriesName: ipartItems[i].productName,
    //         seriesCode: ipartItems[i].seriesCode,
    //         brandName: ipartItems[i].brandName,
    //         brandCode: ipartItems[i].brandCode,
    //         itemPrice: ipartItems[i].unitPrice,
    //         itemNum: ipartItems[i].quantity,
    //         partNumber: ipartItems[i].partNumber,
    //         registerDateTime: ipartItems[i].registerDateTime
    //     });
    // }

    // var object = {
    //     count: ipartItems.length,
    //     partItems: partItemsArray
    // };
    // tracker.track('visit_parts', object);
}

/**
 * karte 事件 选型完成点击确定
 */
function karteTrackerCompPnum() {
    // tracker.track('comp_pnum');
}

/**
 * karte 事件 加入收藏夹
 */
function karteTrackerAddParts() {
    // tracker.track('add_parts');
}

/**
 * karte 事件 加入购物车
 */
function karteTrackerAddCart() {
    // tracker.track('add_cart');
}

function openShareWechatPopup() {
    if ($('body').find("#shareWechatIn").length == 0) {
        var popupHtml = '<div id="shareWechatIn" style="z-index: 9999;" class="popup">'
        popupHtml += '<div style="height: 16rem;display: flex">'
        popupHtml += '<div style="font-size: 16px;font-family: PingFangSC-Regular, PingFang SC;color: #FFFFFF;margin-top: 3.1rem;margin-left: 2.3rem">请点击右上角，分享好友或朋友圈</div>'
        popupHtml += '<img style="width: 5rem;height: 4rem;margin-top: 0.56rem;padding-left: 0.44rem" src="/static/html/images/productEvaluation/weixin.png" alt="">'
        popupHtml += '</div>'
        popupHtml += '</div>'
        $('body').append(popupHtml);
    }

    //点击遮罩关闭弹框
    // $("#shareWechatIn").on('click', function (e) {
    //     console.log(e.target.className)
    //     if (e.target.className == 'popup active-state' || e.target.className == 'popup') {
    //         $("#shareWechatIn").fadeOut(0)
    //     }
    // })

    $("#shareWechatIn").fadeIn(0)
}

function openShareNoWechatPopup() {
    if ($('body').find("#shareWechatOut").length == 0) {
        var popupHtml = '<div id="shareWechatOut" style="z-index: 9999;" class="popup">'
        popupHtml += '<div style="display: flex;justify-content: center">'
        popupHtml += '<div style="height: 70px;bottom: 0;position: absolute">'
        popupHtml += '<div style="height: 58px;font-size: 16px;color: #333333;padding:12px 23px;background-image: url(/static/html/images/productEvaluation/normal.png);background-repeat: no-repeat;">请使用浏览器下方分享功能</div>'
        popupHtml += '</div>'
        popupHtml += '</div>'
        popupHtml += '</div>'
        $('body').append(popupHtml);
    }

    //点击遮罩关闭弹框
    // $("#shareWechatOut").on('click', function (e) {
    //     console.log(e.target.className)
    //     if (e.target.className == 'popup active-state' || e.target.className == 'popup') {
    //         $("#shareWechatOut").fadeOut(0)
    //     }
    // })

    $("#shareWechatOut").fadeIn(0)
}

// 小程序分享弹出框
function openShareAppletPopup() {
    if ($('body').find("#shareAppletIn").length == 0) {
        var popupHtml = '<div id="shareAppletIn" style="z-index: 20001;width: 100%;height: 100%;position: absolute;top: 0;left: 0;display: none;background: rgba(0,0,0,.8);" class="popup">'
        popupHtml += '<div style="height: 100%;display: flex">'
        popupHtml += '<div style="font-size: 14px;font-family: PingFangSC-Regular, PingFang SC;color: #FFFFFF;position: absolute;left: 0.9rem;top: 5.36rem;">请点击右上角，分享好友或朋友圈</div>'
        popupHtml += '<img style="position: absolute;right: 5rem;width: 5.7rem;top: 1.8rem;" src="/static/html/images/productEvaluation/weixin.png" alt="">'
        popupHtml += '</div>'
        popupHtml += '</div>'
        $('body').append(popupHtml);
    }

    //点击遮罩关闭弹框
    $("#shareAppletIn").on('click', function (e) {
        if (e.currentTarget.className == 'popup' || e.currentTarget.className == 'popup active-state') {
            $("#shareAppletIn").fadeOut(0)
        }
    })

    $("#shareAppletIn").fadeIn(0)
}

/**
 * 分享弹框
 * @param content 复制内容
 */
function openSharePopup(content, key) {
    if ($('body').find("#toshareInfoEvluation").length == 0) {
        var popupHtml = '<div id="toshareInfoEvluation" style="z-index: 9999;" class="popup">'
        popupHtml += '<div class="share_footer" style="height: 16.5rem">'

        popupHtml += '<div class="share_c">'
        popupHtml += '<p class="share_text1" style="margin-top: 1.42rem;line-height: 1.2rem;font-size: 14px;">分享到</p>'
        popupHtml += '<ul class="icons share-tree" style="margin-top: 1.4rem;margin-bottom: 1.4rem">'
        if (!isHarmony()) {
            popupHtml += '<li style="width: 4.44rem;line-height: 1.2rem;font-size: 14px;">'
            popupHtml += '<img style="width: 4rem;height: 4rem" src="/static/html/images/signIn/sign_share_bgc3.png" alt="">'
            popupHtml += '<p>微信</p>'
            popupHtml += '</li>'
            popupHtml += '<li style="width: 4.44rem;line-height: 1.2rem;font-size: 14px;">'
            popupHtml += '<img style="width: 4rem;height: 4rem" src="/static/html/images/signIn/sign_share_bgc5.png" alt="">'
            popupHtml += '<p>朋友圈</p>'
            popupHtml += '</li>'
            popupHtml += '<li style = "width: 4.44rem;line-height: 1.2rem;font-size: 14px;" >'
            popupHtml += '<img style="width: 4rem;height: 4rem" src="/static/html/images/signIn/sign_share_bgc2.png" alt="">'
            popupHtml += '<p>QQ</p>'
            popupHtml += '</li>'
        }
        popupHtml += '<li style="width: 4.44rem;line-height: 1.2rem;font-size: 14px;" class="copy-url">'
        popupHtml += '<img style="width: 4rem;height: 4rem" src="/static/html/images/signIn/sign_share_bgc6.png" alt="">'
        popupHtml += '<p>复制链接</p>'
        popupHtml += '<p class="copy-url-content hide">' + content + '</p>'
        popupHtml += '</li>'
        popupHtml += '</ul>'
        popupHtml += '<p class="share_text2 cancel-share" style="line-height:1.22rem;font-size: 16px;">取消</p>'
        popupHtml += '</div>'
        popupHtml += '</div>'
        popupHtml += '</div>'
        $('body').append(popupHtml)
    }
    //点击遮罩关闭弹框
    $("#toshareInfoEvluation").on('click', function (e) {
        if (e.target.className == 'popup' || e.target.className == 'popup active-state') {
            $("#toshareInfoEvluation").fadeOut(0)
        }
    })

    $(".cancel-share").unbind("click").click(function () {
        sensors.track("ReviewSharePopupClick", {button_name: "取消"});
        $("#toshareInfoEvluation").fadeOut(0)

    })


    //右上角分享微信
    $(".share-tree").children("li").unbind("click").click(function () {
        var index = $(this).index();
        $("#toshareInfoEvluation").fadeOut(0)
        if (isHarmony()) {
            // 鸿蒙隐藏了前三个
            if (index == 0) {
                sensors.track("ReviewSharePopupClick", {button_name: "复制链接"});
                if (isNull(content)) {
                    AlertDialog.alert("复制失败!");
                } else {
                    copyContent();
                }
            }
        } else {
            if (index == 0 || index == 1 || index == 2) {
                if (index == 0) {
                    sensors.track("ReviewSharePopupClick", {button_name: "微信"});
                } else if (index == 1) {
                    sensors.track("ReviewSharePopupClick", {button_name: "朋友圈"});
                } else {
                    sensors.track("ReviewSharePopupClick", {button_name: "QQ"});
                }
                window.location.href = "/vona2/review/share/" + key + "/?isopenPopup = 1/";
                // if(isWeiXin()){
                //     openShareWechatPopup()
                // }else{
                //     openShareNoWechatPopup();
                // }
            } else if (index == 3) {
                sensors.track("ReviewSharePopupClick", {button_name: "复制链接"});
                if (isNull(content)) {
                    AlertDialog.alert("复制失败!");
                } else {
                    copyContent();
                }
            }
        }

    })
    $("#toshareInfoEvluation").fadeIn(0)


}

function isInShare() {
    if (isWeiXin()) {
        openShareWechatPopup()
    } else {
        openShareNoWechatPopup();
    }
}


async function ShareInfoWechatAjax(selectedReviewId, selectedSeriesName, selectedSeriesImg) {
    var createUrlParam = {
        sessionId: userInfo.sessionId, reviewId: selectedReviewId
    }
    var shareEvaluationUrl = "";
    var resp = await infoDetailCreateShareUrl(createUrlParam);
    if (resp.returnFlg == 0) {
        if (isProduce) {
            shareEvaluationUrl = "https://m.misumi.com.cn/vona2/review/share/" + resp.reviewShareKey + "/"
        } else {
            shareEvaluationUrl = "https://stg-m.misumi.com.cn/vona2/review/share/" + resp.reviewShareKey + "/"
        }
        if (sessionStorage.getItem('routeFlag')) {
            postMessageToMiniProgramShare(selectedSeriesName, `${location.origin}/vona2/review/share/${resp.reviewShareKey}/`, selectedSeriesImg, '')
            openShareAppletPopup()
        } else {
            openSharePopup(shareEvaluationUrl, resp.reviewShareKey);
        }


    } else {
        AlertDialog.alert(resp.returnMSG);
    }


    //  copyContent();
}


async function infoDetailCreateShareUrl(request) {
    return new Promise((resolve, reject) => {
        var param = request || {};
        var action = WebUtils.evaluationAPI(getReviewShareKey);

        WebUtils.ajaxApiHostGetSubmit(action, param, function (result) { //success
            resolve(result);
        }, function (error) { //error
            reject(error);
        }, function (XHR, TS) { //complete

        });

    });
}

function copyContent() {
    var Itemclipboard = new ClipboardJS(".copy-url", {
        text: function () {
            var content = $(".copy-url-content").html();
            return content;
        }
    });
    Itemclipboard.on("success", function (e) {
        AlertDialog.alert("复制成功!");
    });
    Itemclipboard.on("error", function (e) {
        AlertDialog.alert("复制失败!");
    });

}

/**
 * 对话框封装
 */
var AlertDialog = function () {


    /**
     * 只打印msg
     */
    this.erroralert = function (msg, btnStr, closeBack, titleShow, arrivalDate) {
        if ($('body').find("#iosDialog4").length == 0) {
            var dHtml = '<div class="js_dialog" id="iosDialog4" style="display: none;width: 90%;margin-left: 0;left: 5%;z-index:13500;opacity: 1;position: absolute;top: 30%;">'
            dHtml += '<div class="modal-inner" style="position: relative;background: rgba(255, 255, 255, 0.95);border-radius: 0.7rem;padding: 1.6rem 1rem 1.4rem 1rem"><div class="modal-text" style="display: flex;flex-direction: column;align-items: center;">'
            if (titleShow) {
                dHtml += '<div style="font-size:18px;font-weight: bold;margin-top:10px;margin-bottom:10px;">温馨提示</div>'
            } else {
                dHtml += '<img class="icon" style="width: 2.8rem;height: 2.8rem" src="/static/html/images/returnImg/img20210511_3.png">'
            }
            dHtml += '<div style="margin-top: 0.8rem;font-size: 1.1rem;color: #333333;text-align:center" class="sub-title">' + (isNull(msg) ? '' : msg) + '</div>' + '<div class="ev_dialog__btn_primary" style="width:9rem;height: 2.72rem;font-size: 1.1rem;color: #333333;display: flex;align-items: center;justify-content: center;background: #ffcc00;border-radius: 1.45rem;margin-top: 1.58rem;" id="commit-modal-btn">我知道了</div></div></div></div>'
            dHtml += '</div>'
            dHtml += '<div id="btm-black" class="modal-overlay modal-overlay-visible" style="position: absolute;visibility: visible;opacity: 1;z-index:9999;background: rgba(0, 0, 0, .6);width: 100%;height: 100%;"></div>'
            $('body').append(dHtml);
        } else {
            $("#btm-black").show();
            $("#iosDialog4 .sub-title").html(isNull(msg) ? '提示信息' : msg);
            $("#iosDialog4 .ev-dialog__btn_primary").html(isNull(btnStr) ? '确定' : btnStr);
        }

        $("#iosDialog4").fadeIn(0);
        // if(arrivalDate){
        //     $('#iosDialog4').find('.sub-title').css({'text-align': 'left','font-size':'14px'})
        // }else{
        //     $('#iosDialog4').find('.sub-title').css({'text-align': 'center','font-size':'14px'})
        // }

        $("#iosDialog4").unbind().click(function (e) {
            if (e.target.className == "ev_dialog__btn_primary active-state" || e.target.className == "ev_dialog__btn_primary") {
                $("#iosDialog4").remove();
                $("#btm-black").remove();
                if (closeBack != undefined) {
                    try {
                        closeBack();
                    } catch (e) {
                        //TODO handle the exception
                    }
                }
            }
        });


        // $("#iosDialog4 .ev-dialog__btn_primary").unbind().click(function () {
        //     console.log("点击底部按钮")
        //     $("#iosDialog4").fadeOut(0);
        //     if (closeBack != undefined) {
        //         try {
        //             closeBack();
        //         } catch (e) {
        //             //TODO handle the exception
        //         }
        //     }
        // });
    }
    /**
     * 只打印msg
     */
    this.alert = function (msg, title, btnStr, closeBack) {
        if ($('body').find("#iosDialog2").length == 0) {
            var dHtml = '<div class="js_dialog" id="iosDialog2" style="display: none;">' + '<div class="weui-mask"></div>' + '<div class="weui-dialog">' + '<div class="weui-dialog__hd"><strong class="weui-dialog__title">' + (isNull(title) ? '' : title) + '</strong></div>' + '<div class="weui-dialog__bd">' + (isNull(msg) ? '提示信息' : msg) + '</div>' + '<div class="weui-dialog__ft">' + '<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary">' + (isNull(btnStr) ? '确定' : btnStr) + '</a>' + '</div>' + '</div>' + '</div>';
            $('body').append(dHtml);
        } else {
            $("#iosDialog2 .weui-dialog__title").html(isNull(title) ? '' : title);
            $("#iosDialog2 .weui-dialog__bd").html(isNull(msg) ? '提示信息' : msg);
            $("#iosDialog2 .weui-dialog__btn_primary").html(isNull(btnStr) ? '确定' : btnStr);
        }
        $("#iosDialog2 .weui-dialog__btn_primary").unbind().click(function () {
            $("#iosDialog2").fadeOut(0);
            if (closeBack != undefined) {
                try {
                    closeBack();
                } catch (e) {
                    //TODO handle the exception
                }
            }
        });

        $("#iosDialog2").fadeIn(0);
    }
    /**
     * @param {Object} msg
     * @param {Object} title
     * @param {Object} okBtn
     * @param {Object} noBtn
     * @param {Object} okBack
     * @param {Object} noBack
     */
    this.confirm = function (msg, title, okBtn, noBtn, okBack, noBack, autoCloses) {
        if ($('body').find("#iosDialog1").length == 0) {
            var dHtml = '<div class="js_dialog" id="iosDialog1" style="display: none;">' + '<div class="weui-mask"></div>' + '<div class="weui-dialog">' + '<div class="weui-dialog__hd"><strong class="weui-dialog__title">' + (isNull(title) ? '' : title) + '</strong></div>' + '<div class="weui-dialog__bd">' + (isNull(msg) ? '提示信息' : msg) + '</div>' + '<div class="weui-dialog__ft">' + '<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default">' + (isNull(noBtn) ? '取消' : noBtn) + '</a>' + '<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary">' + (isNull(okBtn) ? '确定' : okBtn) + '</a>' + '</div>' + '</div>' + '</div>';
            $('body').append(dHtml);
        } else {
            $("#iosDialog1 .weui-dialog__title").html(isNull(title) ? '' : title);
            $("#iosDialog1 .weui-dialog__bd").html(isNull(msg) ? '提示信息' : msg);
            $("#iosDialog1 .weui-dialog__btn_default").html(isNull(noBtn) ? '取消' : noBtn);
            $("#iosDialog1 .weui-dialog__btn_primary").html(isNull(okBtn) ? '确定' : okBtn);
        }
        $("#iosDialog1 .weui-dialog__btn_default").unbind().click(function () {
            $("#iosDialog1").fadeOut(0);
            if (noBack != undefined) {
                try {
                    noBack();
                } catch (e) {
                    //TODO handle the exception
                }
            }
        });
        $("#iosDialog1 .weui-dialog__btn_primary").unbind().click(function () {
            $("#iosDialog1").fadeOut(0);
            if (okBack != undefined) {
                try {
                    okBack();
                } catch (e) {
                    //TODO handle the exception
                }
            }
        });

        if (autoCloses) {
            $("#iosDialog1 .weui-mask").unbind("click").click(function () {
                $("#iosDialog1").fadeOut(0);
            });
        }

        $("#iosDialog1").fadeIn(0);
    }

    this.ask = function (msg, title, okBtn, noBtn, askBtn, okBack, noBack, askBack) {
        if ($('body').find("#iosDialog3").length == 0) {
            var dHtml = '<div class="js_dialog" id="iosDialog3" style="display: none;">' + '<div class="weui-mask"></div>' + '<div class="weui-dialog">' + '<div class="weui-dialog__hd"><strong class="weui-dialog__title">' + (isNull(title) ? '' : title) + '</strong></div>' + '<div class="weui-dialog__bd">' + (isNull(msg) ? '提示信息' : msg) + '</div>' + '<div class="weui-dialog__ft">' + '<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_default">' + (isNull(noBtn) ? '取消' : noBtn) + '</a>' + '<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_notask">' + (isNull(noBtn) ? '不再显示' : askBtn) + '</a>' + '<a href="javascript:;" class="weui-dialog__btn weui-dialog__btn_primary">' + (isNull(okBtn) ? '确定' : okBtn) + '</a>' + '</div>' + '</div>' + '</div>';
            $('body').append(dHtml);
        } else {
            $("#iosDialog3 .weui-dialog__title").html(isNull(title) ? '' : title);
            $("#iosDialog3 .weui-dialog__bd").html(isNull(msg) ? '提示信息' : msg);
            $("#iosDialog3 .weui-dialog__btn_default").html(isNull(noBtn) ? '取消' : noBtn);
            $("#iosDialog3 .weui-dialog__btn_primary").html(isNull(askBtn) ? '不再显示' : askBtn);
            $("#iosDialog3 .weui-dialog__btn_primary").html(isNull(okBtn) ? '确定' : okBtn);
        }
        $("#iosDialog3 .weui-dialog__btn_default").unbind().click(function () {
            $("#iosDialog3").fadeOut(0);
            if (noBack != undefined) {
                try {
                    noBack();
                } catch (e) {
                    //TODO handle the exception
                }
            }
        });
        $("#iosDialog3 .weui-dialog__btn_notask").unbind().click(function () {
            $("#iosDialog3").fadeOut(0);
            if (askBack != undefined) {
                try {
                    askBack();
                } catch (e) {
                    //TODO handle the exception
                }
            }
        });
        $("#iosDialog3 .weui-dialog__btn_primary").unbind().click(function () {
            $("#iosDialog3").fadeOut(0);
            if (okBack != undefined) {
                try {
                    okBack();
                } catch (e) {
                    //TODO handle the exception
                }
            }
        });
        $("#iosDialog3").fadeIn(0);
    }
}

var AlertDialog = new AlertDialog();

//随机数
function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function getGuid() {
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function isPoneAvailable(telNum) {
    var myreg = /^[1][3,4,6,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(telNum)) {
        return false;
    } else {
        return true;
    }
}

//保存cookie
//参数：cookie名,cookie值,有效时长(单位：天)
function saveCookie(cookieName, cookieValue, cookieDates, domain) {
//	var d = new Date();
//	d.setDate(d.getDate()+cookieDates*24*3600*1000);
//	document.cookie = cookieName+"="+cookieValue+";expires="+d.toGMTString()+";path=/";;
    $.cookie(cookieName, cookieValue ? cookieValue : '', {expires: cookieDates, path: '/', domain: domain});
}

function saveAllCookie() {
    saveCookie(COOKIE_USERCODE, userInfo.userCode, 365, cookieDomain);
    saveCookie(COOKIE_CUSTOMERCODE, userInfo.customerCode, 365, cookieDomain);
    saveCookie(COOKIE_SESSIONID, userInfo.sessionId, 365, cookieDomain);
    saveCookie(COOKIE_REFRESH_TOKEN_HASH, userInfo.refreshTokenHash, 365, cookieDomain);
    saveCookie(COOKIE_EXPIRATION_TIME, userInfo.checkUserInfo.expirationTime, 365, cookieDomain);
}

function removeAllCookie() {
    removeCookie(COOKIE_USERCODE);
    removeCookie(COOKIE_CUSTOMERCODE);
    removeCookie(COOKIE_SESSIONID);
    removeCookie(COOKIE_REFRESH_TOKEN_HASH);
    removeCookie(COOKIE_EXPIRATION_TIME);
}

/**
 * @param {Object} cookieName
 * 获取cookie
 */
function getCookie(cookieName) {
//	var cookieStr = unescape(document.cookie);
//	var arr = cookieStr.split("; ");
//	var cookieValue = "";
//	for(var i=0;i<arr.length;i++){
//		var temp = arr[i].split("=");
//		if(temp[0]==cookieName){
//			cookieValue = temp[1];
//			break;
//		}
//	}
    return $.cookie(cookieName);
}

/**
 * @param {Object} cookieName
 * 删除cookie
 */
function removeCookie(cookieName) {
    $.removeCookie(cookieName, {path: '/', domain: cookieDomain}); //path为指定路径，直接删除该路径下的cookie
//	var d = new Date();
//    document.cookie= cookieName + "=;expires=" + d.toGMTString();
}

function getLinkImgPath(path) {
    if (isNull(path)) {
        return "/static/html/images/bg/placeholder.png";
    } else {
        if (isProduce) {
            if (path.indexOf("misumi.com.cn") >= 0) {
                return "https://" + path;
            } else {
                return ImgServerPathPro + path;
            }
        } else {
            //暂时都用本番地址
            if (path.indexOf("misumi.com.cn") >= 0) {
                return "https://" + path;
            } else {
                return ImgServerPathStg + path;
            }
        }
    }
}

//比较价格
function comparePrice(minPrice, maxPrice) {
    var returnMinPrice = "-";
    if (isNull(minPrice) && !isNull(maxPrice)) {
        returnMinPrice = priceFormat(maxPrice) + "起";
    } else if (!isNull(minPrice) && isNull(maxPrice)) {
        returnMinPrice = priceFormat(minPrice) + "起";
    } else if (!isNull(minPrice) && !isNull(maxPrice)) {
        if (parseFloat(minPrice) > parseFloat(maxPrice)) {
            returnMinPrice = priceFormat(maxPrice) + "起";
        } else if (parseFloat(minPrice) < parseFloat(maxPrice)) {
            returnMinPrice = priceFormat(minPrice) + "起";
        } else {
            returnMinPrice = priceFormat(minPrice) + "起";
        }
    }
    return returnMinPrice;
}

//首页热门商品分类地址解析
function seriesNameLinkFomat(link) {
    if (!isNull(link)) {
        var codes = link.split("/");
        var catePath = "";
        for (var i = 0; i < codes.length; i++) {
            if (!isNull(codes[i]) && codes[i].indexOf("vona2") < 0 && codes[i].indexOf("?bid") < 0) {
                catePath += codes[i] + "/";
            }
        }
        return catePath;
    }
    return "";
}

/*
 * 猜你喜欢设置最后游览商品code
 */
function setAppFavStatic(appStaticObj) {
    var appValue = localStorage.getItem(RECOMMONDCODE);

    var newList = [];
    if (!isNull(appValue)) {
        var recommondSeriesList = $.parseJSON(appValue);
        for (var i = 0; i < recommondSeriesList.length; i++) {
            if (!isNull(userInfo) && !isNull(userInfo.userCode)) {
                if (recommondSeriesList[i].userCode == userInfo.userCode) {
                    recommondSeriesList.splice(i, 1);
                    break;
                }
            } else {
                if (recommondSeriesList[i].userCode == "NO_CODE") {
                    recommondSeriesList.splice(i, 1);
                    break;
                }
            }
        }
        newList = recommondSeriesList;
    }
    newList.push(appStaticObj);
    //mb缓存
    localStorage.setItem(RECOMMONDCODE, JSON.stringify(newList));
}

/**
 * @param {Object} key
 * 获取最近浏览的商品code
 */
function getAppFavStatic() {
    var returnResult = "";
    var result = localStorage.getItem(RECOMMONDCODE);
    if (!isNull(result)) {
        var recommondSeriesList = $.parseJSON(result);
        for (var i = 0; i < recommondSeriesList.length; i++) {
            if (!isNull(userInfo) && !isNull(userInfo.userCode)) {
                if (recommondSeriesList[i].userCode == userInfo.userCode) {
                    returnResult = recommondSeriesList[i].seriesCode;
                    break;
                }
            } else {
                if (recommondSeriesList[i].userCode == "NO_CODE") {
                    returnResult = recommondSeriesList[i].seriesCode;
                    break;
                }
            }

        }
    }
    return returnResult;
}

//计算发货日
function calCulatedeliveryDateNew(minDate, maxDate) {
    var returnDaysToShip = ""; //默认不显示
    var min = parseInt(minDate);
    var max = parseInt(maxDate);
    if (isNaN(min) && isNaN(max)) {
        return returnDaysToShip;
    } else if (isNaN(min)) {
        return returnDaysToShip;
    } else if (isNaN(max) || minDate == maxDate) {
        if (min == 0) {
            returnDaysToShip = "当天发货";
        } else if (min == 99) {
            returnDaysToShip = "每次进行询价";
        } else {
            returnDaysToShip = min + "天发货";
        }
    } else if (max < min) {
        min = max;
        if (min == 0) {
            returnDaysToShip = "当天发货";
        } else if (min == 99) {
            returnDaysToShip = "每次进行询价";
        } else {
            returnDaysToShip = min + "天发货";
        }
    } else {
        if (min == 0) {
            returnDaysToShip = "当天发货";
        } else if (min == 99) {
            returnDaysToShip = "每次进行询价";
        } else {
            returnDaysToShip = min + "天发货";
        }
    }
    return returnDaysToShip;
}

//商品列表计算折扣日
function showcampainEndDate(campainEndDate) {
    var reg = /^\d{4}(\-|\/|.)\d{1,2}\1\d{1,2}$/;
    var regExp = new RegExp(reg);
    if (regExp.test(campainEndDate)) {
        return "SALE " + campainEndDate.substring(5) + "为止";
    }
    return "";
}


/**
 * @param {Object} nowProcess 当前进行中的节点 1 2 3
 * @param {Object} type Order or Quotation
 * @param {Object} fromPage Cart or QuotationList
 */
function getProcessHtml(nowProcess, type, fromPage, isOrderToQuotation) {

    var processHtml = '';
    processHtml += '<div class="row no-gutter tac">';
    processHtml += '<div class="col-20" style="text-align: -webkit-center;">';
    processHtml += '<div>';
    processHtml += '<span class="processSelectSetpSpan">1</span>';
    processHtml += '</div>';
    var showFromHtml = '';
    if (fromPage == "Cart") {
        showFromHtml = "购物车";
    } else {
        showFromHtml = "报价列表";
    }
    processHtml += '<div style="padding-top: 8px;font-size: 12px;color: #333333;" class="processNotActiveSpan">' + showFromHtml + '</div>';
    processHtml += '</div>';
    processHtml += '<div class="col-20">';
    processHtml += '<hr  class="processSelectHr"/>';
    processHtml += '</div>';
    processHtml += '<div class="col-20" style="text-align: -webkit-center;">';
    processHtml += '<div>';
    processHtml += '<span class="processSelectSetpSpan">2</span>';
    processHtml += '</div>';
    var showOrderOrQuotation = "";
    var showOrderOrQuotationComplete = "";
    if (type == "Order") {
        showOrderOrQuotation = "订购";
        showOrderOrQuotationComplete = "订单";
    } else {
        if (!isNull(isOrderToQuotation) && isOrderToQuotation) {
            showOrderOrQuotation = "订购";
        } else {
            showOrderOrQuotation = "报价";
        }
        showOrderOrQuotationComplete = "报价";
    }
    processHtml += '<div style="padding-top: 8px;font-size: 12px;color: #333333;">' + showOrderOrQuotation + '确认</div>';
    processHtml += '</div>';
    processHtml += '<div class="col-20">';
    if (nowProcess == "2") {
        processHtml += '<hr  class="processNotSelectHr"/>';
        processHtml += '</div>';
        processHtml += '<div class="col-20" style="text-align: -webkit-center;">';
        processHtml += '<div>';
        processHtml += '<span class="processNotSelectSetpSpan">3</span>';
        processHtml += '</div>';
        processHtml += '<div style="padding-top: 8px;font-size: 12px;color: #333333;" class="processNotActiveSpan">' + showOrderOrQuotation + '完成</div>';
        processHtml += '</div></div>';
    } else {
        processHtml += '<hr  class="processSelectHr"/>';
        processHtml += '</div>';
        processHtml += '<div class="col-20" style="text-align: -webkit-center;">';
        processHtml += '<div>';
        processHtml += '<span class="processSelectSetpSpan">3</span>';
        processHtml += '</div>';
        processHtml += '<div style="padding-top: 8px;font-size: 12px;color: #333333;" class="processNotActiveSpan">' + showOrderOrQuotationComplete + '完成</div>';
        processHtml += '</div></div>';
    }
    return processHtml;
}

//发货方式
function expressWay(type) {
    var returnExpressWay = "";
    if (type == "T0") {
        returnExpressWay = "当日出货（瞬达T）";
    } else if (type == "A0") {
        returnExpressWay = "次日出货（瞬达A）";
    } else if (type == "B0") {
        returnExpressWay = "3天出货（瞬达B）";
    } else if (type == "C0") {
        returnExpressWay = "5天出货（瞬达C）";
    } else if (type == "0Z") {
        returnExpressWay = "瞬达Z";
    } else if (type == "0L") {
        returnExpressWay = "瞬达L";
    } else if (type == "0A") {
        returnExpressWay = "次日出货（瞬达A早期折扣）";
    } else if (type == "V0") {
        returnExpressWay = "闪达（V）";
    } else if (type == "00") {
        returnExpressWay = "不使用";
    } else {
        returnExpressWay = "-";
    }
    return returnExpressWay;
}

//报价状态
function judgeQuotationDetailStatus(status) {
    var returnStatus = "-";
    if ("1" == status) {
        returnStatus = "处理中";
    } else if ("3" == status) {
        returnStatus = "订购完成";
    } else if ("4" == status) {
        returnStatus = "发货完成";
    } else if ("z" == status) {
        returnStatus = "确认中";
    } else if ("2" == status) {
        returnStatus = "报价完成";
    } else if ("f" == status) {
        returnStatus = "失败";
    } else if ("c" == status) {
        returnStatus = "超过有效期";
    } else if ("e" == status) {
        returnStatus = "错误信息";
    }
    return returnStatus;
}

//订单状态
function judgeOrderDetailStatus(status) {
    var returnStatus = "-";
    if (status == "1") {
        returnStatus = "处理中";
    } else if (status == "3") {
        returnStatus = "订购完成";
    } else if (status == "4") {
        returnStatus = "发货完成";
    } else if (status == "f") {
        returnStatus = "失败";
    } else if (status == "z") {
        returnStatus = "确认中";
    } else if (status == "x") {
        returnStatus = "已取消";
    } else if (status == "1") {
        returnStatus = "处理中";
    } else if (status == "w") {
        returnStatus = "等待付款";
    } else if (status == "a1") {
        returnStatus = "等待承认";
    } else if (status == "a2") {
        returnStatus = "否认";
    } else if (status == "a3") {
        returnStatus = "退回";
    }
    return returnStatus;
}

//订购方式
function judgeOrderTypeResouce(orderType) {
    var returnOrderType = "";
    if ("M1" == orderType || "P1" == orderType) {
        returnOrderType = "MAIL";
    } else if ("F1" == orderType || "F2" == orderType || "F3" == orderType || "F4" == orderType) {
        returnOrderType = "FAX";
    } else if ("T1" == orderType) {
        returnOrderType = "TEL";
    } else if ("D1" == orderType) {
        returnOrderType = "EDI";
    } else if ("V1" == orderType || "K1" == orderType) {
        returnOrderType = "其他";
    } else if ("E1" == orderType || "D3" == orderType) {
        returnOrderType = "WEB";
    } else {
        returnOrderType = "-";
    }
    return returnOrderType;
}

function formatDate(idate) {
    if (isNull(idate)) {
        return "-";
    }
    var date = new Date(idate);
    var datetime = date.getFullYear() + "年" + +((date.getMonth() + 1) > 10 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1)) + "月" + +(date.getDate() < 10 ? "0" + date.getDate() : date
        .getDate()) + "日";
    return datetime;
}

//组装地址
function getAddress(address1, address2, address3, address4) {
    var returnAddressHtml = '';
    if (!isNull(address1)) {
        returnAddressHtml += address1 + "&nbsp;";
    }
    if (!isNull(address2)) {
        returnAddressHtml += address2 + "&nbsp;";
    }
    if (!isNull(address3)) {
        returnAddressHtml += address3 + "&nbsp;";
    }
    if (!isNull(address4)) {
        returnAddressHtml += address4 + "&nbsp;";
    }
    return returnAddressHtml;
}

//unfit文言
//function getNeedsInquiryBit(d) {
//
//	if(checkOrderUnit(d)){
//		return checkOrderUnit(d);
//	}
//
//	if(checkMinQuantity(d)){
//		return checkMinQuantity(d);
//	}
//
//	var returnBit = parseInt("" +
//		(d.unfitType == 4 ? "1" : "0") // 規格外
//		+
//		(d.largeOrderMaxQuantity ? "1" : "0") // 大口
//		+
//		d.priceInquiryFlag +
//		d.daysToShipInquiryFlag, 2);
//	//	    myApp.alert(returnBit);
//
//	var mask = {
//		ship: parseInt("1101", 2),
//		price: parseInt("1110", 2),
//		shipPrice: parseInt("0011", 2),
//		tooMany: parseInt("0100", 2),
//		unfit: parseInt("1000", 2)
//	}
//	var returnMsg = "";
//	if((returnBit & mask.unfit) > 0) {
//		returnMsg = "本产品的价格/交货期请通过WOS确认。"
//	} else if((returnBit & mask.tooMany) > 0) {
//		returnMsg = "本产品" + d.largeOrderMaxQuantity + "以上订购时, 如果要咨询价格。<br />请直接进入WOS询价。"
//	} else if((returnBit & mask.shipPrice) == mask.shipPrice) {
//		returnMsg = "本产品的价格/交货期随时进行预估。请直接进入WOS。<br />请直接进入WOS询价。"
//	} else if((returnBit & mask.price) > 0) {
//		returnMsg = "本产品的交货期随时进行预估。产品订购前可直接进入WOS咨询交货期。"
//	} else if((returnBit & mask.ship) > 0) {
//		returnMsg = "本商品的交期需每次通过报价确认。<br />请直接进入WOS询价。"
//	}
//
//	return returnMsg;
//}


// TODO 收货地址
function gotoAddress(context) {
    myApp.showIndicator();
    // 有选择权限
    let hasSelectedPermission = context && context.hasSelectedPermission;
    // 神策-PersonalPageClick-个人中心页
    //if($('.myInfo').find('li')[1].innerText == "收货地址") {
    sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "收货地址"});
    //}
    authInstance.checkSession(function (responseList) {
        //收货地址权限
        if (hasSelectedPermission || authInstance.hasShipToManagementPermission) {
            jumpUprPage("shipTo.html", context);
        } else {
            authInstance.noAuthTips();
        }

        myApp.hideIndicator();
    }, false)


}


function getNeedsInquiryBit(d) {

    if (checkOrderUnit(d)) {
        return checkOrderUnit(d);
    }

    if (checkMinQuantity(d)) {
        return checkMinQuantity(d);
    }

    var returnBit = parseInt("" + (d.unfitType == 4 ? "1" : "0") + (d.largeOrderMaxQuantity ? "1" : "0") + d.priceInquiryFlag + d.daysToShipInquiryFlag, 2);
    //	    myApp.alert(returnBit);

    var mask = {
        ship: parseInt("1101", 2),
        price: parseInt("1110", 2),
        shipPrice: parseInt("0011", 2),
        tooMany: parseInt("0100", 2),
        unfit: parseInt("1000", 2)
    }
    var returnMsg = "";
    if ((returnBit & mask.unfit) > 0) {
        returnMsg = "如需咨询此商品的价格和交货期,请先加入购物车,提交报价单,我们会尽快确认。"
    } else if ((returnBit & mask.tooMany) > 0) {
        returnMsg = "此商品订购" + d.largeOrderMaxQuantity + "以上时,如需咨询价格,请先加入购物车,提交报价单,我们会尽快确认。"
    } else if ((returnBit & mask.shipPrice) == mask.shipPrice) {
        returnMsg = "如需咨询此商品的价格和交货期,请先加入购物车,提交报价单,我们会尽快确认。"
    } else if ((returnBit & mask.price) > 0) {
        returnMsg = "如需咨询此商品的价格和交货期,请先加入购物车,提交报价单,我们会尽快确认。"
    } else if ((returnBit & mask.ship) > 0) {
        returnMsg = "如需咨询此商品的价格和交货期,请先加入购物车,提交报价单,我们会尽快确认。"
    }

    return returnMsg;
}

function checkOrderUnit(d) {
    return parseInt(d.orderUnit) && !(parseInt(d.quantity) % parseInt(d.orderUnit) == 0) ? "此产品" + d.orderUnit + "个起售，请输入" + d.orderUnit + "的倍数。" : false
}

function checkMinQuantity(d) {
    return (parseInt(d.minQuantity) || 0) > parseInt(d.quantity) ? "没有达到最低订购数量。请通过产品页面或产品目录确认。" : false
}

function addFrom() {
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        return "起";
    } else {
        return "";
    }
}

// function imgProductMain(path){
// 	if(!isNull(path)){
// 		path += "?$product_main$";
// 		return path;
// 	}else{
// 		return path;
// 	}
// }

function imgProductMain(path) {
    if (!isNull(path)) {
        if (path.indexOf("//content") >= 0 || path.indexOf("//stg-content") >= 0) {
            var replaceStr = "upload/t_product_main/v1"
            path = path.replace(/upload(\S+|\s+)v1/g, replaceStr)
        } else {
            path += "?$product_main$";
        }
        return path;
    } else {
        return path;
    }
}

/**
 * 数量折扣发货日期
 * @param {Object} daysToShip
 */
function gettVolumeDiscountDaysShip(daysToShip) {
    var returnCaldaysToShip = "-";
    if (isNull(daysToShip)) {
        return returnCaldaysToShip;
    }
    if (daysToShip == 0) {
        returnCaldaysToShip = "当天";
    } else if (daysToShip > 0 && daysToShip < 99) {
        returnCaldaysToShip = daysToShip + "天";
    } else if (daysToShip == 99) {
        returnCaldaysToShip = "询价";
    } else {
        returnCaldaysToShip = daysToShip + "天";
    }
    return returnCaldaysToShip;
}

//变更发货方式
function getShipOption(todayShipFlag, todayShipSelectedFlag) {
    if (todayShipFlag == "1") {
        if (todayShipSelectedFlag == "1") {
            return '变更'; //
        } else {
            return '当天发货'; //
        }
    } else {
        return "";
    }
}

function appApiError(error) {
    if (error.status == "401") {
        loginObj.showLoginDialog();
    } else if (error.status == "403") {
        if (!isNull(userInfo) && !isNull(userInfo.customerCode)) {
            var data = error.responseJSON;
            AlertDialog.alert(data.errorList[0].errorMessage, "错误信息")
        } else {
            var acountClass = new acount_class();
            acountClass.init();
        }
    } else {
        var data = error.responseJSON;
        if (data != undefined && data.errorList != undefined && data.errorList.length > 0) {
            AlertDialog.alert(data.errorList[0].errorMessage, "错误信息");
        }
    }
}

function appApiErrorForCoupon(error) {
    if (error.status == "401") {
        loginObj.showLoginDialog();
    } else {
        var data = error.responseJSON;
        if (data != undefined && data.errorList != undefined && data.errorList.length > 0) {
            AlertDialog.alert(data.errorList[0].errorMessage, "错误信息");
        }
    }
}

var acount_class = function () {
    this.init = function () {
        var initHtml = '<div class="div-modal account_main" style="opacity: 1; display: block;">' + '<div class="div-modal-body">' + '<div class="div-title">' + '<span class="span-title">您是个人用户，如需报价或订购请先升级或绑定为企业用户</span>' + '</div>' + '<div style="margin: 0 15px 0;">' + '<button id="btn_bind_grade">升级为企业用户</button>' +

            '<button id="btn_up_grade">绑定企业用户</button>' +

            '<button id="btn_close_upOrBind_grade">关闭</button>' + '</div>' + '</div>' + '</div>';
        $("body .account_main").remove();
        $("body").append(initHtml);


        $("#cookieImgs").remove();
        $("body").append('<div class="dn" id="cookieImgs"></div>');

        var cookieHtml = "";
        if (userInfo != null && !isNull(userInfo.createCookieUrlList) && userInfo.createCookieUrlList.length > 0) {
            var urlList = userInfo.createCookieUrlList;

            for (var i = 0; i < urlList.length; i++) {
                cookieHtml += '<img src="' + urlList[i] + '" />';
            }
        }
        $("#cookieImgs").html(cookieHtml);


        $("#btn_bind_grade").unbind("click").bind("click", function () {
            //埋点：点击升级企业用户
            sensors.track('UpgradeCompany', {
                current_page: '我的'
            })

            closeThis();
            openAccountUrl("accountUpGrade");
        });
        $("#btn_up_grade").unbind("click").bind("click", function () {
            //埋点：点击绑定企业用户
            sensors.track('BindCompany', {
                current_page: '我的'
            })
            closeThis();
            openAccountUrl("accountBindGrade");
        });
        $("#btn_close_upOrBind_grade").unbind("click").bind("click", function () {
            closeThis();
        });
        showThis();
    }

    function showThis() {
        $(".div-modal").fadeTo(300, 1);
        //隐藏窗体的滚动条
        $("body").css({
            "overflow": "hidden"
        });
    }

    function closeThis() {
        $(".div-modal").fadeOut(300);
        //显示窗体的滚动条
        $("body").css({
            "overflow": "visible"
        });
    }

    function openAccountUrl(url) {
        if (isProduce) {
            if (url == "accountUpGrade") {
                window.open("https://wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE");
                //					window.open("https://www.misumi-ec.com/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_ACCOUNT_UP_GRADE_WITH_EXISTED_CUSTOMER_CODE");
            } else if (url == "accountBindGrade") {
                window.open("https://wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE_WITH_EXISTED_CUSTOMER_CODE");
                //					window.open("https://www.misumi-ec.com/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_ACCOUNT_UP_GRADE");
            }
        } else {
            if (url == "accountUpGrade") {
                window.open("https://stg0-wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE");
            } else if (url == "accountBindGrade") {
                window.open("https://stg0-wos.misumi.com.cn/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_SP_ACCOUNT_UP_GRADE_WITH_EXISTED_CUSTOMER_CODE");
                //					window.open("https://www.misumi-ec.com/cn/common/EC002SingleLoginCmd.do?lang=cn&OK_URL=/cn/common/EC003WosTopCmd.do?commandCode=EC_ACCOUNT_UP_GRADE");
            }
        }
    }
}


/**
 *
 * @param seriesCode
 * @param partNumber
 * @param quantity
 * @param fn
 * @param isDiscount
 * @param statusText
 * @param isClass 是否末端分类页的人气商品
 */
function gotoProductInfo(seriesCode, partNumber, quantity, fn, isDiscount, statusText, isClass, isSearch) {
    localStorage.removeItem('redirect')
    if (fn) fn();
    if (typeof WebUtils === 'undefined') {
        var partNumberParam = "";
        if (!isNull(partNumber)) {
            partNumberParam = "?HissuCode=" + partNumber + noNeedString();
        } else {
            partNumberParam = needString();
        }
        if (isDiscount) {
            partNumberParam += '&isDiscount=1'
        }
        if (isSearch) {
            partNumberParam += '&isSearch=1'
        }
        window.location.href = jumpUrl + "/vona2/detail/" + seriesCode + "/" + partNumberParam;
    }
    var partNumberParam = "";
    if (isNull(seriesCode)) {
        AlertDialog.alert("该商品信息未公开,可直接订购");
        return;
    }
    var param = {};
    param.seriesCode = seriesCode;
    param.pageSize = 100;
    param.page = 1;
    param.field = "@search";
    param.allSpecFlag = "1";

    var action = WebUtils.preEcApi(api_getSeriesSearch);
    WebUtils.ajaxGetSubmit(action, param, function (result) { //success
        if (result['seriesList'].length > 0 && result['specList'].length > 0) {
            if (!isNull(partNumber)) {
                partNumberParam = "?HissuCode=" + partNumber + noNeedString();
            } else {
                partNumberParam = needString();
            }
            if (isDiscount) {
                partNumberParam += '&isDiscount=1'
            }
            if (!isNull(statusText)) {
                partNumberParam += '&statusText=' + statusText
            }
            if (isMiniProgram() && isClass) {
                let RecommendObj = SensorsSearchPage({detail: result})
                sensors.track("ProductClick", {button_name: '预览商品', button_type: '人气商品栏', ...RecommendObj});
            }
            if (isSearch) {
                partNumberParam += '&isSearch=1'
            }
            // window.localStorage.setItem("cart_check_list", getCheckedSeNo())
            window.location.href = jumpUrl + "/vona2/detail/" + seriesCode + "/" + partNumberParam;
        } else {
            AlertDialog.alert("该商品不存在!");
            return;
        }
    }, function (error) { //error
        // depoProductListBack(error.status, error.responseText);
        AlertDialog.alert(error.responseText);
    }, function (XHR, TS) { //complete

    });
}

// function getCheckedSeNo(){
// 	var seNos = []
// 	$("#cartItemList .cartDiv .form-checkbox input").each(function() {
// 		if($(this).is(':checked')) {
// 			seNos.push($($(this).parents('.cartDiv')[0]).attr('seriescode'));
// 		}
// 	});
// 	return JSON.stringify(seNos);
// }

function gotoCategoryListFormLp(categoryCode) {
    window.location.href = jumpUrl + "/vona2/" + categoryCode + needString();
}

function gotoIndex() {
    window.location.href = jumpUrl + "";
}

function gotoCartListNotInIndex() {
    window.location.href = jumpUrl + "/static/html/page/cart.html";
}

function gotoQuotationListFromOrderComfirm() {
    window.location.href = "quotationList.html";
}

function topBannerGotoSolidworksRD() {
    userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    if (!isNull(userInfo) && !isNull(userInfo.userCode)) {
        window.open(jumpUrl + "/static/html/page/localPage/SolidworksRD190627.html?sessionId=" + userInfo.sessionId + "&customerCode=" + userInfo.customerCode + "&userName=" + userInfo.userName + "&customerName=" + userInfo.customerName);
    } else {
        loginObj.showLoginDialog();
    }
}

//计算发货日
function calCulatedeliveryDate2(minDate, maxDate) {
    var returnDaysToShip = ""; //默认不显示
    var min = parseInt(minDate);
    var max = parseInt(maxDate);
    if (isNaN(min) && isNaN(max)) {
        return returnDaysToShip;
    } else if (isNaN(min)) {
        return returnDaysToShip;
    } else if (isNaN(max) || minDate == maxDate) {
        if (min == 0) {
            returnDaysToShip = "当天";
        } else if (min == 99) {
            returnDaysToShip = "每次进行询价";
        } else {
            returnDaysToShip = min + "天";
        }
    } else if (max < min) {
        min = max;
        if (min == 0) {
            returnDaysToShip = "当天";
        } else if (min == 99) {
            returnDaysToShip = "每次进行询价";
        } else {
            returnDaysToShip = min + "天";
        }
    } else {
        if (min == 0) {
            returnDaysToShip = "当天";
        } else if (min == 99) {
            returnDaysToShip = "每次进行询价";
        } else {
            returnDaysToShip = min + "天";
        }
    }
    return returnDaysToShip;
}

//格式化复杂品型号
function formatComplexPartNum(str) {
    if (isNull(str)) {
        return ["", 0];
    }
    var strs = str.split("[");
    if (strs.length == 1) {
        return [str, 0];
    }
    var complexHtml = "";
    for (var i = 0; i < strs.length; i++) {
        var strss = strs[i].split("]");
        if (i == 0) {
            complexHtml += strs[i];
        } else {
            complexHtml += '<span style="color:#003399;    background-color: #FFCC00;padding:1px 0 2px;">[' + strss[0] + ']</span>' + strss[1];
        }
    }
    return [complexHtml, strs.length - 1];
}

/**
 * @param {Object} type screen代表屏幕  action代表事件
 * @param {Object} screenName 屏幕名称
 * @param {Object} category 事件名称
 * @param {Object} label 事件标签
 */
function sendGa(type, screenName, category, label, scode, ccode) {
}

function sendScreenGa(screenName, scode, ccode) {
}

function sendActionGa(screenName, myCategory, myLabel, action) {
}

function sendActionGaAfterRegiste(screenName, myCategory, myLabel) {
}

function sendScreenGaAfterRegiste(screenName, scode, ccode) {
}

function sendActionGaAfterRegiste(screenName, myCategory, myLabel) {
}

function sendScreenGaAfterRegiste(screenName, scode, ccode) {
}

function sendScreenGaAfterRegiste(screenName, scode, ccode) {
}

//macShowAndHide看起来是原生需要的方法
function macShowAndHide() {
}

function getGaTime() {
    var dt = new Date();
    dt = new Date(dt.getTime() + 8 * 60 * 60 * 1000);
    var str = dt.toISOString();
    var resutl = str.replace(/[a-zA-Z]/g, " ") + "CST";
    return resutl;
}

//输入范围判断,是否输入正确
function isInRange(min, max, step, v) {
    if (parseFloat(v) > parseFloat(max) || parseFloat(v) < parseFloat(min)) {
        return false;
    }
    var ti = 0;
    if (step.toString().split(".").length > 1) {
        ti = step.toString().split(".")[1].length
    }
    var inTi = 0;
    if (v.toString().split(".").length > 1) {
        inTi = v.toString().split(".")[1].length
    }
    if (inTi > ti) {
        //小数点后长度大于精度
        //您所输入的值不在规定范围内，请确认后重新输入
        return false;
    }
    var bs = Math.pow(10, ti);
    var miu = parseInt(v * bs) - parseInt(min * bs);
    if ((miu) % (parseInt(step * bs)) == 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * @param {Object} type 0：不做操作 1,显示mic；2：隐藏mic 3:关闭登录框  4：关闭回退动画效果并显示mic 5 回到首页 并选中我的  6 回到首页并选中首页
 */
function returnBackForPrise(type) {
    if (window.currentCaseNo) currentCaseNo = ""; // 如果有点击过案例库，则回退时这个值要清空
    if (type == 2) {
        // mainView.router.back();
        history.go(-1);
        var param = {
            "operation": "hide"
        };
        macShowAndHide(param);
    } else if (type == 1) {

        if ($(".page-on-left:last").attr("data-page") == "search") {

            var param = {
                "operation": "show"
            };
            macShowAndHide(param);
        }
        // mainView.router.back();
        history.go(-1);
    } else if (type == 3) {
        LoginButtonClickState = '其他'
        if ($(".page-on-left").length > 0) {
            if ($(".page-on-left").eq($(".page-on-left").length - 1).attr("data-page") == "search") {
                var param = {
                    "operation": "show"
                };
                macShowAndHide(param);
            }
        }
        clearnJSMessageStack();
        // mainView.router.back();
        history.go(-1);
    } else if (type == 4) {

        if ($(".page-on-left:last").attr("data-page") == "search") {

            var param = {
                "operation": "show"
            };
            macShowAndHide(param);
        }
        history.go(-1);
        // mainView.router.back({
        //     animatePages: false
        // });
    } else if (type == 5) { //个人中心
        history.go(-1);
        // mainView.router.back({
        //     pageName: 'tabbar-labels',
        //     force: true,
        //     animatePages: false
        // });
        $("#homePageBottomBar .bottombar").eq(3).click();
    } else if (type == 6) { //去首页
        // mainView.router.back({
        //     pageName: 'tabbar-labels',
        //     force: true
        // });
        history.go(-1);
        $("#homePageBottomBar .bottombar").eq(0).click();
    } else if (type == 7) {

        if ($(".page-on-left").length > 0) {
            if ($(".page-on-left").eq($(".page-on-left").length - 1).attr("data-page") == "search") {
                var param = {
                    "operation": "show"
                };
                macShowAndHide(param);
            }
        }
        // mainView.router.back();
        history.go(-1);
    } else if (type == 8) {
        fromMessageCenter = false;
        // mainView.router.back();
        history.go(-1);
    } else if (type == 9) {
        myApp.params.modalButtonOk = "再看看";
        myApp.params.modalButtonCancel = "离开";
        myApp.confirm("您即将离开本页面<br/>进入【我的】→【设置】→【消息】<br/>您可以重新回到这里哦~", "", function () {

        }, function () {
            // mainView.router.back();
            history.go(-1);
        });
        $(".modal-inner .modal-text").css("font-size", "14px");
        myApp.params.modalButtonOk = "确定";
        myApp.params.modalButtonCancel = "取消";
    } else if (type == 11) {
        myApp.params.modalButtonOk = "再看看";
        myApp.params.modalButtonCancel = "离开";
        myApp.confirm("您即将离开本页面<br/>进入【我的】→【设置】→【消息】<br/>您可以重新回到这里哦~", "", function () {

        }, function () {
            // mainView.router.back({
            //     pageName: 'tabbar-labels',
            //     force: true
            // });
            history.go(-1);
            $("#homePageBottomBar .bottombar").eq(0).click();
        });

        $(".modal-inner .modal-text").css("font-size", "14px");
        myApp.params.modalButtonOk = "确定";
        myApp.params.modalButtonCancel = "取消";
    } else if (type == 10) {
        history.go(-1);
        // mainView.router.back({
        //     animatePages: false
        // });
        openPhoto();

    } else if (type == 12) {
        //退出画面，型号会被清空时（未点确认按钮时）

        if (!isNull($(".page-on-center #complexDetailSelectPartNum").html())) {
            var isFirstIn = true;
            if (!isNull(guideObj) && guideObj.length > 0) {
                for (var i = 0; i < guideObj.length; i++) {
                    if (guideObj[i] == "rememberQuite") {
                        isFirstIn = false;
                    }
                }
            }
            if (isFirstIn) {
                $("#div_3DView_black").show();
                $("#div_3DView_pop").show();
            } else {
                returnBack(1);
            }
        } else {
            returnBack(1);
        }

    } else if (type == 13) {
        //退出画面，设定筛选条件提示

        var isFirstIn = true;
        if (!isNull(guideObj) && guideObj.length > 0) {
            for (var i = 0; i < guideObj.length; i++) {
                if (guideObj[i] == "rememberQuiteChoosePartNumber") {
                    isFirstIn = false;
                }
            }
        }
        if (isFirstIn) {
            $("#div_complex_info_black").show();
            $("#div_complex_info_pop").show();
        } else {
            returnBack(0);
        }

    } else if (type == 14) { //商品分类
        history.go(-1);
        // mainView.router.back({
        //     pageName: 'tabbar-labels',
        //     force: true,
        //     animatePages: false
        // });
        $("#homePageBottomBar .bottombar").eq(1).click();
    } else if (type == 15) { //返回购物车
        //返回购物车
        history.go(-1);
        // mainView.router.back({
        //     pageName: 'tabbar-labels',
        //     force: true,
        //     animatePages: false
        // });
        $(".bottombar [bid='cart']").click()
    } else {
        // mainView.router.back();
        history.go(-1);
    }
}

macShowAndHide({
    "operation": "hide"
});

//设置打开过的引导页名字
function setUserGuide(pageName) {
    var userGuilds = localStorage.getItem("UserGuide");
    var guideObj = [];
    if (isNull(userGuilds)) {
        guideObj = [];
        guideObj.push(pageName);
    } else {
        guideObj = JSON.parse(userGuilds);
        var pushFlag = true;
        $.each(guideObj, function (dex, data) {
            if (pageName == data) {
                pushFlag = false;
                return false;
            }
        });
        if (pushFlag) {
            guideObj.push(pageName);
        }
    }
    localStorage.setItem("UserGuide", JSON.stringify(guideObj));
}

//获取引导页列表
function getUserGuides() {
    var userGuilds = localStorage.getItem("UserGuide");
    var guideObj = [];
    if (isNull(userGuilds)) {
        guideObj = [];
    } else {
        guideObj = JSON.parse(userGuilds);
    }
    return guideObj;
}

//弹出修改用户名提示
function openDelUserModal() {
    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/offerConfirmation/oc-6.png" alt="">
<div class="text1" style="margin-top: 0.3rem">您确定要删除账号吗？</div>
<div class="btn-content" style="padding: 0 1.4rem">

<div class="btn1" onclick="tomyPage()">取消</div>
<div class="btn2"  id="deleteUserFun">确定</div>
</div>
</div>`

    myApp.modal({
        cssClass: 'common-modal del-user-modal', text: text
    })
}


function tomyPage() {
    closeModal('del-user-modal');
    closePage('del-user-page')
    myApp.closeModal()
}

//弹出修改用户名提示
function openSaveUsernameModal() {
    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text3" style="margin-top: 0.3rem">您确定要修改用户名吗？</div>
<div class="text3">用户名仅可修改一次</div>
<div class="btn-content ">

<div class="btn1" onclick="closeModal('username-modal')">取消</div>
<div class="btn2" id="comformSubmitAccount">确定</div>
</div>
</div>`

    myApp.modal({
        cssClass: 'common-modal username-modal', text: text
    })
}

function closeModal(className, type) {
    myApp.closeModal(`.${className}`)

    if (type == 'cart') {//购物车
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-提示框', button_name: '关闭'});
    } else if (type == 'cartAlert') {//购物车
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车', button_name: '关闭'});
    } else if (type == 'order') {//订购
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-去订购', button_name: '关闭'});
    } else if (type == 'quote') {//报价
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-去报价', button_name: '关闭'});
    } else if (type == 'my') {//个人中心弹框
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '个人中心页', button_name: '关闭'});
    }
}

function gotoPcOrApp() {
    AlertDialog.confirm("此功能需要访问PC版或使用APP", "", "打开APP查看", "访问PC版查看", function () {
        sendGa("action", "", "AppDownload", "");
        window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.misumi_ec.cn.misumi_ec";
    }, function () {
        sendGa("action", "", "VisitPC", "");
        window.location.href = "https://www.misumi.com.cn/";
    }, true);
}

function gotoApp(source) {
    AlertDialog.confirm("此功能需要访问APP才能使用", "", "打开APP", "取消", function () {
        sendGa("action", "", "AppDownload", "");
        //埋点：诱导APP下载
        sensors.track("RecommendAPP", {source_page: source, button_name: "打开APP"});
        window.location.href = jumpUrl + "/static/html/page/downOropenApp.html"
        // window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.misumi_ec.cn.misumi_ec";
    }, function () {
        sensors.track("RecommendAPP", {source_page: source, button_name: "取消"});
    }, true);
}

function showIndicator_() {
    if ($('.preloader-indicator-overlay').length > 0) return;
    $('body').append('<div class="preloader-indicator-overlay"></div><div class="preloader-indicator-modal"><span class="preloader preloader-white"></span></div>');
}

function hideIndicator_() {
    $('.preloader-indicator-overlay, .preloader-indicator-modal').remove();
}

//比较价格
function comparePriceNew(minPrice, maxPrice) {
    var returnMinPrice = "";
    if (isNull(minPrice) && !isNull(maxPrice)) {
        returnMinPrice = priceFormat(maxPrice) + "起";
    } else if (!isNull(minPrice) && isNull(maxPrice)) {
        returnMinPrice = priceFormat(minPrice) + "起";
    } else if (!isNull(minPrice) && !isNull(maxPrice)) {
        if (parseFloat(minPrice) > parseFloat(maxPrice)) {
            returnMinPrice = priceFormat(maxPrice) + "起";
        } else if (parseFloat(minPrice) < parseFloat(maxPrice)) {
            returnMinPrice = priceFormat(minPrice) + "起";
        } else {
            returnMinPrice = priceFormat(minPrice) + "起";
        }
    }
    return returnMinPrice;
}

function openPCSite() {
    sendGa("action", "", "VisitPC", "");
    window.location.href = "https://www.misumi.com.cn/";
}

function openAppSite(source) {
    //埋点：诱导APP下载
    sensors.track('RecommendAPP', {
        source_page: source, button_name: '立即打开'
    }, function () {
        window.location.href = jumpUrl + "/static/html/page/downOropenApp.html"
        // window.location.href = "http://a.app.qq.com/o/simple.jsp?pkgname=com.misumi_ec.cn.misumi_ec";
    });
    sendGa("action", "", "AppDownload", "");
}

//获取购物车数量
function getCartNumber() {
    var param = {};
    var action = WebUtils.preReferPCApiParam(upr_api_cart_search);
    WebUtils.ajaxGetSubmit(action, param, function (result) { //success
        if (result != undefined) {
            setCartCount(result.cartCount);
        }
    }, function (error) { //error

    }, function (XHR, TS) { //complete

    });
}


//设置购物车数量
function setCartCount(num) {
    if (isNull(num) || num == "0") {
        $("#indexCartCount").hide();
        $("#complexPdCartCount").addClass("no");
        $("#complexPdCartCount").attr("realcartcount", 0);
        $("#pdCartCount").addClass("no");
        $("#pdCartCount").attr("realcartcount", 0);
    } else {
        $("#indexCartCount").show();
        $("#complexPdCartCount").removeClass("no");
        $("#complexPdCartCount").attr("realcartcount", num);
        $("#pdCartCount").removeClass("no");
        $("#pdCartCount").attr("realcartcount", num);
        if (parseInt(num) <= 99) {
            $("#indexCartCount").html(num);
            $("#complexPdCartCount").html(num);
            $("#pdCartCount").html(num);
        } else {
            $("#indexCartCount").html("...");
            $("#complexPdCartCount").html("...");
            $("#pdCartCount").html("...");
        }
    }
}


function hrefUrl(url, isNeedLogin) {
    if (isNeedLogin) {
        if (!checkIsLoginForLP()) {
            setTimeout(function () {
                localStorage.setItem('redirect', JSON.stringify({from: 'lp', url: jumpUrl + url}))//从哪来回哪的方法
                loginObj.showLoginDialog()
            }, 500)

        } else {
            window.location.href = jumpUrl + url;
        }
    } else {
        window.location.href = jumpUrl + url;
    }


}


function jspJump(url) {
    if (url.indexOf("vona2") > 0) {
        if (url.indexOf("?") > 0) {
            url += noNeedString()
        } else {
            url += needString();
        }
    }
    window.location.href = url;
}

/**
 * 返回上一页
 * @returns
 */
function rebackPage() {
    history.go(-1);
    return false;
}

function indexGotoCatalog() {
    userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    if (!isNull(userInfo) && !isNull(userInfo.userCode)) {
        window.location.href = "/catalog/catalogIndex/";
    } else {
        loginObj.showLoginDialog();
    }
}

function sendBaiduPush() {
    //百度统计代码和百度推送代码
    // var bp = document.createElement('script');
    // var curProtocol = window.location.protocol.split(':')[0];
    // if (curProtocol === 'https') {
    //     bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    // } else {
    //     bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    // }
    // var s = document.getElementsByTagName("script")[0];
    // s.parentNode.insertBefore(bp, s);
    //
    // baiduAnalytics();
}

//百度分析
function baiduAnalytics() {
    // var hm = document.createElement("script");
    // hm.src = "//hm.baidu.com/hm.js?c86e2c4bb4ad01427261d9484e89bf8b";
    // var s = document.getElementsByTagName("script")[0];
    // s.parentNode.insertBefore(hm, s);
}

/**
 * 关键字检索跳转
 * @param keyword
 * @returns
 */
function keywordSearchCopy(keyword) {
    var urlParam = "";
    if (!isNull(keyword)) {
        urlParam = "?Keyword=" + keyword + noNeedString();
    } else {
        urlParam = needString();
    }

    window.location.href = jumpUrl + "/vona2/result/" + urlParam;
}

//unfit判断
function showUnfitFlag(d, type) {
    var returnBit = parseInt("" + (d.unfitType == 4 ? "1" : "0") // 規格外
        + (d.largeOrderMaxQuantity ? "1" : "0") // 大口
        + d.priceInquiryFlag + d.daysToShipInquiryFlag, 2);
    //	    myApp.alert(returnBit);

    var mask = {
        ship: parseInt("1101", 2),
        price: parseInt("1110", 2),
        shipPrice: parseInt("0011", 2),
        tooMany: parseInt("0100", 2),
        unfit: parseInt("1000", 2)
    }
    if (type == "price") {
        return (returnBit & mask.price) > 0;
    } else {
        return (returnBit & mask.ship) > 0;
    }


}


//删除账号时解绑微信
function deleteAccountAndUnBindWeChat(callback) {
    var action = WebUtils.deleteAccountAndUnBindWeChat();
    WebUtils.ajaxPutSubmit(action, "", function (result) { //success
        // callback();
    }, function (error) { //error
        // callback();
    }, function (XHR, TS) { //complete
        callback();
    });
}


// function goToDetailPage(){
// 	const needPayOrder = localStorage.getItem("needPayOrder")
// 	if(needPayOrder){
// 		localStorage.removeItem("needPayOrder")
// 		window.location.href = jumpUrl + "/static/html/page/orderDetail.html?soNo=" + needPayOrder
// 	}
// }

function initGa() {
}


function isInclude(name) {
    var js = /js$/i.test(name);
    var es = document.getElementsByTagName(js ? 'script' : 'link');
    for (var i = 0; i < es.length; i++) if (es[i][js ? 'src' : 'href'].indexOf(name) != -1) {
        return true;
    }
    return false;
}

function loadJS(url) {

    var script = document.createElement('script');
    script.type = 'text/javascript';

    script.src = url;

    document.getElementsByTagName('head')[0].appendChild(script);

}

//保存最近浏览的seriesCode
function saveRecentSeriesCode(seriesCode) {
    if (isNull(seriesCode)) {
        return;
    }
    var codes = localStorage.getItem("MisumiRecentSeriesCodes");
    var arr = [];
    if (!isNull(codes)) {
        arr = codes.split(",");
        if ($.inArray(seriesCode, arr) < 0) {
            arr.unshift(seriesCode);
            if (arr.length > 10) {
                arr = arr.slice(0, 10);
            }
        } else {
            var idx = $.inArray(seriesCode, arr);
            arr.splice(idx, 1);
            arr.unshift(seriesCode);
        }
        var resultCodes = "";
        for (var i = 0; i < arr.length; i++) {
            resultCodes += arr[i];
            if (i < arr.length - 1) {
                resultCodes += ",";
            }
        }
        localStorage.setItem("MisumiRecentSeriesCodes", resultCodes);
    } else {
        //第一个数据
        localStorage.setItem("MisumiRecentSeriesCodes", seriesCode);
    }
}

//商品详情一起浏览跳转商品详情GA
function gotoPdRecmdreadFromDetailGa(i, seriesCode, detailtype, itemObjStr) {

    //埋点：推荐点击(商品详情->常被一起浏览的商品)
    var itemObj = JSON.parse(decodeURIComponent(itemObjStr));
    sendSensorRecommend('商品详情页', '常被一起浏览的商品', itemObj)

    sendGa("action", "", "Detail", "Recmdread_item_" + seriesCode);
    if (detailtype == "cp") {//复杂品
        //一起浏览,第几个
        var logbody = {
            "logtype": "6", "remark1": i + "", "remark2": seriesCode
        };
        addMisumiAppLog(logbody);
    } else {//简单品
        //一起浏览,第几个
        var logbody = {
            "logtype": "8", "remark1": i + "", "remark2": seriesCode
        };
        addMisumiAppLog(logbody);
    }
}

//商品详情一起购买跳转商品详情GA
function gotoPdRecmdbuyFromDetailGa(i, seriesCode, detailtype, itemObjStr) {
    //埋点：推荐点击(商品详情->常被一起购买的商品)
    var itemObj = JSON.parse(decodeURIComponent(itemObjStr));
    sendSensorRecommend('商品详情页', '常被一起购买的商品', itemObj)

    sendGa("action", "", "Detail", "Recmdbuy_item_" + seriesCode);
    if (detailtype == "cp") {//复杂品
        //一起浏览,第几个
        var logbody = {
            "logtype": "7", "remark1": i + "", "remark2": seriesCode
        };
        addMisumiAppLog(logbody);
    } else {//简单品
        //一起浏览,第几个
        var logbody = {
            "logtype": "9", "remark1": i + "", "remark2": seriesCode
        };
        addMisumiAppLog(logbody);
    }
}

//MisumiApi添加日志接口
function addMisumiAppLog(logbody) {
    if (isNull(logbody)) {
        logbody = {};
    }
    //保存log
    var action = `${apiUrl.Campaign.urlList.addLog({})}`
    // var action = WebUtils.preWebUrlApiWithOutParam(url_api_addLog);
    if (!isNull(userInfo) && !isNull(userInfo.sessionId)) {
        logbody.sessionId = userInfo.sessionId;
    }
    logbody.deviceos = "mb";
    logbody.deviceuuid = "-";
    $.ajax({
        url: action, data: JSON.stringify(logbody), async: false, type: 'POST', headers: {
            "x-api-key": apiUrl.Campaign.xApiKey
        }, dataType: 'json', contentType: "application/json", complete: function (XHR, TS) {
        }, success: function (result) {
        }, error: function (result) {
        }
    });
}

//发起EClog日志Api
function postSearchLogApi(logType, message) {
    message.cookieId = getCommonLogCookieId();
    var body = {
        'message': message
    };
    var action = WebUtils.preEcApi(api_logAdd);
    action = action + '&logType=' + logType + '&suppressResponseCode=true';
    WebUtils.ajaxPostSubmitJson(action, JSON.stringify(body), function (result) { //success
    }, function (error) { //error
    }, function (XHR, TS) { //complete
    });
}

function getCommonLogCookieId() {
    var cookieId = localStorage.getItem("CommonLogCookieId");
    if (!isNull(cookieId)) {
        return cookieId;
    } else {
        var c = getGuid();
        localStorage.setItem("CommonLogCookieId", c);
        return c;
    }
}

//获取当前时间，格式YYYY-MM-DD
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "/";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    }
    var strDate = date.getDate();
    if (strDate < 10) {
        strDate = '0' + strDate;
    }
    var hours = date.getHours();
    if (hours < 10) {
        hours = '0' + hours;
    }
    var minutes = date.getMinutes();
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    var seconds = date.getSeconds();
    if (seconds < 10) {
        seconds = '0' + seconds;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate + ' ' + hours + ':' + minutes + ':' + seconds;
    return currentdate;
}

//获取当前时间，格式YYYY-MM-DD HH:mm:ss
function getDateWithFormate(formate) {
    var date = new Date();
    var dateStr = formate;
    var seperator1 = "/";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    if (month < 10) {
        month = '0' + month;
    }
    var strDate = date.getDate();
    if (strDate < 10) {
        strDate = '0' + strDate;
    }
    var hours = date.getHours();
    if (hours < 10) {
        hours = '0' + hours;
    }
    var minutes = date.getMinutes();
    if (minutes < 10) {
        minutes = '0' + minutes;
    }
    var seconds = date.getSeconds();
    if (seconds < 10) {
        seconds = '0' + seconds;
    }
    dateStr = dateStr.replace(/YYYY/g, year);
    dateStr = dateStr.replace(/MM/g, month);
    dateStr = dateStr.replace(/DD/g, strDate);
    dateStr = dateStr.replace(/HH/g, hours);
    dateStr = dateStr.replace(/mm/g, minutes);
    dateStr = dateStr.replace(/ss/g, seconds);

    return dateStr;
}

//发送MA Tracker网页浏览//暂时注释
function sendMAPage() {
}

//发送MA Tracker事件互动
function sendMATrack(eventId, params) {
}

//发送MA Tracker identify
function sendMAIdentify() {
}

//发送convertLab 事件
function sendconvertLabTrack(event, params) {
}

//发送convertLab 用户识别
function sendConvertLabIdentify() {
}

//判断是否为iPhone
function isIphone() {
    if (navigator.userAgent.toLowerCase().indexOf("iphone") > -1 || navigator.userAgent.toLowerCase().indexOf("ipad") > -1) {
        return true;
    } else {
        return false;
    }
}

//381-skye
function checkTabType(tabType) {
    var tabList;
    if (tabType == 1) {
        tabList = [{
            "tabId": "tabList_basicInfo", "tabName": "基本信息", "tabHtml": ['productDescriptionHtml']
        }, {
            "tabId": "wysiwyg_area_1", "tabName": "规格表", "tabHtml": ['specificationsHtml', 'alterationHtml']
        }, {"tabId": "wysiwyg_area_2", "tabName": "交货期/价格", "tabHtml": ['priceListHtml', 'daysToShipHtml']}, {
            "tabId": "wysiwyg_area_3", "tabName": "概述/特性", "tabHtml": ['overviewHtml', 'exampleHtml', 'generalHtml']
        },];
    } else if (tabType == 2) {
        tabList = [{
            "tabId": "tabList_basicInfo",
            "tabName": "基本信息",
            "tabHtml": ['productDescriptionHtml', 'specificationsHtml', 'alterationHtml']
        }, {"tabId": "wysiwyg_area_2", "tabName": "交货期/价格", "tabHtml": ['priceListHtml', 'daysToShipHtml']}, {
            "tabId": "wysiwyg_area_3", "tabName": "概述/特性", "tabHtml": ['overviewHtml', 'exampleHtml', 'generalHtml']
        },];
    } else if (tabType == 3) {
        tabList = [{
            "tabId": "tabList_basicInfo",
            "tabName": "基本信息",
            "tabHtml": ['specificationsHtml', 'daysToShipHtml', 'overviewHtml', 'generalHtml']
        }, {"tabId": "wysiwyg_area_2", "tabName": "使用方法", "tabHtml": ['exampleHtml']}, {
            "tabId": "wysiwyg_area_3", "tabName": "尺寸图", "tabHtml": ['alterationHtml']
        }, {"tabId": "basic_spec", "tabName": "基本规格", "tabHtml": ['standardSpecHtml']},];
    } else if (tabType == 4) {
        tabList = [{
            "tabId": "tabList_basicInfo",
            "tabName": "基本信息",
            "tabHtml": ['specificationsHtml', 'daysToShipHtml', 'overviewHtml', 'generalHtml']
        }, {"tabId": "wysiwyg_area_2", "tabName": "使用方法", "tabHtml": ['exampleHtml']}, {
            "tabId": "wysiwyg_area_3", "tabName": "尺寸图", "tabHtml": ['alterationHtml']
        }, {"tabId": "basic_spec", "tabName": "基本规格", "tabHtml": ['standardSpecHtml']},];
    } else if (tabType == 5) {
        tabList = [{
            "tabId": "tabList_basicInfo", "tabName": "基本信息", "tabHtml": ['productDescriptionHtml']
        }, {
            "tabId": "wysiwyg_area_1", "tabName": "规格/交期", "tabHtml": ['specificationsHtml', 'daysToShipHtml']
        }, {"tabId": "wysiwyg_area_2", "tabName": "价格", "tabHtml": ['priceListHtml']}, {
            "tabId": "wysiwyg_area_3", "tabName": "概述/特性", "tabHtml": ['overviewHtml', 'exampleHtml', 'generalHtml']
        }, {"tabId": "wysiwyg_area_4", "tabName": "追加工", "tabHtml": ['alterationHtml']},];
    } else if (tabType == 6) {
        tabList = [{
            "tabId": "tabList_basicInfo",
            "tabName": "基本信息",
            "tabHtml": ['productDescriptionHtml', 'specificationsHtml', 'daysToShipHtml']
        }, {"tabId": "wysiwyg_area_2", "tabName": "价格", "tabHtml": ['priceListHtml']}, {
            "tabId": "wysiwyg_area_3", "tabName": "概述/特性", "tabHtml": ['overviewHtml', 'exampleHtml', 'generalHtml']
        }, {"tabId": "wysiwyg_area_4", "tabName": "追加工", "tabHtml": ['alterationHtml']},];
    } else if (tabType == 7) {
        tabList = [{
            "tabId": "tabList_basicInfo", "tabName": "基本信息", "tabHtml": ['productDescriptionHtml']
        }, {"tabId": "wysiwyg_area_1", "tabName": "规格/价格", "tabHtml": ['specificationsHtml', 'daysToShipHtml']}, {
            "tabId": "wysiwyg_area_2",
            "tabName": "特征/使用事例",
            "tabHtml": ['overviewHtml', 'generalHtml', 'exampleHtml']
        }, {"tabId": "wysiwyg_area_3", "tabName": "追加工/追加编码", "tabHtml": ['alterationHtml']},];
    } else if (tabType == 8) {
        tabList = [{
            "tabId": "tabList_basicInfo",
            "tabName": "基本信息",
            "tabHtml": ['productDescriptionHtml', 'specificationsHtml', 'daysToShipHtml']
        }, {
            "tabId": "wysiwyg_area_2",
            "tabName": "特征/使用事例",
            "tabHtml": ['overviewHtml', 'generalHtml', 'exampleHtml']
        }, {"tabId": "wysiwyg_area_3", "tabName": "追加工/追加编码", "tabHtml": ['alterationHtml']},];
    } else if (tabType == 9) {
        tabList = [{"tabId": "tabList_basicInfo", "tabName": "基本信息", "tabHtml": ['productDescriptionHtml']},];
    } else {
        tabList = ''
    }
    return tabList;
}

//unfit判断
function showUnfitFlag(d, type) {
    var returnBit = parseInt("" + (d.unfitType == 4 ? "1" : "0") // 規格外
        + (d.largeOrderMaxQuantity ? "1" : "0") // 大口
        + d.priceInquiryFlag + d.daysToShipInquiryFlag, 2);
    //	    myApp.alert(returnBit);

    var mask = {
        ship: parseInt("1101", 2),
        price: parseInt("1110", 2),
        shipPrice: parseInt("0011", 2),
        tooMany: parseInt("0100", 2),
        unfit: parseInt("1000", 2)
    }
    if (type == "price") {
        return (returnBit & mask.price) > 0;
    } else {
        return (returnBit & mask.ship) > 0;
    }
}

//金型3Dview
function getSinusParam(paramMap, seriesObj, partNumberIntObj) {
    var params = [];
    var partNumberObj = {};

    partNumberObj.SYCD = partNumberIntObj.partNumberList[0].productCode;
    partNumberObj.alterationSpecList = getAlterationSpecValueList(partNumberIntObj.alterationSpecList);
    partNumberObj.brdCode = seriesObj.brandCode;
    partNumberObj.customer_cd = userInfo.customerCode;
    partNumberObj.dl_format = "";
    partNumberObj.domain = paramMap.domain;
    partNumberObj.environment = paramMap.environment;
    partNumberObj.language = paramMap.language;
    partNumberObj.partNumber = partNumberIntObj.partNumberList[0].partNumber;
    partNumberObj.seriesCode = seriesObj.seriesCode;
    partNumberObj.specValueList = getSpecValueList(partNumberIntObj);
    partNumberObj.typeCode = partNumberIntObj.partNumberList[0].typeCode;

    params.push(partNumberObj);
    var obj = {};
    obj.partNumberList = params;
    return obj;
}

//3d预览数据组合
function getSpecValueList(partNumberIntObj) {
    var specL = [];
    var specList = partNumberIntObj.specList;
    var specValueList = partNumberIntObj.partNumberList[0].specValueList;
    for (var i = 0; i < specList.length; i++) {
        if (!isNull(specList[i].cadSpecCode)) {
            var specO = {};
            specO.specCADCode = specList[i].cadSpecCode;
            $.each(specValueList, function (j, data) {
                if (specList[i].specCode == data.specCode) {
                    specO.specCADValue = data.cadSpecValue || data.specValue || '';
                    return false;
                }
            });
            if (specO.specCADValue == null) {
                specO.specCADValue = "";
            }
            specL.push(specO);
        }
    }
    return specL;
}

//3d追加工选项参数配置
function getAlterationSpecValueList(alterationSpecList) {
    if (isNull(alterationSpecList)) {
        return [];
    }

    var cadSpecList = alterationSpecList.filter(function (item) {
        return item.cadSpecCode && item.selectedFlag == "1";
    });
    return cadSpecList.map(function (spec) {
        var specValues = spec.specValueList.filter(function (specValue) {
            return specValue.selectedFlag == '1';
        });

        var specDic = specValues.map(function (specValue) {
            return specValue.cadSpecValue || specValue.specValue;
        })
        specValues = specDic;

        if (spec.numericSpec && spec.numericSpec.specValue) {
            specValues.push(spec.numericSpec.specValue);
        }

        return {
            specCADCode: spec.cadSpecCode, specCADValue: specValues.join(','),
        }
    });
}


/**
 * 是否是复杂品
 * @param {Object} parentCategoryCodeList
 */
function checkEndCategoryType(topCategoryCode) {
    let topCate = ['mech', 'mech_screw', 'mech_material', 'el_wire', 'el_control', 'fs_machining', 'mold', 'press', 'injection'];
    if (!isNull(topCategoryCode)) {
        let index = $.inArray(topCategoryCode, topCate);
        return index >= 0;
    } else {
        return false;
    }
}

/**
 * 获取分类下尺寸图数据
 * @param {Object} topCategory
 */
function getSeriesDrw(topCategory) {

    if (isDebug) {
        if (isMobileSite) {

        }
    } else {
        if (isIphone()) {

            var param = {
                'misumiAjaxUrl': url, 'misumiAjaxMethod': "GET", 'topCategory': topCategory
            }
            window.webkit.messageHandlers.appAjax.postMessage([JSON.stringify(param), "getSeriesDrwBack"]);
        } else {
            var param = {
                'misumiAjaxUrl': url, 'misumiAjaxMethod': "GET", 'topCategory': topCategory
            }
            misumiJs.appAjax(JSON.stringify(param), "getSeriesDrwBack");
        }
    }
}

function formatDrwImg(seriesCode, path) {
    if (isNull(seriesCode) || isNull(path) || path == "none") {
        return "";
    }
    return "https://www.misumi.com.cn/linked/chn_drw/" + seriesCode + "/" + path;
}

//在库逻辑unfit
function stockQuantityUnfit(num, SQnum) {
    return;
//	if(SQnum!=""){
//		if(num>SQnum){
//			return "非常抱歉，您所订购的商品库存不足，请修改数量继续订购"
//		}
//	}
}

//在库全逻辑
//返回{isUnfit: bool, stockMsg: string},isUnfit==true时,unfit形式显示stockMsg,isUnfit==false时,在库数形式显示stockMsg
function stockLogic(inputCount, data, unfitText, BigOrderdata) {
    var needsInquiry = parseInt("" + (data.unfitType == 4 ? "1" : "0") // 規格外
        + (data.largeOrderMaxQuantity ? "1" : "0") // 大口
        + data.priceInquiryFlag + data.daysToShipInquiryFlag, 2);
    var stockQuantity = data.stockQuantity;
    var largeOrderMaxQuantity = data.largeOrderMaxQuantity;
    var shipType = data.shipType;
    var stockMessage = data.stockMessage;
    var shipDate = data.shipDate;
    var stockType = 0; // 1.在库 2.库存不足 0.不显示
    var stockMsg = "";
    var isUnfit = false;

    if (inputCount >= largeOrderMaxQuantity) {
        // 输入大于大口，只判断unfit
        // 存在unfit情况
        if (needsInquiry > 0 && userInfo != undefined && userInfo.userCode != undefined) {
            if ('' != unfitText) {
                isUnfit = true;
                stockType = 0;
            } else {
                isUnfit = false;
            }
        } else {
            if ('' != unfitText) {
                isUnfit = true;
            } else {
                isUnfit = false;
            }
        }
        return {"isUnfit": isUnfit, "stockMsg": unfitText};
    } else {
        // 输入小于大口，unfit存在，在库不判断
        // 存在unfit情况
        if (needsInquiry > 0 && userInfo != undefined && '' != unfitText) {
            isUnfit = true;
            return {"isUnfit": isUnfit, "stockMsg": unfitText};
        } else {
            if (!isNull(userInfo) && !isNull(userInfo.userCode)) {
                if (shipType == 1) {
                    if (undefined != stockQuantity && null != stockQuantity && stockQuantity > 0) {
                        if (1 == inputCount) {
                            stockType = 1;
                        } else {
                            if (inputCount <= stockQuantity) {
                                // 显示【在库数stockQuantity】
                                stockType = 1
                            } else if (stockQuantity * 0.5 < inputCount && inputCount <= stockQuantity) {
                                //显示【库存紧张】
                                stockType = 1

                            } else {
                                stockType = 2
                                // 显示【非常抱歉，您所订购的商品库存不足，请修改数量继续订购，或者】
                            }


                        }
                    } else {
                        stockType = 2
                    }
                } else {
                    if (!shipType && stockMessage) {
                        stockType = 2;
                    } else if (!shipType && !stockMessage) {
                        stockType = 0;
                    } else {
                        stockType = 0;

                    }
                }

                if (stockType == 1) {
                    if (!stockQuantity) {
                        isUnfit = false;
                        stockMsg = "(库存品)";
                    } else {
                        if (stockQuantity * 0.5 < inputCount && inputCount <= stockQuantity) {
                            isUnfit = false;
                            stockMsg = "库存紧张，库存(" + stockQuantity + "个)";
                        } else {
                            isUnfit = false;
                            stockMsg = "库存(" + stockQuantity + "个)";
                        }

                    }
                } else if (stockType == 2) {
                    if (1 == inputCount) {
                        if (BigOrderdata && BigOrderdata.big_order_max_threshold) {
                            if (inputCount > BigOrderdata.big_order_max_threshold || inputCount < BigOrderdata.big_order_min_threshold) {
                                isUnfit = true;
                                if (data.shipDate != undefined) {
                                    shipdate = data.shipDate;
                                    stockMsg = '非常抱歉。此商品暂时缺货，预计最快出货日为' + shipdate;
                                } else {
                                    stockMsg = '非常抱歉。此商品暂时缺货。';
                                }
                            } else {
                                isUnfit = false
                                stockMsg = ''
                            }
                        } else {
                            isUnfit = true;
                            if (data.shipDate != undefined) {
                                shipdate = data.shipDate;
                                stockMsg = '非常抱歉。此商品暂时缺货，预计最快出货日为' + shipdate;
                            } else {
                                stockMsg = '非常抱歉。此商品暂时缺货。';
                            }
                        }
                    } else {
                        if (stockQuantity == undefined || stockQuantity <= 0) {
                            if (BigOrderdata && BigOrderdata.big_order_max_threshold) {
                                if (inputCount > BigOrderdata.big_order_max_threshold || inputCount < BigOrderdata.big_order_min_threshold) {
                                    isUnfit = true;
                                    if (data.shipDate != undefined) {
                                        shipdate = data.shipDate;
                                        stockMsg = '非常抱歉。此商品暂时缺货，预计最快出货日为' + shipdate;
                                    } else {
                                        stockMsg = '非常抱歉。此商品暂时缺货。';
                                    }
                                } else {
                                    isUnfit = false
                                    stockMsg = ''
                                }
                            } else {
                                isUnfit = true;
                                if (data.shipDate != undefined) {
                                    shipdate = data.shipDate;
                                    stockMsg = '非常抱歉。此商品暂时缺货，预计最快出货日为' + shipdate;
                                } else {
                                    stockMsg = '非常抱歉。此商品暂时缺货。';
                                }
                            }
                        } else {
                            if (BigOrderdata && BigOrderdata.big_order_max_threshold) {
                                if (inputCount > BigOrderdata.big_order_max_threshold || inputCount < BigOrderdata.big_order_min_threshold) {
                                    // 显示【库存不足，请先加入购物车,提交报价单,我们会尽快确认】
                                    isUnfit = true;
                                    stockMsg = "库存不足，请先加入购物车,提交报价单,我们会尽快确认";
                                } else {
                                    isUnfit = false
                                    stockMsg = ''
                                }
                            } else {
                                // 显示【库存不足，请先加入购物车,提交报价单,我们会尽快确认】
                                isUnfit = true;
                                stockMsg = "库存不足，请先加入购物车,提交报价单,我们会尽快确认";
                            }
                        }

                    }
                } else {
                    if (!isUnfit) {
                        isUnfit = false;
                        stockMsg = "(非库存品)";
                    }
                }
            }
        }
    }
    return {"isUnfit": isUnfit, "stockMsg": stockMsg};

    //             if(BigOrderdata && inputCount>=BigOrderdata.big_order_min_threshold && inputCount<BigOrderdata.big_order_max_threshold){
    //                 return {
    //                     "isUnfit": false,
    //                     "stockMsg": ""
    //                 };
    //             }
    //             if (shipType == 1 || shipType == 2) {
    //                 // 在库逻辑
    //                 if (undefined != stockQuantity && null != stockQuantity) {
    //                     if (1 == inputCount) {
    //                         if (0 < stockQuantity) {
    //                             // 显示【在库品】
    //                             isUnfit = false;
    //                             stockType = 1;
    //                             stockMsg = "(库存品)";
    //                         } else {
    //                             // 显示【非常抱歉。此商品暂时缺货，预计最快出货日为shipDate 继续询价】
    //                             isUnfit = true;
    //                             stockType = 2;
    //                             if (data.shipDate != undefined) {
    //                                 shipdate = data.shipDate;
    //                                 stockMsg = '非常抱歉。此商品暂时缺货，预计最快出货日为' + shipdate;
    //                             } else {
    //                                 stockMsg = '非常抱歉。此商品暂时缺货。';
    //                             }
    //                         }
    //                     } else if (inputCount > 1 && inputCount <= stockQuantity * 0.5) {
    //                         // 显示【在库数stockQuantity】
    //                         isUnfit = false;
    //                         stockType = 1;
    //                         stockMsg = "库存(" + stockQuantity + "个)";
    //                     } else if (stockQuantity * 0.5 < inputCount && inputCount <= stockQuantity) {
    //                         //显示【库存紧张】
    //                         isUnfit = false;
    //                         stockType = 1;
    //                         stockMsg = "库存紧张，库存(" + stockQuantity + "个)";
    //                     } else if (inputCount > stockQuantity) {
    //                         // 显示【库存不足，请先加入购物车,提交报价单,我们会尽快确认】
    //                         isUnfit = true;
    //                         stockType = 2;
    //                         stockMsg = "库存不足，请先加入购物车,提交报价单,我们会尽快确认";
    //                     }
    //                 }else{
    //                     isUnfit = false;
    //                     stockMsg = "(非库存品)";
    //                 }
    //             } else {
    //                 //shipType无,stockmsg有
    //                 if (!shipType && stockMessage) {
    //                     stockMsg = stockMessage;
    //                     stockType = 2;
    //                 } else if (!shipType && !stockMessage) {
    //                     //shipType无,stockmsg无
    //                     stockType = 0;
    //                 } else {
    //                     if(shipType == 3 || shipType == 4 || shipType == 5 ){
    //                         isUnfit = false;
    //                         stockMsg = "(非库存品)";
    //                     }else{
    //                         stockType = 0;
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }
    return {"isUnfit": isUnfit, "stockMsg": stockMsg};
}

function goToDetailPage() {
    // const needPayOrder = localStorage.getItem("needPayOrder")
    // if(needPayOrder){
    // 	localStorage.removeItem("needPayOrder")
    // 	window.location.href = jumpUrl + "/static/html/page/orderDetail.html?soNo=" + needPayOrder
    // }
}


// 数量计数器控制类
function QuantityController(options) {
    var _this = this;

    // 配置项
    options = $.extend({
        min: 1, max: 99999, step: 1, maxLength: 5, quantityEl: null, // 计数器的dom元素 - jquery元素
        inputEl: null, // 输入框元素 - jquery元素
        initValue: 1, // 当前的数据值
        onChange: null, // 输入框的change事件
        onFocus: null, // 输入获得焦点事件
        onBlur: null, // 输入框的blur事件
        onError: null, // 验证出错的事件
        onNoError: null, // 验证成功的事件
        onPlusFn: null, // 点击加号
        onMinusFn: null, // 点击减号
        hasTips: true, // 是否显示提示信息
        disabled: false, theme: '', // 主题
        openMinBuyQuantity: false // 购物车校验最小数量规则
    }, options || {});

    Object.keys(options).forEach(function (key) {
        _this[key] = options[key];
    });

    this.bindingValue = "";
    this.quantity = +(options.initValue) || 0;
    this.correctPattern = new RegExp("^[0-9０-９]{1," + options.maxLength + "}$");
    this.errorMessage = "请在数量中填写" + options.min + "到" + options.max + "的数字";
    this.hasError = false;

    Object.defineProperties(this, {
        isNotNaturalNumber: {
            get() {
                return !this.correctPattern.test(this.bindingValue)
            }
        },

        isLessThanMin: {
            get() {
                if (this.openMinBuyQuantity) {
                    return this.isNotNaturalNumber ? false : 0 >= parseInt(this.bindingValue);
                } else {
                    return this.isNotNaturalNumber ? false : this.min >= parseInt(this.bindingValue);
                }
            }
        },

        isMoreThanMax: {
            get() {
                return this.isNotNaturalNumber ? false : this.max <= parseInt(this.bindingValue);
            }
        },

        // 减按钮disabled状态
        isDisabledOfMinus: {
            get() {
                return this.disabled || this.isNotNaturalNumber || this.isLessThanMin
            }
        },

        // 加按钮disabled状态
        isDisabledOfPlus: {
            get() {
                return this.disabled || this.isNotNaturalNumber || this.isMoreThanMax
            }
        },

        // 商品数量异常
        isWarning: {
            get() {
                return this.theme === QuantityController.Theme.Warning
            }
        }, // 大口纳短
        isBlueing: {
            get() {
                return this.theme === QuantityController.Theme.isBlueing
            }
        },

        isExceedMaxValueWithStepAdd: {
            get() {
                var numberValue = parseInt(this.bindingValue);
                return numberValue + this.step - (numberValue % this.step) > this.max;
            }
        }
    });

    // 生成实例时，自动调用初始化方法
    // 前提是new实例时就给到了元素，也有可能是后给出的，这时就不能进行初始化了
    if (options.quantityEl) this.init();
}

// 设置主题
QuantityController.Theme = {
    Warning: "warning", Default: "default", isBlueing: "blueing"
};
QuantityController.prototype = $.extend(QuantityController.prototype, {
    // 初始化
    init: function () {
        this.setInputEl();
        this.setBindingValue(this.initValue);
        this.setQuantity(this.initValue);
        this.addClickToBtn();
        this.addFocusToInput();
        this.addInputToInput();
        this.addBlurToInput();
        this.addKeydownToInput();
        this.addKeypressToInput();
        this.setExceptionStatus();
        this.showErrorMsg();
    },

    setQuantityEl: function ($el) {
        this.quantityEl = $el;
        if (this.quantityEl) this.init();
    },

    setInputEl: function () {
        // 如果已经存在，或者 计数器元素不存在时退出
        if (this.inputEl || !this.quantityEl) return this.inputEl;
        this.inputEl = this.quantityEl.find('.number-input');
        return this.inputEl;
    },

    setQuantity: function (numb) {
        if (numb === undefined || numb === null) return false;
        numb = typeof numb === 'number' ? numb : Number(numb);
        if (isNaN(numb)) return false;
        this.quantity = numb;
    },

    setBindingValue: function (val) {
        if (val === undefined || val === null) return false;
        this.bindingValue = typeof val === 'string' ? val : String(val);
        this.setInputElVal(this.bindingValue);
        this.setDisabledToBtn();
    },

    setHasError: function (bool) {
        this.hasError = typeof bool !== 'boolean' ? false : bool;
        this.showErrorMsg();
        this.setExceptionStatus();
    },

    setInputElVal: function (val) {
        var oldVal = this.inputEl.val();
        if (oldVal === val) return false;
        this.inputEl.val(val);
    },

    setTheme: function (theme) {
        this.theme = theme || QuantityController.Theme.Default;
    },

    setDisabled: function (disabled) {
        this.disabled = disabled || false;
    },

    // 为加减按钮注册事件
    addClickToBtn: function () {
        var _this = this;
        this.quantityEl.off('click').on('click', '.minus-btn, .plus-btn', function (ev) {
            if (_this.disabled) return; // 禁止点击
            ev.stopPropagation();
            var type = $(ev.currentTarget).data('type');
            switch (type) {
                case 'minus':
                    _this.clickDecrement();
                    break;
                case 'plus':
                    _this.clickIncrement();
                    break;
                default:
                    break;
            }
            return false;
        })
    },

    // 为输入框注册input事件
    addInputToInput: function () {
        var _this = this;
        this.inputEl.off("input").on("input", function () {
            var val = $(this).val();
            _this.setBindingValue(val);
        })
    },

    // 为输入框注册焦点事件
    addFocusToInput: function () {
        var _this = this;
        this.inputEl.off("focus").on("focus", function () {
            if (_this.disabled) { // 当禁止输入时，直接失焦
                _this.inputEl.blur();
                return false;
            }

            // 清空输入框内的值
            _this.inputEl.val("");
            _this.emitFocus();
        })
    },

    // 为输入框注册失焦事件
    addBlurToInput: function () {
        var _this = this;
        this.inputEl.off("blur").on("blur", function () {
            if (_this.disabled) return false;
            var value = _this.inputEl.val();
            // 如果当前输入值内没有输入任何值，失焦时还原为原来的值
            if (value === "") {
                _this.inputEl.val(_this.bindingValue);
            }

            // 是不是以0开头
            if (/^0\d+$/.test(value)) {
                _this.setBindingValue(parseInt(value));
            }

            if (!_this.isNotNaturalNumber) {
                _this.setBindingValue(_this.toHalfWidthNumber(_this.bindingValue));
            }
            _this.reflect();
            _this.emitBlur();
        })
    },

    // 为输入框注册keydown事件
    addKeydownToInput: function () {
        var _this = this;
        this.inputEl.off("keydown").on("keydown", function (ev) {
            if (ev.key === `Enter`) {
                if (!_this.isNotNaturalNumber) {
                    _this.setBindingValue(_this.toHalfWidthNumber(_this.bindingValue));
                }
                _this.inputEl.trigger('blur');
                // _this.reflect();
            }
        })
    },

    // 为输入框注册keypress事件
    addKeypressToInput: function () {
        var _this = this;
        this.inputEl.off("keypress").on("keypress", function (ev) {
            // 保证只能输入数字
            var isNumber = ev.keyCode >= 48 && ev.keyCode <= 57;
            var val = $(this).val();
            if (!isNumber || val.length >= _this.maxLength) {
                ev.preventDefault ? ev.preventDefault() : event.returnValue = false;
                return isNumber;
            }
        })
    },

    // 减按钮事件处理函数
    clickDecrement: function () {
        if (this.isNotNaturalNumber || this.isLessThanMin) return false;
        var numberValue = parseInt(this.bindingValue);
        var open = numberValue !== this.min
        var correctedStep = open ? (numberValue % this.step > 0 ? numberValue % this.step : this.step) : this.min;
        this.setBindingValue(numberValue - correctedStep);
        this.reflect();
        this.onMinusFn && this.onMinusFn(this.bindingValue);

    },

    // 加按钮事件处理函数
    clickIncrement: function () {
        if (this.isNotNaturalNumber || this.isMoreThanMax || this.isExceedMaxValueWithStepAdd) return false;
        var numberValue = parseInt(this.bindingValue);
        // NODE: 这里可能转换为一个绝对值比较好，可以保证一直是向上加的状态
        var correctedStep = Math.max(numberValue + (this.step - (numberValue % this.step)), this.min)
        this.setBindingValue(correctedStep);
        this.reflect();
        this.onPlusFn && this.onPlusFn(this.bindingValue);
    },

    // 校验输入框内的值
    validate: function (value) {
        this.setHasError(false);
        // 输入值不是自然数时
        if (this.isNotNaturalNumber) {
            this.setHasError(true);
            return;
        }
        // this.min = 1

        var numberValue = parseInt(value);

        // 超出极限值(min~max)
        // if (this.min > numberValue || this.max < numberValue) {
        //     if (numberValue !== 0) {
        //         this.setHasError(true);
        //     }
        // }
        // // 非步长的倍数
        // if (numberValue % this.step !== 0) {
        //     this.setHasError(true);
        // }
    },

    // 通知外部组件
    reflect: function () {
        // 校验输入值
        this.validate(this.bindingValue);
        if (this.hasError) {
            this.emitError();
            return;
        }
        // 触发无错误通知
        this.emitNoError();

        var inputQuantity = parseInt(this.bindingValue);
        if (this.quantity === inputQuantity) {
            return;
        }
        this.setQuantity(this.bindingValue);
        this.emitChange();
    },

    // 全角转半角
    toHalfWidthNumber: function (value) {
        if (typeof value !== 'string') value = String(value);
        return value.replace(/[０-９]/g, function (c) {
            return String.fromCharCode(c.charCodeAt(0) - 65248)
        });
    },

    // 显示错误提示
    showErrorMsg: function () {
        if (!this.hasTips) return;
        var msg = this.hasError ? this.errorMessage : "";
        this.quantityEl.find('.message-box').toggle(!!msg).text(msg);
    },

    // 设置加减按钮的disabled状态
    setDisabledToBtn: function () {
        this.quantityEl.find('.minus-btn').toggleClass('is-disabled', this.isDisabledOfMinus);
        this.quantityEl.find('.plus-btn').toggleClass('is-disabled', this.isDisabledOfPlus);
    },

    // 设置异常状态
    setExceptionStatus: function () {
        this.quantityEl.toggleClass('is-exception', this.isWarning);
        this.quantityEl.toggleClass('is-blue', this.isBlueing);
        this.quantityEl.toggleClass('is-error', this.hasError);
    },

    emitFocus: function () {
        this.onFocus && this.onFocus();
    },

    emitBlur: function () {
        this.onBlur && this.onBlur(this.quantity);
    },

    emitError: function () {
        this.onError && this.onError(true);
    },

    emitNoError: function () {
        this.onNoError && this.onNoError(false);
    },

    emitChange: function () {
        this.onChange && this.onChange(this.quantity);
    },
});


// 解析json数据
function msmParseJSON(result) {
    // return (result && typeof result === "string") ? $.parseJSON(result) : result;
    try {
        return $.parseJSON(result);
    } catch (e) {
        return result;
    }
}

function browserType() {
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    }
    ; //判断是否Opera浏览器
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    } //判断是否Firefox浏览器
    if (userAgent.indexOf("Chrome") > -1) {
        return "Chrome";
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    } //判断是否Safari浏览器
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    }
    ; //判断是否IE浏览器
}

var ObjectUtil = {
    fromList: function (list, extractor) {
        if (!list.length) {
            return {};
        }

        var map = {};
        list.forEach(function (item) {
            map[extractor(item)] = item;
        });
        return map;
    }
}

function radioSelected(jqObj, value) {
    jqObj.each(function () {
        if ($(this).val() != value) {
            $(this).removeAttr("checked");
        } else {
            $(this).prop("checked", true);
        }
    });
}

function is_weixin() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

function gotoWechat() {
    //埋点：点击微信绑定账号
    sensors.track('WeChatClick', {});
    window.location.href = "/static/html/page/bindWechat.html"
}

// logUtil 日志发送
var LogUtil = {
    noStackTraceMessage: "no stack trace", errorHandlerTypeAppError: "app-error",

    // 获取调用栈
    getStackTrace: function (error) {
        return error && error instanceof Error && error.stack ? error.stack : LogUtil.noStackTraceMessage;
    },

    getMessage: function (message, type, error) {
        var errorToSend = error;

        return [type ? type : ``, userInfo ? userInfo.customerCode : ``, userInfo ? userInfo.userCode : ``, location.href, message, errorToSend ? String(errorToSend) : ``, window.navigator.userAgent, LogUtil.getStackTrace(errorToSend),].join(`\t`);
    },

    sendMessage: function (logLevel, message, type, error) {
        var sendMessage = LogUtil.getMessage(message, type, error);
        var param = {
            logLevel: logLevel || "ERROR", message: sendMessage
        };
        var action = WebUtils.preReferPCApiParam(upr_api_log, true);
        WebUtils.ajaxPostSubmit(action, JSON.stringify(param), function (result) { //success
        }, function (error) { //error
        }, function (XHR, TS) { //complete
        });
    },

    info: function (message) {
        LogUtil.sendMessage(`INFO`, message);
    },

    warn: function (message, error, options) {
        options = options || {type: ""};
        if (error || options) {
            // error.tsで警告レベルのログが送信された場合
            LogUtil.sendMessage(`WARN`, message, // NOTE: 引数の定義上、messageは必ずstring
                options && options.type ? options.type : LogUtil.errorHandlerTypeAppError, error);
        } else if (message instanceof Error) {
            // Errorオブジェクト
            LogUtil.sendMessage(`WARN`, message.message);
        } else if (typeof message === `string`) {
            // 文字列
            LogUtil.sendMessage(`WARN`, message);
        } else {
            // 上記以外
            LogUtil.sendMessage(`WARN`, String(message));
        }
    },

    error: function (message, error, options) {
        this.sendMessage(`ERROR`, message, options && options.type ? options.type : LogUtil.errorHandlerTypeAppError, error);
    }


};

// 防抖
function debounceFn(fn, delay) {
    var timer = null;
    return () => {
        clearTimeout(timer);
        timer = setTimeout(fn, delay || 300)
    };
}


// 输入框的键盘事件，（主要是针对安卓软键盘的enter键 - 安卓的enter键，不能使输入框失去焦点）
function handleKeypressToInput(ev) {
    var $target = $(ev.target);
    if (ev.keyCode === 13 || ev.key === "Enter") {
        $target.trigger('blur');
    }
}


function SensorsSearchPage(detail) {
    if (detail.detail.seriesList.length == 0) {
        return
    } else {
        var param = {
            inner_cd: '',
            series_cd: detail.detail.seriesList[0].seriesCode,
            series_name: detail.detail.seriesList[0].seriesName,
            brand_cd: detail.detail.seriesList[0].brandCode,
            brand_name: detail.detail.seriesList[0].brandName
        }

    }
    var len = detail.detail.seriesList[0].categoryList.length;
    for (let i = 0; i < 6; i++) {
        if (detail.detail.seriesList[0].categoryList[i] === undefined) {
            param[`category${i}_cd`] = ''
            param[`category${i}_name`] = ''
        } else {
            param[`category${i}_cd`] = detail.detail.seriesList[0].categoryList[i].categoryCode
            param[`category${i}_name`] = detail.detail.seriesList[0].categoryList[i].categoryName
        }
        param[`category${len}_cd`] = detail.detail.seriesList[0].categoryCode
        param[`category${len}_name`] = detail.detail.seriesList[0].categoryName
    }
    delete param.category0_cd
    delete param.category0_name
    return param
}

function sensorsProductPage(card) {
    var param = {}
    try {
        param = {
            inner_cd: '',
            series_cd: card.seriesCode,
            series_name: card.seriesName,
            brand_cd: card.brandCode,
            brand_name: card.brandName
        }
        var len = card.categoryList.length;
        for (let i = 0; i < 6; i++) {
            if (card.categoryList[i] === undefined) {
                param[`category${i}_cd`] = ''
                param[`category${i}_name`] = ''
            } else {
                param[`category${i}_cd`] = card.categoryList[i].categoryCode
                param[`category${i}_name`] = card.categoryList[i].categoryName
            }
            param[`category${len}_cd`] = card.categoryCode
            param[`category${len}_name`] = card.categoryName
        }
        delete param.category0_cd
        delete param.category0_name
    } catch (e) {

    }

    return param
}

function SaObj(event) {
    let context = parseUrlQuery()
    if (typeof context == 'undefined') {
        var param = {
            product_cd: '', inner_cd: '', series_cd: '', series_name: '', brand_cd: '', brand_name: '', vsd: ''
        }
    } else {
        var {detail} = context.param;
        if (event) {
            var param = {
                inner_cd: '',
                series_cd: detail.seriesList[0].seriesCode,
                series_name: detail.seriesList[0].seriesName,
                brand_cd: detail.seriesList[0].brandCode,
                brand_name: detail.seriesList[0].brandName,
                vsd: ''
            }
        } else {
            var param = {
                product_cd: '',
                inner_cd: '',
                series_cd: detail.seriesList[0].seriesCode,
                series_name: detail.seriesList[0].seriesName,
                brand_cd: detail.seriesList[0].brandCode,
                brand_name: detail.seriesList[0].brandName,
                vsd: ''
            }
        }
        var len = detail.seriesList[0].categoryList.length;
        for (let i = 0; i < 6; i++) {
            if (detail.seriesList[0].categoryList[i] === undefined) {
                param[`category${i}_cd`] = '';
                param[`category${i}_name`] = '';
            } else {
                param[`category${i}_cd`] = detail.seriesList[0].categoryList[i].categoryCode;
                param[`category${i}_name`] = detail.seriesList[0].categoryList[i].categoryName;
            }
            param[`category${len}_cd`] = detail.seriesList[0].categoryCode;
            param[`category${len}_name`] = detail.seriesList[0].categoryName;
        }
    }

    delete param.category0_cd
    delete param.category0_name
    return param
}

function sendSa(option) {
    var event = option.event;
    var sensorsObj = SaObj(event);
    var newObj = {};
    if (getPageName() == 'productInfo.html') {
        if (typeof itemPriceObj != 'undefined') {
            sensorsObj.vsd = itemPriceObj.priceList ? gettVolumeDiscountDaysShip(itemPriceObj.priceList[0].daysToShip) : '';
            sensorsObj.inner_cd = itemPriceObj.priceList ? itemPriceObj.priceList[0].innerCode : '';
            sensorsObj.product_cd = itemPriceObj.priceList ? itemPriceObj.priceList[0].partNumber : '';
        }
    } else if (getPageName() == 'complexProduct.html' || getPageName() == 'complexProductChoosePartNum.html') {
        if (typeof partNumObj != 'undefined') {
            sensorsObj.vsd = $('#complexInfoDaysToShip').html() ? $('#complexInfoDaysToShip').html() : '';
            sensorsObj.inner_cd = partNumObj.partNumberList ? partNumObj.partNumberList[0].innerCode : '';
            sensorsObj.product_cd = $('#complexDetailSelectPartNum').html() ? $('#complexDetailSelectPartNum').html() : '';
            if (typeof partNumObj.partNumberList != 'undefined' && partNumObj.partNumberList[0].partNumber != $('#complexDetailSelectPartNum').html()) {
                sensorsObj.inner_cd = '';
            }
        }
    } else if (getPageName() == 'notOpenProduct.html') {
        sensorsObj.vsd = $('#notopenInfoDaysToShip').html() ? $('#notopenInfoDaysToShip').html() : '';
        sensorsObj.product_cd = $('#notopenDetailSelectPartNum').html() ? $('#notopenDetailSelectPartNum').html() : '';
    }
    if (option.event == 'ElevatorbarClick' || option.event == 'ProductCatalogClick') {
        delete sensorsObj.vsd
    }
    delete option.event;
    Object.assign(newObj, sensorsObj, option);
    sensors.track(event, newObj)
}

/**
 * 获取当前页面的名称（html的文件名）
 * @param isIncludeHtml true -> 返回的名称中包含.html, false -> 不包含
 * @param pathname 页面路径
 * @returns {any}
 */
function getPageName(isIncludeHtml, pathname) {
    // 整个路径是以/分隔，以下拿到最后一个
    var pageName = (pathname || window.location.pathname).split("/").pop();
    // 如果访问的不是html页面，就直接返回空字符
    return /\.html$/.test(pageName) ? isIncludeHtml ? pageName : pageName.replace(".html", "") : "";
}

// 判断当前页面是否为指定页面
function judgePageName(name, pathname) {
    name = name || "";
    let pageName = getPageName(false, pathname);
    return pageName.toLocaleLowerCase() === name.toLocaleLowerCase();
}

// 无权限的跳转规则
function noAuthJumpAction() {
    // 没有权限时，返回到上一页，如果没有上一页，则返回到个人中心
    if (history.length) {
        history.back();
    } else {
        jumpUprPage('my.html')
    }
}

function getOrderList() {
    userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        // loginObj.showLoginDialog();
        return;
    } else {
        // loadingClass.showLoading();
        var param = {
            page: 1, pageSize: 60,
            orderDateFrom: dayjs().add(-3, `month`).format(`YYYY/MM/DD`),
            orderDateTo: dayjs().format(`YYYY/MM/DD`),
        }

        if (globalIndex != "") {
            if (globalIndex !== 'all') {
                param.orderSlipGroupStatus = globalIndex
            }
        }

        if (globalIndex == "2") {
            sensors.track("PersonalPageClick", {button_type: "我的订单", button_name: "处理中"});
        } else if (globalIndex == "3") {
            sensors.track("PersonalPageClick", {button_type: "我的订单", button_name: "待支付"});
        } else if (globalIndex == "4") {
            sensors.track("PersonalPageClick", {button_type: "我的订单", button_name: "待发货"});
        } else if (globalIndex == "5") {
            sensors.track("PersonalPageClick", {button_type: "我的订单", button_name: "已发货"});
        }

        jumpUprPage('orderList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : ""
        })
    }
}

//获取订单列表数据回调
function getOrderListBack(code, result) {
    loadingClass.closeLoading();
    if (parseInt(code) == 200) {
        var data = $.parseJSON(result);
        sessionStorage.setItem("namekey", JSON.stringify(data))
        jumpUprPage('orderList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : "",
        })
    } else if (parseInt(code) < 0) {
        myApp.alert(result, "错误信息");
    } else if (parseInt(code) == 401) {
    } else {
        var data = $.parseJSON(result);
        if (data.errorList[0].errorMessage.indexOf("没有权限") > -1) {
            if (!isNull(userInfo) && !isNull(userInfo.customerCode)) {
                myApp.alert(data.errorList[0].errorMessage, "错误信息");
            } else {
                myApp.popup(".popup-upOrBind_grade");
            }
        } else if (data.errorList[0].errorMessage.indexOf("sessionId为必填项") > -1) {
        } else {
            if (data != undefined && data.errorList != undefined && data.errorList.length > 0) {
                if (data.errorList[0].errorCode != ECODE_API000300) {
                    myApp.alert(data.errorList[0].errorMessage, "错误信息");
                }
            }
        }
    }
}

// 订单生成
function gotoorderComplete(slipNumberList, slipTypeList) {
    jumpUprPage('orderComplete.html', {
        slipNumberList: slipNumberList, slipTypeList: slipTypeList
    })
}

// 报价单生成
function gotoquoteComplete(slipNumberList, slipTypeList) {
    jumpUprPage('quoteComplete.html', {
        slipNumberList: slipNumberList, slipTypeList: slipTypeList
    })
}

// 订单完成，跳转报价详情
function gotoQuoteDetail(slipNumber, from) {
    QuoteFinishPageClick('报价生成', '查看报价单详情')
    if (from == 'quote') {
        sensors.track('QuotationDetailView', {source_page: "报价完成页-查看报价详情"})
    } else {
        sensors.track('QuotationDetailView', {source_page: "订单完成页-查看报价详情"})
    }
    jumpUprPage('quoteListDetail.html', {
        quoteSlipNumber: slipNumber, from: from
    })


}

// 跳转订单详情
function gotoOrderDetail(slipNumber) {
    // 神策-OrderDetailView-搜索栏发起搜索
    if (judgePageName("orderComplete")) {
        sensors.track('OrderDetailView', {source_page: "订单完成页-查看订单详情"});
    }
    jumpUprPage('orderListDetail.html', {
        orderSlipNumber: slipNumber, from: true
    })
}

//报价列表
function gotoQuoteList() {
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        return;
    } else {
        // loadingClass.showLoading();
        var param = {
            page: 1, pageSize: 60,
            quoteDateFrom: dayjs().add(-3, `month`).format(`YYYY/MM/DD`),
            quoteDateTo: dayjs().format(`YYYY/MM/DD`),
        }
        if (globalIndex !== 'all') {
            param.quoteSlipGroupStatus = globalIndex
        }
        jumpUprPage('quotationList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : ""
        })
        if (globalIndex == "2") {
            sensors.track("PersonalPageClick", {button_type: "我的报价", button_name: "处理中"});
        } else if (globalIndex == "3") {
            sensors.track("PersonalPageClick", {button_type: "我的报价", button_name: "可订购"});
        }
    }
}


//获取退货列表数据
function getRefundList() {
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        // showLoginDialog();
        return;
    } else {
        loadingClass.showLoading();
        // var param = {
        // 	applyType: 1,
        //     pagingStartRowNum: 1,
        // 	pagingOnePageCount: 60,
        // 	progressOffLineDispFlg : false,
        //     applyDayFrom: dayjs().add(-2, `month`)
        //         .startOf(`month`)
        //         .format(`YYYY/MM/DD`),
        // 	applyDayTo: dayjs().format(`YYYY/MM/DD`),
        // }

        // if (globalIndex != "") {
        //     if (globalIndex !== 'all') {
        //         param.orderSlipGroupStatus = globalIndex
        //     }
        // }
        sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "我的退货"});
        jumpUprPage('refundList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : ""
        })

    }
}

//获取退货列表数据回调
function getRefundListBack(code, result) {
    loadingClass.closeLoading();
    if (parseInt(code) == 200) {
        var data = $.parseJSON(result);
        sessionStorage.setItem("refundKey", JSON.stringify(data))
        jumpUprPage('refundList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : "",
        })
    } else if (parseInt(code) < 0) {
        myApp.alert(result, "错误信息");
    } else if (parseInt(code) == 401) {
        // showLoginDialog();
    } else {
        var data = $.parseJSON(result);
        if (data.errorList[0].errorMessage.indexOf("没有权限") > -1) {
            if (!isNull(userInfo) && !isNull(userInfo.customerCode)) {
                myApp.alert(data.errorList[0].errorMessage, "错误信息");
            } else {
                myApp.popup(".popup-upOrBind_grade");
            }
        } else if (data.errorList[0].errorMessage.indexOf("sessionId为必填项") > -1) {
            showLoginDialog();
        } else {
            if (data != undefined && data.errorList != undefined && data.errorList.length > 0) {
                if (data.errorList[0].errorCode != ECODE_API000300) {
                    myApp.alert(data.errorList[0].errorMessage, "错误信息");
                }
            }
        }
    }
}

//获取换货列表
function getExchangeList() {
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        // showLoginDialog();
        return;
    } else {
        loadingClass.showLoading();
        var param = {
            applyType: 2,
            pagingStartRowNum: 1,
            pagingOnePageCount: 60,
            progressOffLineDispFlg: false,
            applyDayFrom: dayjs().add(-2, `month`)
                .startOf(`month`)
                .format(`YYYY/MM/DD`),
            applyDayTo: dayjs().format(`YYYY/MM/DD`),
        }
        if (globalIndex != "") {
            if (globalIndex !== 'all') {
                param.orderSlipGroupStatus = globalIndex
            }
        }
        sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "我的换货"});

        jumpUprPage('exchangeList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : ""
        })
    }
}

//获取换货列表数据回调
function getExchangeListBack(code, result) {
    loadingClass.closeLoading();
    if (parseInt(code) == 200) {
        var data = $.parseJSON(result);
        jumpUprPage('exchangeList.html', {
            orderSlipGroupStatus: globalIndex ? globalIndex : "",
        })
    } else if (parseInt(code) < 0) {
        myApp.alert(result, "错误信息");
    } else if (parseInt(code) == 401) {
        // showLoginDialog();
    } else {
        var data = $.parseJSON(result);
        if (data.errorList[0].errorMessage.indexOf("没有权限") > -1) {
            if (!isNull(userInfo) && !isNull(userInfo.customerCode)) {
                myApp.alert(data.errorList[0].errorMessage, "错误信息");
            } else {
                myApp.popup(".popup-upOrBind_grade");
            }
        } else if (data.errorList[0].errorMessage.indexOf("sessionId为必填项") > -1) {
            showLoginDialog();
        } else {
            if (data != undefined && data.errorList != undefined && data.errorList.length > 0) {
                if (data.errorList[0].errorCode != ECODE_API000300) {
                    myApp.alert(data.errorList[0].errorMessage, "错误信息");
                }
            }
        }
    }
}


// 跳转新注册
function gotoRegisterNew() {
    window.location.href = "/static/html/page/register_step1_search.html"
}

// 购物流程发送神策数据
function sa_AddCart(eventName, eventParams1, eventParams2) {

    let trackParam = {}


    if (eventParams1.categoryList && eventParams1.categoryList.length >= 0) {
        //针对再次报价category数据反转做更改
        if (eventParams1.categoryList[eventParams1.categoryList.length - 1]) {
            if (eventParams1.categoryList[eventParams1.categoryList.length - 1].categoryCode.indexOf('_') != -1 || eventParams1.categoryList[eventParams1.categoryList.length - 1].categoryCode.length < 11) {
                eventParams1.categoryList.reverse()
            }

            if (eventParams1.categoryList[0].categoryCode.indexOf('_') != -1 || eventParams1.categoryList[0].categoryCode.length < 11) {
                eventParams1.categoryList.shift()
            }
        }
        for (let i = 0; i < 5; i++) {
            if (i < eventParams1.categoryList.length) {
                trackParam['category' + (i + 1) + '_cd'] = eventParams1.categoryList[i].categoryCode
                trackParam['category' + (i + 1) + '_name'] = eventParams1.categoryList[i].categoryName
            } else if (i == eventParams1.categoryList.length) {
                trackParam['category' + (i + 1) + '_cd'] = eventParams1.categoryCode ? eventParams1.categoryCode : ''
                trackParam['category' + (i + 1) + '_name'] = eventParams1.categoryName ? eventParams1.categoryName : ''
            } else {
                trackParam['category' + (i + 1) + '_cd'] = ''
                trackParam['category' + (i + 1) + '_name'] = ''
            }
        }
    }

    // seriosObj中无法获取的值，如果有就添加上
    if (eventParams2 != undefined) {
        Object.keys(eventParams2).map((item, index) => {
            trackParam[item] = Object.values(eventParams2)[index]
        })
    }

    sensors.track(eventName, trackParam)
}

// 提供lp校验是否登录
function checkIsLoginForLP() {
    if (isNull(localStorage.getItem("userInfo"))) {
        return false
    } else {
        return true;
    }
}

//跳转注册
function LpgotoRegist() {
    sendGa("action", "", "LpLogin", "register");
    window.location.href = jumpUrl + "/static/html/page/registStep1.html";
}

//打开企业信息页面
function goQyInfo() {
    sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "企业信息"});
    // backIndex = 'myPage';
    localStorage.setItem('backIndex', 'myPage')
    // 企业信息是否存在
    getCustomerInfo(function (code, result) {
        if (!isNull(customerInfo.customerCode)) {
            jumpUprPage('enterpriseInformation.html')
        } else {
            jumpUprPage('enterpriseInfoNoPrefect.html')
        }
    })

}

//打开发票管理
function goInvoiceSetPage() {
    sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "开票信息"});
    jumpUprPage('invoiceSet.html', {
        mode: 'page-view'
    })
}

//打开通知设定
function goNoticeSetPage() {
    sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "通知设定"});
    jumpUprPage('noticeSet.html')
}

function gotoProductEvalMineList(type) {
    //神策埋点
    if (type) {
        sensors.track("PersonalPageClick", {button_type: "下方栏", button_name: "我的点评"});
    } else {
        sensors.track("PersonalPageClick", {button_type: "上方栏", button_name: "待点评"});
    }
    jumpUprPage('productEvaluationMineList.html', {
        type: 1
    })
}

//返回内嵌页面
function closePage(pageClass) {
    $(`.${pageClass}`).removeClass('page-in')
}

// 换绑手机号返回
function goBackChangePhone() {
    let changePhone = parseUrlQuery().changePhone
    let backUrl = parseUrlQuery().backUrl
    if (changePhone && backUrl) {
        window.location.href = backUrl
    } else {
        closePage('change-phone-page')
    }
}

$('body').on('focus', '.edit-item input', function () {
    isNeedCheck = true
    $(this).parents('.edit-item').find('.value').css('border-color', '#003399');
})

// 失去焦点隐藏 del-icon
$('body').on('blur', '.edit-item .need-del-val-input', function () {
    $(this).parents('.edit-item').find('.del-icon').hide()
})
// 失去焦点边线恢复
$('body').on('blur', '.edit-item .need-del-val-input', function () {
    $(this).parents('.edit-item').find('.value').css('border-color', '#F3F3F3');
})

//判断获得焦点输入框是否有值 有值显示del-icon
$('body').on('focus', '.edit-item .need-del-val-input', function () {
    $(this).parents('.edit-item').find('.success-icon').hide();
    $(this).parents('.edit-item').find('.error-icon').hide();
    if (isNull($(this).val())) {
        $(this).parents('.edit-item').find('.del-icon').hide()
    } else {
        $(this).parents('.edit-item').find('.del-icon').show()
    }
})
$('body').on('mousedown', '.no-blur', function (e) {
    e.preventDefault();
})
$('body').on('mousedown', '.edit-item .del-icon', function (e) {
    $(this).parents('.edit-item').find('input').val('')
    $(this).parents('.edit-item').find('.success-icon').hide();
    $(this).parents('.edit-item').find('.del-icon').hide();
    $(this).parents('.edit-item').find('.error-icon').hide();
    //同步vue v-model值
    $(this).parents('.edit-item').find('input')[0].dispatchEvent(new Event('input'));
    e.preventDefault();
});

//input输入判断是否显示del
$('body').on('input', '.edit-item .need-del-val-input', function () {
    var iptValue = $(this).val();
    if (iptValue) {
        $(this).parents('.edit-item').find('.del-icon').show();
    } else {
        $(this).parents('.edit-item').find('.del-icon').hide();
        $(this).parents('.edit-item').find('.success-icon').hide();
        $(this).parents('.edit-item').find('.error-icon').hide();
    }
})


//清空icon和边线恢复
function cssClear(element) {
    element.parents('.edit-item').find('.success-icon').hide();
    element.parents('.edit-item').find('.error-icon').hide();
    element.parents('.value').css('borderBottom', '1px solid #F3F3F3');
}

//验证邮箱 失去焦点
$('body').on('blur', '.edit-item .need-check-email-input', function () {
    if (isNeedCheck) {
        let reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;
        let iptvalue = $(this).val();
        $(this).parents('.edit-item').find('.del-icon').hide();
        // 有输入内容情况
        // 有输入内容情况
        if (iptvalue) {
            // 验证
            if (!reg.test(iptvalue)) {
                //验证失败
                new MessageAlert({
                    icon: 'error', msg: '请输入正确的邮箱地址'
                })
                cssError($(this))
            } else {
                cssSuccess($(this))
            }
        } else {
            new MessageAlert({
                icon: 'error', msg: '请输入邮箱地址'
            })
            cssError($(this))
        }
    }

})
//验证CC邮箱 失去焦点 只需要判断格式是否正确
$('body').on('blur', '.edit-item .need-check-cc-email', function () {
    if (isNeedCheck) {
        let reg = /^[a-zA-Z0-9_-]+([-_.][a-zA-Z0-9_-]+)*@([a-zA-Z0-9_-]+[-.])+[a-zA-Z0-9_-]{2,5}$/;
        let iptvalue = $(this).val();
        $(this).parents('.edit-item').find('.del-icon').hide();
        let registerFlag = window.location.href.indexOf('register.html')
        // 有输入内容情况
        if (iptvalue) {
            // 验证
            if (!reg.test(iptvalue)) {
                //验证失败
                new MessageAlert({
                    icon: 'error', msg: '请输入正确的邮箱地址'
                })
                cssError($(this))
            } else {
                if (registerFlag > 0) {
                    cssSuccess($(this), true)
                } else {
                    cssSuccess($(this))
                }
            }
        } else {
            new MessageAlert({
                icon: 'error', msg: '请输入邮箱地址'
            })
            cssError($(this))
        }
    }
})
//格式化手机号344
// $('body').on('input', '.edit-item .need-check-phone-input', function () {
//
//     let str = $(this).val().toString().replace(/[^\d]/g, '');
//     let len = str.length;
//     switch (true) {
//         case len > 11:
//             str = str.substr(0, 3) + ' ' + str.substr(3, 4) + ' ' + str.substr(7, 4);
//             $(this).val(str);
//             break;
//         case len > 7:
//             str = str.substr(0, 3) + ' ' + str.substr(3, 4) + ' ' + str.substr(7);
//             $(this).val(str);
//             break;
//         case len > 3:
//             str = str.substr(0, 3) + ' ' + str.substr(3);
//             $(this).val(str);
//             break;
//         default:
//             $(this).val(str);
//     }
// })
//验证手机号 失去焦点
$('body').on('blur', '.edit-item .need-check-phone-input', function () {
    if (isNeedCheck) {
        let reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
        let iptvalue = $(this).val().replace(/\s/g, "");
        $(this).parents('.edit-item').find('.del-icon').hide();
        let registerFlag = window.location.href.indexOf('register.html')
        // 有输入内容情况
        if (iptvalue) {
            // 验证
            if (!reg.test(iptvalue)) {
                //验证失败
                new MessageAlert({
                    icon: 'error', msg: '请输入正确的手机号'
                })
                cssError($(this))
            } else {
                //验证成功
                if (registerFlag > 0) {
                    cssSuccess($(this), true)
                } else {
                    cssSuccess($(this))
                }
            }
        } else {
            new MessageAlert({
                icon: 'error', msg: '请输入手机号'
            })
            cssError($(this))
        }
    }


})

//报错css
function cssError(element) {
    element.parents('.edit-item').find('.success-icon').hide();
    element.parents('.edit-item').find('.error-icon').show();
    // element.parents('.value').css('borderBottom', '1px solid #E52F2C');
}

//正确css
function cssSuccess(element, register = false) {
    element.parents('.edit-item').find('.success-icon').show();
    element.parents('.edit-item').find('.error-icon').hide();
    if (!register) {
        element.parents('.value').css('borderBottom', '1px solid #F3F3F3');
    }
}

$('body').on('input', '.qy-info-item .need-check-pass-input', function () {
    $(this).val($(this).val().replace(/[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/, ''))
})

function usernameCheck() {
    this.userLoginPostData.username = this.userLoginPostData.username.replace(/[\u4E00-\u9FA5]|[\uFE30-\uFFA0]/g, '')
}

//验证密码失去焦点
$('body').on('blur', '.edit-item .need-check-pass-input', function () {
    if (isNeedCheck) {
        let iptvalue = $(this).val();
        if (!iptvalue) {
            new MessageAlert({
                icon: 'error', msg: '请输入新密码'
            })
            $('#password-rule').hide();
            $('#password-tips-one').attr('src', '../images/icon/password-normal-icon.png')
            $('#password-tips-two').attr('src', '../images/icon/password-normal-icon.png')
            $('#password-tips-three').attr('src', '../images/icon/password-normal-icon.png')
            cssError($(this))
        } else {
            if (!/^(?![\da-z]+$)(?![\dA-Z]+$)(?![\d#$%&'()*+-./:;=?@_~]+$)(?![a-zA-Z]+$)(?![a-z#$%&'()*+-./:;=?@_~]+$)(?![A-Z#$%&'()*+-./:;=?@_~]+$)[\da-zA-z#$%&'()*+-./:;=?@_~]{8,15}$/.test(iptvalue)) {
                if (iptvalue.trim() == "" || iptvalue.trim() == null || iptvalue.trim() == undefined) {
                    new MessageAlert({
                        icon: 'error', msg: '请输入新密码'
                    })
                    cssError($(this))
                } else {
                    new MessageAlert({
                        icon: 'error', msg: '密码设置不符合要求，请重新设置', layer: 'V'
                    })
                    cssError($(this))
                }

            } else {
                $('#password-rule').hide();
                cssSuccess($(this))
            }
        }
    }


})
//验证确认密码失去焦点
// $('body').on('blur', '.edit-item .need-check-passConfirm-input', function () {
//     if (isNeedCheck) {
//         let iptvalue = $(this).val();
//         if (!iptvalue) {
//             new MessageAlert({
//                 icon: 'error',
//                 msg: '请再次输入新密码'
//             })
//             cssError($(this))
//         } else {
//             if (!/^(?![\da-z]+$)(?![\dA-Z]+$)(?![\d#$%&'()*+-./:;=?@_~]+$)(?![a-zA-Z]+$)(?![a-z#$%&'()*+-./:;=?@_~]+$)(?![A-Z#$%&'()*+-./:;=?@_~]+$)[\da-zA-z#$%&'()*+-./:;=?@_~]{8,15}$/.test(iptvalue)) {
//                 new MessageAlert({
//                     icon: 'error',
//                     msg: '密码设置不符合要求，请重新设置',
//                     layer:'V'
//                 })
//                 cssError($(this))
//             } else {
//                 cssSuccess($(this))
//             }
//         }
//     }


// })
//验证登录密码失去焦点
$('body').on('blur', '.edit-item .need-check-pass-login-input', function () {
    if (isNeedCheck) {
        let iptvalue = $(this).val();
        if (!iptvalue) {
            new MessageAlert({
                icon: 'error', msg: '请输入密码'
            })
            cssError($(this))
        } else {
            if (!/^[0-9A-Za-z#$%&'()*+-./:;=?@_~]{4,15}$/.test(iptvalue)) {
                new MessageAlert({
                    icon: 'error', msg: '输入的密码不符合密码规范'
                })
                cssError($(this))
            } else {
                cssSuccess($(this))
            }
        }
    }


})
//验证登录用户名失去焦点
$('body').on('blur', '.edit-item .need-check-user-input', function () {
    if (isNeedCheck) {
        let iptvalue = $(this).val();
        if (iptvalue) {
            // if (!/^[0-9A-Za-z\-\_\.\@]{4,999}$/.test(iptvalue)) {
            //     cssError($(this))
            //     new MessageAlert({
            //         icon: 'error',
            //         msg: '请输入正确手机号/用户名'
            //     })
            // } else {
            cssSuccess($(this))
            // }

        } else {
            new MessageAlert({
                icon: 'error', msg: '请输入手机号/用户名'
            })
            cssError($(this))
        }
    }


})
//验证用户名失去焦点
$('body').on('blur', '.edit-item .need-check-userName-input', function () {
    if (isNeedCheck) {
        let iptvalue = $(this).val();
        if (iptvalue) {
            // if (!/^[0-9A-Za-z\-\_\.\@]{4,999}$/.test(iptvalue)) {
            //     cssError($(this))
            //     new MessageAlert({
            //         icon: 'error',
            //         msg: '请输入正确用户名'
            //     })
            // } else {
            //     cssSuccess($(this))
            // }
            cssSuccess($(this))


        } else {
            new MessageAlert({
                icon: 'error', msg: '请输入用户名'
            })
            cssError($(this))
        }
    }


})

//验证验证码失去焦点
$('body').on('blur', '.edit-item .need-check-code-input', function () {
    if (isNeedCheck) {
        let iptvalue = $(this).val();
        if (!iptvalue) {
            new MessageAlert({
                icon: 'error', msg: '请输入验证码'
            })
            cssError($(this))
        } else {
            if (iptvalue.length !== 6) {
                new MessageAlert({
                    icon: 'error', layer: 'V', msg: '输入的手机验证码不正确，请重新输入'
                })
                cssError($(this))
            } else {
                cssSuccess($(this))
            }
        }

    }


})

//显示密码 隐藏密码
$('body').on('mousedown', '.edit-item .password-icon', function (event) {
    if ($(this).hasClass('is-hide')) {
        $(this).parents('.edit-item').find('input').attr("type", "text")
        $(this).removeClass('is-hide')
    } else {
        $(this).parents('.edit-item').find('input').attr("type", "password")
        $(this).addClass('is-hide')
    }
    event.preventDefault();
})

//0延迟弹窗
function alertDiabled() {
    new MessageAlert({icon: "", msg: '', delay: 0, hideClass: true});
}

function unEscapeHTML(str) {
    if (!isNull(str) && Object.prototype.toString.call(str) === "[object String]") {
        return str.replace(/\&lt\;/g, "<").replace(/\&gt\;/g, ">").replace(/\&\#x27\;/g, "'").replace(/\&\#x2F\;/g, "/").replace(/\&amp\;/g, "&")
    } else {
        return str
    }
}

// 退出登录
function logout(isGoLogin, isDel) {
    sendGa("action", "", "Logout", "register");
    // loadingClass.showLoading();
    var action = WebUtils.preEcApi(api_logoutApi);
    WebUtils.ajaxPostSubmit(action, "", function (result) { //success
        writeCookieUrlList(result.deleteCookieUrlList)
        if (result != undefined) {
            localStorage.removeItem("userInfo");
            localStorage.removeItem("bindPhoneModal")
            localStorage.removeItem("defaultaddress");
            localStorage.removeItem('point')
            //删除登录信息cookie
            removeCookie('openInvoiceFlag')
            removeAllCookie()
            userInfo = {};
            if (sessionStorage.getItem('routeFlag')) {
                if (isDel) {
                    logOutInMiniProgram({flag: 'DEL'})
                } else {
                    logOutInMiniProgram({flag: 'OUT'})
                }

            } else {
                if (isGoLogin) {
                    showLoginDialog()
                } else {
                    gotoIndex();
                }

            }
        } else {
            //登录失败
        }
    }, function (error) { //error
    }, function (XHR, TS) { //complete
        loadingClass.closeLoading();
    });
}

function errorInfoAlert(title) {
    AlertDialog.alert(title, "")
}

function openCommitErrorModal(title, buttonText) {
    AlertDialog.erroralert(title, buttonText)
}


//跳转加入企业 因为可能多个地方跳转 就不在每个页面写了
function goJoinQy(code, type) {
    // 神策记录
    if (type == 'cart') {//购物车
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-提示框', button_name: '加入企业'});
        sensors.track('AttendCompanyView', {source_page: '购物车页-弹框'});
    } else if (type == 'cartAlert') {//购物车
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车', button_name: '加入企业'});
        sensors.track('AttendCompanyView', {source_page: '购物车页-弹框'});
    } else if (type == 'order') {//订购
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-去订购', button_name: '加入企业'});
        sensors.track('AttendCompanyView', {source_page: '购物车页-弹框'});
    } else if (type == 'quote') {//报价
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-去报价', button_name: '加入企业'});
        sensors.track('AttendCompanyView', {source_page: '购物车页-弹框'});
    } else if (type == 'my') {//个人中心弹框
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '个人中心页', button_name: '加入企业'});
        sensors.track('AttendCompanyView', {source_page: '个人中心页-弹框'});
    }
    //页面记录
    let backIndex = localStorage.getItem('backIndex')
    if (code == 'cartPage') {
        backIndex = 'cartPage';
        localStorage.setItem('backIndex', 'cartPage');
        localStorage.setItem('redirect', JSON.stringify({
            from: 'cart', url: window.location.origin + "/static/html/page/cart.html"
        }))
    } else if (code == 'myPage') {
        backIndex = 'myPage';
        localStorage.setItem('backIndex', 'myPage')
        localStorage.setItem('redirect', JSON.stringify({
            from: 'common', url: window.location.origin + "/static/html/page/enterpriseInformation.html"
        }))
    } else if (code == 'registerPage') {
        backIndex = 'registerPage';
        localStorage.setItem('backIndex', 'registerPage')
    } else if (code == 'myPageNoprofect') {
        backIndex = 'myPageNoprofect';
        localStorage.setItem('backIndex', 'myPageNoprofect')
        localStorage.setItem('redirect', JSON.stringify({
            from: 'common', url: window.location.origin + "/static/html/page/enterpriseInformation.html"
        }))
    }
    ;closeModal('no-perfect-modal')
    var query = parseUrlQueryAfterDecode()
    jumpUprPageNew('enterpriseJoin.html', query)
}

////跳转完善企业信息 因为可能多个地方跳转 就不在每个页面写了

function goEnterpriseInfoPrefect(code, type) {
    // 神策记录
    if (type == 'cart') {//购物车
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-提示框', button_name: '完善企业信息'});
        sensors.track('CompleteCompanyInfoView', {source_page: '购物车页-弹框'});
    } else if (type == 'cartAlert') {//购物车
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车', button_name: '完善企业信息'});
        sensors.track('CompleteCompanyInfoView', {source_page: '购物车页-弹框'});
    } else if (type == 'order') {//订购
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-去订购', button_name: '完善企业信息'});
        sensors.track('CompleteCompanyInfoView', {source_page: '购物车页-弹框'});
    } else if (type == 'quote') {//报价
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '购物车-去报价', button_name: '完善企业信息'});
        sensors.track('CompleteCompanyInfoView', {source_page: '购物车页-弹框'});
    } else if (type == 'my') {
        sensors.track('CompleteCompanyInfoPopupClick', {source_page: '个人中心页', button_name: '完善企业信息'});
        sensors.track('CompleteCompanyInfoView', {source_page: '个人中心页-弹框'});
    }

    let backIndex = localStorage.getItem('backIndex')
    if (code == 'cartPage') {
        backIndex = 'cartPage';
        localStorage.setItem('redirect', JSON.stringify({
            from: 'cart', url: window.location.origin + "/static/html/page/cart.html"
        }))
        localStorage.setItem('backIndex', 'cartPage')
    } else if (code == 'myPage') {
        // backIndex = 'cartPage';
        backIndex = 'myPage';
        localStorage.setItem('backIndex', 'myPage')
        localStorage.setItem('redirect', JSON.stringify({
            from: 'common', url: window.location.origin + "/static/html/page/enterpriseInformation.html"
        }))
    } else if (code == 'registerPage') {
        backIndex = 'registerPage';
        localStorage.setItem('backIndex', 'registerPage')

    } else if (code == 'myPageNoprofect') {
        backIndex = 'myPageNoprofect';
        localStorage.setItem('backIndex', 'myPageNoprofect')
        localStorage.setItem('redirect', JSON.stringify({
            from: 'common', url: window.location.origin + "/static/html/page/enterpriseInformation.html"
        }))
    }
    ;closeModal('no-perfect-modal')
    var query = parseUrlQueryAfterDecode()
    jumpUprPageNew('enterpriseInfoPrefect.html', query)
}


//弹出企业信息已存在
function openQyInfoModal() {

    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text1">您当前完善的企业，已在米思米注册过</div>
<div class="set_company_content">
<div class="btn-item">
            <img class="img" src="../images/icon/customer-icon1.png" alt="">
            <div class="btn-label">按照当前信息注册<br/>新的企业账号</div>
            <div class="btn1 goOnSetComInfo btn-btn">直接完成注册</div>
        </div>
         <div class="btn-item">
            <img class="img" src="../images/icon/customer-icon2.png" alt="">
            <div class="btn-label">选择加入企业需要<br/>填写<span style="color:#003399">客户编码</span><img onclick="helpCustomerCodeModal(true,'个人中心-编辑企业信息')" class="tip-icon-customer" src="../images/icon/tipIcon.png" alt=""></div>
            <div class="btn2 joinCompany btn-btn">加入企业</div>
        </div>
</div>
</div>`
    const afterText = `<div class="common-close" onclick="sensors.track('FillinCompanyInfoError', {button_name:'退出'});closeModal('qy-info-modal')"></div>`
    myApp.modal({
        cssClass: 'common-modal qy-info-modal hasCustomerInfoModal', text: text, afterText: afterText
    })
}

//弹出账号当前账号暂无订购/报价权限
function openUserNoPermissionsModal() {
    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text2">当前账号暂无订购/报价权限</div>
<div class="text1">请联系企业管理员添加，或升级账号权限</div>
<div class="btn-content btn-content-one-btn">

<div class="btn2" onclick="closeModal('user-no-permissions')">我知道了</div>
</div>
</div>`

    myApp.modal({
        cssClass: 'common-modal user-no-permissions', text: text
    })
}

//商品详情无法订购
function openNoOrderModal(btnCallBack) {
    const text = `<div class="no-prefect-content">
    <img class="tips-icon"  src="/static/html/images/returnImg/img20210511_3.png" alt="">
    <p style='margin-top: 0.3rem;font-size: .36rem;color: #333;font-weight: bold;'>关于商品交期的重要通知<br/><p style='font-size: 0.28rem;font-weight: 400;color: #333333;line-height: 0.5rem;margin-top:0.2rem;text-align:left;padding:0 0.28rem;'>发货地为<span style='color:red'>广州、东莞、深圳</span>的商品的交期不受上海疫情影响，当您订购由三地发货的<span style='color:red'>库存品</span>后，我们将在当日晚间集中处理交期信息，您可在<span style='color:red'>【订购后次日】</span>于<span id='gotoOrderList' style='color:#003399;text-decoration:underline;'>【我的订单】</span> 页面中查看实际情况。给您带来诸多不便、深表歉意、感谢理解和支持!</p></p>
    <div class="btn-content" style="padding: 0 0.9rem;margin-top: 0.6rem">
    <div class="btn2" id='noOrder' style='width:2.48rem;height:0.72rem;font-size:0.28rem;border-radius:0.45rem;color:#333;background:#FFCC00'>我知道了</div>
    </div>
    </div>`

    myApp.modal({
        cssClass: 'common-modal no-order-modal', text: text
    })
    //   $('.common-modal').css("cssText","width: 7.02rem!important")

    $('.no-order-modal').on('modal:opened', function () {
        sessionStorage.setItem('noOrderFlag', 'true')
        $('#noOrder').click(function () {
            closeModal('no-order-modal');
            if (btnCallBack && typeof btnCallBack == 'function') {
                btnCallBack()
            }

        })
        $('#gotoOrderList').click(function () {
            if (isNull(userInfo) && isNull(userInfo.sessionId)) {
                jumpUprPageNew('loginNew.html', {
                    back_url: jumpUrl + '/static/html/page/orderList.html', jumpmode: '1'
                })
            } else {
                jumpUprPage('orderList.html')
            }
        })
    })

}

function randomString(len) {
    len = len || 32;
    let $chars = 'ABC1DEFGH2IJK3LMNOQP4RSTU5VWXYZab6cdef8ghij7kmlnopq9rest0uvwxyz';
    let maxPos = $chars.length;
    let pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function getWxConfigInfo(fn) {
    loadJs_('https://res.wx.qq.com/open/js/jweixin-1.6.0.js', function () {
        let timestamp = Date.parse(new Date()) / 1000;
        let nonceStr = randomString()
        var action = 'https://apihosts.misumi.com.cn/Customer/MblWechat/wechat_mp/getJssdkSign?subsidiaryCode=CHN'
        param = {
            noncestr: nonceStr, timestamp: timestamp, url: encodeURIComponent(window.location.href)
        }
        headers = {
            'Content-Type': "application/json", "x-api-key": "z7egOF19hr9DUxsvyGhkO69qMuCa2O8Y796BuksP"
        }
        // 调接口获取APPID
        $.ajax({
            url: action,
            type: 'POST',
            data: JSON.stringify(param),
            headers: headers,
            dataType: "json",
            success: function (result) {
                // console.log(result)
                var a = {
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: result.masterData.appId, // 必填，公众号的唯一标识
                    timestamp: timestamp, // 必填，生成签名的时间戳
                    nonceStr: nonceStr, // 必填，生成签名的随机串
                    signature: result.masterData.sign,// 必填，签名
                    jsApiList: ['chooseImage', 'previewImage', 'getLocalImgData'], // 必填，需要使用的JS接口列表
                    openTagList: ['wx-open-launch-weapp']
                }
                wx.config(a)
                fn && fn()
            },
            error: function () {
                // console.log('注入微信jssdk失败')
            },
            complete: function () {
            }
        })

    })


}

// 商品详情跳转小程序弹窗
function openGoAppletModal(btnCallBack) {
    var AppletName = isProduce ? 'gh_cb1ec9b028d5' : 'gh_3f65f65fe4f9'
    var AppletUrl = '/pages/index/index?sourceChl=HTWE&isLogin=1&isLoading=1&returnURL=' + encodeURIComponent(window.location.href)
    const text = `<div class="no-prefect-content" style='padding-bottom:0.4rem;'>
    <img class="tips-icon"  src="/static/html/images/returnImg/img20210511_3.png" alt="">
    <p style='font-size: .36rem;color: #333;font-weight: bold;'><p style='font-size: 0.28rem;font-weight: 400;color: #333333;line-height: 0.5rem;margin-top:0.2rem;text-align:center;padding:0 0.28rem;'>即将用微信小程序打开此页面</p></p>
    <wx-open-launch-weapp
    id="launch-btn"
    username="${AppletName}"
    path="${AppletUrl}"
    style="width:124px !important;"
    >
    <template>
        <style>.btn {
            width:124px !important;
            height:36px !important;
            font-size:14px !important;
            border-radius:22px !important;
            color:#333 !important;
            background-color:#FFCC00 !important;
            margin: 15px auto 0 auto !important;
            line-height: 36px !important;
            text-align:center !important;
          }</style>
          <div class="btn">我知道了</div>
    </template>
    </wx-open-launch-weapp>
    </div>`
    // <div class="btn-content" style="padding: 0 0.9rem;margin-top: 0.6rem">
    // <div class="btn2" id='goApplet' style='width:2.48rem;height:0.72rem;font-size:0.28rem;border-radius:0.45rem;color:#333;background:#FFCC00'>我知道了</div>

    myApp.modal({
        cssClass: 'common-modal no-order-modal', text: text
    })

    $('.no-order-modal').on('modal:opened', function () {
        sessionStorage.setItem('appletFlag', 'true')
        $('#launch-btn').on('launch', function (e) {
            closeModal('no-order-modal');
            // console.log(e,'success')
            location.reload()

        })
        $('#launch-btn').on('error', function (e) {
            closeModal('no-order-modal');
            // console.log(e,'error')
            location.reload()
        })
        //   $('#goApplet').click(function () {
        //     //   closeModal('no-order-modal');

        //       if (btnCallBack && typeof btnCallBack == 'function') {
        //          btnCallBack()
        //     }

        //   })
    })

}


//弹出输入信息有误
function openInfoErrorModal() {
    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text3" style="margin-top: 0.3rem">您输的公司或企业编码有误请重新输入</div>
<div class="text3">如果您没有企业，可前往完善企业信息</div>
<div class="btn-content ">

<div class="btn1 toComplateInfoPage" >完善企业信息</div>
<div class="btn2" onclick="sensors.track('AttendCompanyError', {button_name:'重新输入'});closeModal('info-error-modal');">重新输入</div>
</div>
</div>`
    const afterText = `<div class="common-close" onclick="sensors.track('AttendCompanyError', {button_name:'退出'});closeModal('info-error-modal');"></div>`
    myApp.modal({
        cssClass: 'common-modal info-error-modal', text: text, afterText: afterText
    })
}

//返回企业选择
function backToQYpage() {
    let backIndex = localStorage.getItem('backIndex');
    if (backIndex == 'registerPage') {
        // window.location.href = jumpUrl + "/static/html/page/my.html"
        history.go(-1)
    } else if (backIndex == 'myPage') {
        window.location.href = jumpUrl + "/static/html/page/my.html"
    } else if (backIndex == 'cartPage') {
        window.location.href = jumpUrl + "/static/html/page/cart.html";
    } else if (backIndex == 'myPageNoprofect') {
        jumpUprPage('enterpriseInfoNoPrefect.html')
    } else {
        window.location.href = jumpUrl + "/static/html/page/my.html"
    }

}

function openErrorModal() {

    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text3" style="margin-top: 0.3rem">发生未知错误，请稍后再试</div>

<div class="btn-content">
<div class="btn2" style="width: 2.48rem" onclick="closeModal('error-modal')">我知道了</div>
</div>
</div>`

    myApp.modal({
        cssClass: 'common-modal error-modal', text: text
    })
}

function sens() {
    sensors.track('CommonClick', {
        button_type: "无法参与抽奖弹窗", button_name: "我知道了", current_page: '我的订单', content: '积分抽奖'
    });
}

// 无法参与抽奖弹窗
function openNoLotteryModal() {
    const noPrefectText = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text2" style="font-size: 0.28rem;font-weight: normal">当前账号无法参与抽奖，如有疑问请联系在线客服</div>
<div class="btn-content">
<div class="btn1" id="go-chat-p" style="border: 0.02rem solid rgb(205,205,205);">在线客服</div>
<div class="btn2" onclick="closeModal('no-lottery-modal');sens()">我知道了</div>
</div>
</div>`
    myApp.modal({
        cssClass: 'common-modal no-lottery-modal', text: noPrefectText
    })
    $('#go-chat-p').off('touchend').on('touchend', function (event) {
        // Stop event propagation
        event.stopPropagation();
        closeModal();
        onLineChat('orderListkf')
    })
}

//弹出修改提示
function openSaveCustomerInfoModal() {
    const text = `<div class="no-prefect-content">
<img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
<div class="text3" style="margin-top: 0.3rem">您当前资料有修改，是否需要保存？</div>
<div class="btn-content ">

<div class="btn1" style="border-color: #CDCDCD" id="concelCustomerSave">取消</div>
<div class="btn2" id="saveCustomerSubmit">保存</div>
</div>
</div>`
    const afterText = `<div class="common-close" onclick="closeModal('username-modal')"></div>`
    myApp.modal({
        cssClass: 'common-modal username-modal', text: text, afterText: afterText
    })
}


//弹出未完善提示-购物车
function openNoPrefectModal(type) {
    getWsCouponApi().then(res => {
        if (res.returnFlg == 0) {
            if (res.status == 0) {
                let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
                noPrefectText += `<div id='no-prefect-ws-text'>完善企业信息，领新客专享大礼包</div>`
                noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;'  onclick="goJoinQy('cartPage','${type}');">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('cartPage','${type}');">完善企业信息</div>
                </div>
                </div>`
                const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal','${type}')"></div>`
                myApp.modal({
                    cssClass: 'common-modal no-perfect-modal', text: noPrefectText, afterText: noPrefectAfterText
                })
            } else {
                let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
                noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;'  onclick="goJoinQy('cartPage','${type}');">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('cartPage','${type}');">完善企业信息</div>
                </div>
                </div>`
                const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal','${type}')"></div>`
                myApp.modal({
                    cssClass: 'common-modal no-perfect-modal', text: noPrefectText, afterText: noPrefectAfterText
                })
            }
        } else {
            let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
            noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;'  onclick="goJoinQy('cartPage','${type}');">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('cartPage','${type}');">完善企业信息</div>
                </div>
                </div>`
            const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal','${type}')"></div>`
            myApp.modal({
                cssClass: 'common-modal no-perfect-modal', text: noPrefectText, afterText: noPrefectAfterText
            })
        }
    }).catch((err => {
        let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
        noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;'  onclick="goJoinQy('cartPage','${type}');">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('cartPage','${type}');">完善企业信息</div>
                </div>
                </div>`
        const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal','${type}')"></div>`
        myApp.modal({
            cssClass: 'common-modal no-perfect-modal', text: noPrefectText, afterText: noPrefectAfterText
        })
    }))
}

//未完善我的页面弹出
function openNoPrefectModalmy(type) {
    getWsCouponApi().then(res => {
        if (res.returnFlg == 0) {
            if (res.status == 0) {
                let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
                noPrefectText += `<div id='no-prefect-ws-text'>完善企业信息，领新客专享大礼包</div>`
                noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;' onclick="goJoinQy('myPage','${type}')">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('myPage','${type}')">完善企业信息</div>
                </div>
                </div>`
                const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal2','${type}')"></div>`
                myApp.modal({
                    cssClass: 'common-modal no-perfect-modal2', text: noPrefectText, afterText: noPrefectAfterText
                })
            } else {
                let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
                noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;' onclick="goJoinQy('myPage','${type}')">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('myPage','${type}')">完善企业信息</div>
                </div>
                </div>`
                const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal2','${type}')"></div>`
                myApp.modal({
                    cssClass: 'common-modal no-perfect-modal2', text: noPrefectText, afterText: noPrefectAfterText
                })
            }
        } else {
            let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
            noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;' onclick="goJoinQy('myPage','${type}')">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('myPage','${type}')">完善企业信息</div>
                </div>
                </div>`
            const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal2','${type}')"></div>`
            myApp.modal({
                cssClass: 'common-modal no-perfect-modal2', text: noPrefectText, afterText: noPrefectAfterText
            })
        }
    }).catch((err) => {
        let noPrefectText = `<div class="no-prefect-content">
                <img class="tips-icon" src="../images/returnImg/img20210511_3.png" alt="">
                <div class="text2">您尚未完善企业信息</div>
                <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>`
        noPrefectText += `
                <div class="btn-content">
                <div class="btn1" style='background-color: #003399;color:#fff;border:0;' onclick="goJoinQy('myPage','${type}')">加入企业</div>
                <div class="btn2" onclick="goEnterpriseInfoPrefect('myPage','${type}')">完善企业信息</div>
                </div>
                </div>`
        const noPrefectAfterText = `<div class="common-close" onclick="closeModal('no-perfect-modal2','${type}')"></div>`
        myApp.modal({
            cssClass: 'common-modal no-perfect-modal2', text: noPrefectText, afterText: noPrefectAfterText
        })
    })

}

function openCommonModal(mode, mainTitle, title, btnText, isShowClose, btnCallBack, mainTitleClass = '', subTitleClass = '', src = "../images/returnImg/img20210511_3.png") {
    var mainTitle_ = mainTitle ? mainTitle : '温馨提示'
    var btnText_ = btnText ? btnText : '我知道了'
    var title_ = title ? title : '默认提示'
    var content = ''
    switch (mode) {
        case 1:
            //温馨提示
            content = `<div class="main-title ${mainTitleClass}" >${mainTitle_}</div>
                         <div class="sub-title">${title_}</div>`
            break;
        default:
            content = `<div class="sub-title2 ${subTitleClass}">${title_}</div>`
            break;

    }
    if (isShowClose) {
        var closeText = `<div class="common-close" onclick="closeModal('common-modal-new')"></div>`
    } else {
        var closeText = ``
    }

    var text = `<div class="common-modal-wrap">${closeText}<img class="icon" src="${src}" alt="">${content}<div class="btn" id="common-btn-ok" >${btnText_}</div></div>`

    myApp.modal({
        cssClass: 'common-modal-new', text: text
    })
    $$('.common-modal-new').on('modal:opened', function () {
        $('#common-btn-ok').click(function () {
            closeModal('common-modal-new')
            if (btnCallBack && typeof btnCallBack == 'function') {
                btnCallBack()
            }
        })
    });
}

//无此权限 弹出登录过期提示
function openErrorTipsModal() {
    myApp.closeModal()
    openCommonModal('', '', '<div style="font-weight:bold;color:#333;font-size:0.36rem;">登录过期，请重新登录<p style="font-size:0.24rem;color:#666;font-weight:normal;margin-top:0.2rem;margin-bottom:0;">如反复出现此问题，请前往米思米桌面端网站 <br/>联系客服解决</p></div>', '', false, function () {
        logout()
    })
}

//未绑定手机弹窗
function openNoBindPhoneModal() {
    const text = `<div class="no-prefect-content">
  <img class="tips-icon"  src="/static/html/images/returnImg/phonebind.png" alt="">
  <div style='font-size: 0.36rem;font-family: PingFangSC-Semibold, PingFang SC;font-weight: bold;color: #333333;line-height: 0.5rem;margin-top:0.4rem'>请绑定手机号完成实名认证</div>
  <div style='font-size: 0.24rem;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: #333333;line-height: 0.34rem;margin: 0.2rem 0.36rem 0 0.34rem;text-align: left;' >·2021年12月12日起, 未绑定手机号的用户可能无法登录与使用本网站或相关服务受到限制。</div>
  <div style='font-size: 0.24rem;font-family: PingFangSC-Regular, PingFang SC;font-weight: 400;color: #333333;line-height: 0.34rem;margin: 0.2rem 0.36rem 0 0.34rem;text-align: left;' >·您的个人信息仅用于身份验证, 米思米将按照<br/><span style='color:#003399' id='zhengce'>《客户信息与个人信息保护方针》</span>予以保护</div>
  <div class="btn-content" style="padding: 0 0.9rem;margin-top: 0.44rem">
  <div class="btn2" id='bindPhone'>立即绑定</div>
  </div>
  </div>`
    const afterText = `<div class="common-close" id='closebindPhone'></div>`

    myApp.modal({
        afterText: afterText, cssClass: 'common-modal no-bind-phone-modal', text: text
    })
    $('.no-bind-phone-modal').on('modal:opened', function () {
        $('#bindPhone').click(function () {
            closeModal('no-bind-phone-modal');
            localStorage.setItem('bindPhoneModal', '2')
            jumpUprPage('myInfoSet.html');
        })
        $('#closebindPhone').click(function () {
            closeModal('no-bind-phone-modal');
            logout();
        })
        $('#zhengce').click(function () {
            jumpUprPage('settingPrivacyPolicy.html');
        })
    })

}

//判断是否微信浏览器
function isWeiXin() {
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        return true;
    } else {
        return false;
    }
}

// 判断是否为小程序环境
function isMiniProgram() {
    if (sessionStorage.getItem('routeFlag') == '微信小程序') {
        return true
    } else {
        return false
    }
}

// 校验报错类型
function checkErrorTypeForBind(res, from) {
    var errorMsg = ''
    switch (res) {
        case 'USR018002':
            errorMsg = '此米思米账号已被其他微信绑定';
            break;
        case 'USR018005':
            errorMsg = '此米思米账号已被其他微信绑定';
            break;
        case 'USR018004':
            errorMsg = '此微信已被其他米思米账号绑定';
            break;
        default:
            errorMsg = '更新失败，请重新尝试！[MS001_W154]'
    }
    if (from == 'Apple') {
        errorMsg = errorMsg.replace('微信', 'Apple')
    }
    return errorMsg
}

//优惠券我知道点击
function closeCouponUseArea() {
    myApp.closeModal("#order-confirm-couponUseArea-modal")
    $(".coupon_userArea").hide();
}

//判断是否已经引入css js
function isInclude_(name) {
    var js = /js$/i.test(name);
    var es = document.getElementsByTagName(js ? 'script' : 'link');
    for (var i = 0; i < es.length; i++) if (es[i][js ? 'src' : 'href'].indexOf(name) != -1) return true;
    return false;
}

//加载外部js文件
function loadJs_(src, callback) {
    if (!isInclude_(getValue(src))) {
        var script = document.createElement('script'), head = document.getElementsByTagName('head')[0];
        script.type = 'text/javascript';
        script.charset = 'UTF-8';
        script.src = src + "?t=" + new Date().getTime();
        if (script.addEventListener) {
            script.addEventListener('load', function () {
                callback();
            }, false);
        } else if (script.attachEvent) {
            script.attachEvent('onreadystatechange', function () {
                var target = window.event.srcElement;
                if (target.readyState == 'loaded') {
                    callback();
                }
            });
        }
        head.appendChild(script);
    } else {
        callback()
    }

}

// 20211215新增 m站对接小程序环节
function postMessageToMiniProgram(title, path, imageUrl, needLogin = true, needLoad) {

    var blessingArr = ['boostList', 'friendBoost', 'writeBlessing', 'writeBlessingAddress', 'writeBlessingLottery', 'writeBlessingRules', 'writeBlessingUpdate']

    var needLoginHtml = ['cart', 'my', 'confirmOrder', 'confirmQuotation', 'enterpriseInfoNoPrefect', 'enterpriseInfoPrefect', 'enterpriseInformation', 'enterpriseJoin', 'exchangeApply', 'exchangeList', 'exchangeListDetail', 'invoiceSet', 'myCoupon', 'myInfoSet', 'myPart', 'noticeSet', 'notificationCenter', 'orderComplete', 'orderConfirm', 'orderDetail', 'orderList', 'orderListDetail', 'orderListNew', 'pay-complete', 'paymentCompleted', 'quotationDetail', 'quotationList', 'refundList', 'registerSuccess', 'returnApply', 'returnListDetail', 'satisfactionEvaluation', 'shipTo']

    var miniAction = {
        title: title || '帮我写福字 赢大奖',
        path: path || ('https://' + window.location.host + '/static/html/page/activity/writeBlessing.html'),
        imageUrl: imageUrl || 'https://stg-d.misumi.com.cn/MisumiManagement/fileUpload/blessing.png',
        needLogin: needLogin
    }

    var flag = blessingArr.some(item => {
        return window.location.href.indexOf(item + '.html') > -1
    })

    var needLoginFlag = needLoginHtml.some(item => {
        return window.location.href.indexOf(item + '.html') > -1
    })
    // 活动分享
    if (needLoad) {
        uni.postMessage({
            data: {
                action: JSON.stringify(miniAction)
            }
        });
        return false
    }
    loadJs_('https://res.wx.qq.com/open/js/jweixin-1.6.0.js', function () {
        loadJs_('https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js', function () {
            document.addEventListener('UniAppJSBridgeReady', function () {
                uni.postMessage({
                    data: {
                        action: flag ? JSON.stringify(miniAction) : JSON.stringify({
                            path: window.location.href, needLogin: needLoginFlag
                        })
                    }
                });
            });
        })
    })

}

if (sessionStorage.getItem('routeFlag') == '微信小程序' || (isWeiXin() && window.navigator.userAgent.toLowerCase().match(/miniProgram/i) == 'miniprogram')) {
    if (window.location.pathname.indexOf('vx_loading.html') === -1 && window.location.pathname.indexOf('vx_return.html') === -1) {
        if (location.href.indexOf('friendBoost.html') != -1) {
            //好友助力页面 是分享当前页
            postMessageToMiniProgram('', location.href, '', false)
        } else {
            postMessageToMiniProgram()
        }
    }

}

// 小程序对应评价分享
function postMessageToMiniProgramShare(title, path, imageUrl, needLogin) {
    var miniActionShare = {
        title: title, path: path, imageUrl: imageUrl, needLogin: false
    }
    uni.postMessage({
        data: {
            action: JSON.stringify(miniActionShare)
        }
    });

}

// app跳转
function webviewReturnBack(param) {
    if (isIphone()) {
        window.webkit.messageHandlers.webviewReturnBack.postMessage([JSON.stringify(param), 'webviewReturnBackFun']);
    } else {
        misumiJs.webviewReturnBack(JSON.stringify(param), 'webviewReturnBackFun');
    }
}

// 小程序内部统一退出登录方法
function logOutInMiniProgram(params) {
    if (sessionStorage.getItem('routeFlag') == 'APP') {
        // app进入
        if (params.flag == 'OUT') {
            removeAllCookie();
            webviewReturnBack({
                callBack: 'logout', param: ''
            })
        } else {
            // removeAllCookie();
            webviewReturnBack({
                callBack: 'returnBack', param: 6
            })
        }

    } else {
        // 小程序进入
        if (params.flag == 'OUT') {
            jumpUprPage('vx_return.html?to=OUT')
        } else if (params.flag == 'DEL') {
            jumpUprPage('vx_return.html?to=DEL')
        } else if (params.flag == 'LOGIN') {
            jumpUprPage('vx_return.html?to=login&returnUrl=' + encodeURIComponent(returnUrl))
        } else if (params.flag == 'lpRegister') {
            jumpUprPage('vx_return.html?to=lpRegister')
        } else if (params.flag == 'lpCoupon') {
            jumpUprPage('vx_return.html?to=lpCoupon')
        } else {
            jumpUprPage('vx_return.html')
        }

    }

}

(function () {

    if (typeof WeixinJSBridge == "object" && typeof WeixinJSBridge.invoke == "function") {
        handleFontSize();
    } else {
        if (document.addEventListener) {
            document.addEventListener("WeixinJSBridgeReady", handleFontSize, false);
        } else if (document.attachEvent) {
            document.attachEvent("WeixinJSBridgeReady", handleFontSize);
            document.attachEvent("onWeixinJSBridgeReady", handleFontSize);
        }
    }

    function handleFontSize() {
        // 设置网页字体为默认大小
        WeixinJSBridge.invoke('setFontSizeCallback', {
            'fontSize': 0
        });
        // 重写设置网页字体大小的事件
        WeixinJSBridge.on('menu:setfont', function () {
            WeixinJSBridge.invoke('setFontSizeCallback', {
                'fontSize': 0
            });
        });
    }
})();

function getMeviyImageList() {
    var action = ''
    var param = {}
    // if (isProduce) {
    //     action = `https://api.misumi.com.cn/MisumiApi/online/meviyImageList_json.htmls`
    // } else {
    //     action = `${WebUrlApiStg}online/meviyImageList_json.htmls`
    // }
    action = `${apiUrl.Customer.urlList.meviyImageList({})}`
    return new Promise((resolve, reject) => {
        WebUtils.ajaxGetSubmit(action, param, function (result) { //success
            resolve(result);
        }, function (error) { //error
            reject(error);
        }, function () {
        }, {'x-api-key': apiUrl.Customer.xApiKey});
    })
}

function createMeviyItemImageUrlMap() {
    return new Promise(async (resolve, reject) => {
        try {
            const res = await getMeviyImageList()
            var host = ''
            if (isProduce) {
                host = upApidev
            } else {
                host = upApiStg1
            }
            res.meviyImageList.forEach(meviyItem => {
                const key = meviyItem.partNumber5;
                if (!meviyItemImageUrlMap[key]) {
                    meviyItemImageUrlMap[key] = meviyItem.productImagePath ? host + meviyItem.productImagePath : ``;
                }
            });
            // console.log('map构建完成')
            resolve(meviyItemImageUrlMap)
        } catch (err) {
            resolve({})
        }
    })
}

function setIframeHeight() {
    var iframes = $('.iframeWrap')
    for (var i = 0; i < iframes.length; i++) {
        iframes[i].setAttribute('height', iframes[i].contentWindow.document.body.scrollHeight);
    }
}


function goto() {
    var urlParams = parseUrlQuery()
    var path = ""
    if (urlParams.fromPage == 'productInfo') {
        let url = localStorage.getItem('QrAndPc')
        path = url
    } else if ((urlParams.mode ? urlParams.mode.toUpperCase() : '') == 'OLC01') {
        // let baseUrl = 'm.misumi.com.cn/static/html/page/onlineChat.html?customCode=' + userInfo.customerCode + '&customName=' + userInfo.customerName + '&userName=' + userInfo.userName + '&userCode=' + userInfo.userCode
        let baseUrl = 'm.misumi.com.cn/static/html/page/onlineChat.html?customCode={customCode}&customName={customerName}&userName={userName}&userCode={userCode}'
        baseUrl = baseUrl.replace("{customCode}", userInfo.customerCode ? userInfo.customerCode : '')
        baseUrl = baseUrl.replace("{customerName}", userInfo.customerCode ? userInfo.customerCode : '')
        baseUrl = baseUrl.replace("{userName}", userInfo.customerName)
        baseUrl = baseUrl.replace("{userCode}", userInfo.userName)
        path = isProduce ? 'https://' + baseUrl : 'https://stg-' + baseUrl
    } else if ((urlParams.mode ? urlParams.mode.toUpperCase() : '') == 'LP') {
        let baseUrl = 'm.misumi.com.cn/static/html/page/lp'
        let url = isProduce ? 'https://' + baseUrl : 'https://stg-' + baseUrl
        if (urlParams.redirectUrl && urlParams.redirectUrl.indexOf(baseUrl) === -1) {
            path = urlParams.redirectUrl
        }
        if (urlParams.redirectUrl && urlParams.redirectUrl.indexOf(baseUrl) > -1) {
            url = url + urlParams.redirectUrl.substring(urlParams.redirectUrl.indexOf(baseUrl) + baseUrl.length)
            path = url
        }
        // window.history.back();
    } else {
        window.history.back();
    }
    window.localStorage.removeItem('QrAndPc');
    window.localStorage.setItem("lpJump", encodeURIComponent(path))
    window.location.href = '/'
}

// 大学生活动banner跳转
function jumpCollegeActivity(type) {
    var baseUrl = isProduce ? 'https://techinfo.misumi.com.cn/' : 'https://techinfo-stg.misumi.com.cn/';
    if (type === 'top') {
        window.open(baseUrl + 'campus/?bid=m_top')
    } else if (type === 'login') {
        window.open(baseUrl + 'campus/?bid=m_login')
    } else if (type === 'regist') {
        window.open(baseUrl + 'campus/?bid=m_regist')
    } else if (type === 'success') {
        window.open(baseUrl + 'campus/')
    }
}

async function getWsCouponShow() {
    await getWsCouponApi().then(res => {
        if (res.returnFlg == 0) {
            if (res.status == 0) {
                return true;
            } else {
                return false
            }
        } else {
            return false
        }
    }).catch((err) => {
        return false

    })
}

// 完善企业优惠券是否显示
async function getWsCouponApi() {
    return new Promise((resolve, reject) => {
        let url = isProduce ? 'https://apihosts.misumi.com.cn' : 'https://apihosts-stg.misumi.com.cn'
        WebUtils.ajaxGetSubmit(`${url}/Campaign/getCouponStatus?eventId=1`, '', function (res) {
            resolve(res)
        }, function (err) {
            reject(err);
        }, function () {
        }, {"x-api-key": isProduce ? "zoLggKKTuB9yOR1tUDFc87xuc8RiOubA3N1ICpbI" : "bYLkzu7FU432Mw2XubuFL571GJwnchJr3aPdZxcy"})
    })
}

function replacePreset(param, preset) {
    if (isNull(param)) {
        return param
    }
    var imgUrl = param
    var path = imgUrl.split("/")
    // Cloudinaryドメイン定数を定義する。
    var targetImgDomainList = ['content.misumi-ec.com', // 本番:中国以外
        'content.misumi.com.cn', // 本番:中国
        'stg-content.misumi-ec.com', // STG:中国以外
        'stg-content.misumi.com.cn', // STG:中国
    ];

    // 画像URLからuriオブジェクトに変換する。

    // 画像URLがCloudinaryドメインの場合
    if (targetImgDomainList.indexOf(path[2]) != -1) {
        var pregMatch = /^\/image\/upload\//;
        // console.log(imgUrl.indexOf("/image/upload/"))
        //if (pregMatch.test(imgUrl)) {
        if (imgUrl.indexOf("/image/upload/") > -1) {
            //f_auto
            var presetPath = 'f_auto,' + preset;
            // 画像URLにCloudinaryプリセットが含まれる場合
            var preg_matchArr = /^[a-zA-Z]+_/;
            // console.log(preg_matchArr.test(path[5]))
            if (preg_matchArr.test(path[5])) {
                // 引数に指定されたCloudinaryプリセットで置換する。
                path[5] = presetPath;
            } else { // 画像URLにCloudinaryプリセットが含まれない場合
                // 引数に指定されたCloudinaryプリセットを画像URLパスの/image/upload/の直後のパスに挿入する。
                path.splice(5, 0, presetPath);
            }
            // 画像URLを再設定する。
            return path.join("/").split("?")[0]

        }
    } else {
        return imgUrl;

    }
}

function convertImageUrl(param, preset = '') {
    if (isNull(param)) {
        return param
    }
    var domainArr = ['content.misumi-ec.com', 'stg-content.misumi-ec.com', 'content.misumi.com.cn', 'stg-content.misumi.com.cn'];
    var resStr = param;
    domainArr.forEach(function (item) {
        if (param.indexOf(item) !== -1) {
            resStr = param.replace(/upload\/v1/, function () {
                if (preset) {
                    return `upload/${preset}/v1`
                } else {
                    return `upload/v1`
                }
            })
        }
    })
    return resStr

}

function imgLoadError(e) {
    if (e.src.indexOf('/image/upload/') > -1) {
        if (e.src.match(/\/image\/upload\/(\S*\/)v1\//)) {
            var imgstr = e.src.match(/\/image\/upload\/(\S*\/)v1\//)[1]
            e.src = e.src.replace(imgstr, '')
        } else {
            return
        }
    } else {
        return
    }
}

function isBackUrl() {
    var backFlag = parseUrlQueryAfterDecode().back_url;
    if (backFlag) {
        return true;
    } else {
        if (localStorage.getItem('redirect')) {
            return true;
        } else {
            return false;
        }
    }

}

//  M站广告埋点方法
// eventClick:事件名称
function apiBuryingPoint(eventClick) {
    if (sessionStorage.getItem("clickid")) {
        var times = Date.parse(new Date());
        var clickid = sessionStorage.getItem("clickid")
        var params = {
            event_type: eventClick, context: {
                ad: {
                    callback: clickid
                }
            }, timestamp: times
        }
        var action = ''
        action = `${apiUrl.Customer.urlList.conversion({})}`
        var header = {
            "x-api-key": apiUrl.Customer.xApiKey
        }
        // if(isProduce){
        //     // 正式
        //     action = WebUrlApi + 'pack/oceanengine/conversion.htmls'
        // }else{
        //     action = WebUrlApiStg +'pack/oceanengine/conversion.htmls'
        // }
        $.ajax({
            url: action,
            type: 'POST',
            headers: header,
            data: JSON.stringify(params),
            contentType: 'application/json;charset=utf-8',
            success: function (res) {
                var result = JSON.parse(res)
                if (JSON.parse(result.data).code == 0) {
                    console.log('广告埋点成功')
                } else {
                    console.log(res, '广告埋点失败')
                }
            },
            error: function (err) {
                console.log(err, '广告埋点失败')
            }
        })
    }

}

function apiBuryingPointWeChat(eventClick) {
    if (sessionStorage.getItem("wechatClickid")) {
        var times = Date.parse(new Date()) / 1000;
        var clickid = sessionStorage.getItem("wechatClickid")
        var actionType = eventClick;
        var action = ''
        action = `${apiUrl.Customer.urlList.convWeb({})}`
        var header = {
            "x-api-key": apiUrl.Customer.xApiKey
        }
        // if(isProduce){
        //     // 正式
        //     action = WebUrlApi + 'pack/conv/web.htmls'
        // }else{
        //     action = WebUrlApiStg +'pack/conv/web.htmls'
        // }
        $.ajax({
            url: action + '?clickid=' + clickid + '&action_time=' + times + '&action_type=' + actionType + '&link=' + encodeURI(window.location.host),
            type: 'GET',
            headers: header,
            success: function (res) {
                var result = JSON.parse(res)
                console.log(result)
                if (JSON.parse(result.data).code == 0) {
                    console.log('微信广告埋点成功')
                } else {
                    console.log(res, '微信广告埋点失败')
                }
            },
            error: function (err) {
                console.log(err, '微信广告埋点失败')
            }
        })
    }

}

function getSeriesTsvCommon(request) {
    return new Promise((resolve, reject) => {
        //根据当前环境确定地址
        let url = isProduce ? 'https://apihosts.misumi.com.cn' : 'https://apihosts-stg.misumi.com.cn'
        let action = `${url}/Campaign/getECSettingFileInfo`
        let xApiKey = isProduce ? "zoLggKKTuB9yOR1tUDFc87xuc8RiOubA3N1ICpbI" : "bYLkzu7FU432Mw2XubuFL571GJwnchJr3aPdZxcy"
        WebUtils.ajaxPostSubmitJson(action, JSON.stringify(request), function (res) {
            resolve(res);
        }, function (err) {
            resolve(null);
        }, function () {
        }, {"x-api-key": xApiKey})


    })
}

function setReviewList() {
}

function getWhite(sessionId) {
    return new Promise((resolve, reject) => {
        //根据当前环境确定地址
        let url = isProduce ? 'https://apihosts.misumi.com.cn' : 'https://apihosts-stg.misumi.com.cn'
        let action = `${url}/Review/NeedRealNameAuthentication?sessionId=${sessionId}`
        let xApiKey = isProduce ? "CHjIHFD82g54eWKbqRscG5u0jvXFxQ1U2Nu40No2" : "uqKz8jthzZ9O1Kws2iQ6D39e3YF685rwOyaqxYPa"
        WebUtils.ajaxGetSubmit(action, '', function (res) {
            resolve(res);
        }, function (err) {
            resolve(null);
        }, function () {
        }, {"x-api-key": xApiKey})


    })
}

// ip地址获取
function getLocalIP() {
    return new Promise((resolve, reject) => {
        //根据当前环境确定地址
        // let action = isProduce ? 'https://api.misumi.com.cn/MisumiApi/util/getClientIp.htmls' : 'https://stg-api.misumi.com.cn/MisumiApi/util/getClientIp.htmls'
        let action = apiUrl.Customer.urlList.getClientIp()
        WebUtils.ajaxGetSubmit(action, '', function (res) {
            resolve(res);
        }, function (err) {
            resolve(null);
        }, function () {
        }, {
            'x-api-key': apiUrl.Customer.xApiKey
        })
    })
}

// 获取默认地址
async function setDefaultAddress(request) {
    return new Promise((resolve, reject) => {
        var param = {
            shipToCode: 'ZZZZZZZ', disableAddressSplittingFlag: 0
        };
        var action = WebUtils.preReferPCApiParam(api_shipSearch);
        WebUtils.ajaxGetSubmit(action, param, function (result) { //success
            if (result && result.shipToList && result.shipToList.length > 0) {
                let defaultaddress = result.shipToList[0]
                localStorage.setItem("defaultaddress", JSON.stringify(defaultaddress));
                resolve(defaultaddress);

            } else {
                resolve('')
            }

        }, function (error) { //error
            resolve('')
        }, function (XHR, TS) { //complete
        });
    })
}

// 预计到货日第二期
async function getDetailArrivalDate(params) {
    if (!localStorage.getItem('defaultaddress')) {
        var resultAddress
        try {
            resultAddress = await setDefaultAddress()
            if (isNull(resultAddress)) {
                return ''
            }
        } catch (e) {
            return ''
        }
    }
    return new Promise((res, rej) => {
        _getDate(params).then(r => {
            res(r)
        }).catch(err => {
            res()
        })
    })


    function _getDate(params = []) {

        let defaultAddress = JSON.parse(localStorage.getItem('defaultaddress'))
        let addressData = {
            province: defaultAddress.district1 ? defaultAddress.district1 : '',
            city: defaultAddress.district2 ? defaultAddress.district2 : '',
            area: defaultAddress.district3 ? defaultAddress.district3 : '',
            address: defaultAddress.address ? defaultAddress.address : '',
            plantCode: customerInfo.plantCode ? customerInfo.plantCode : ''
        }
        let defaultparam = {
            depoCustFlag: userInfo.promptDeliveryFlag == 1 ? "1" : "0", detailList: [{
                shipToCd: defaultAddress.shipToCode ? defaultAddress.shipToCode : '', productList: params.map(el => {
                    return Object.assign({}, addressData, el)
                }),
            }]


        }
        var action = isProduce ? "https://rainbow.misumi.com.cn" : "https://rainbow-stg.misumi.com.cn"
        return new Promise((resolve, reject) => {
            WebUtils.ajaxPostSubmitPayload(`${action}/eadp/api/getDetailArrivalDateService?sessionId=${userInfo.sessionId}`, defaultparam, (res) => {
                resolve(res)
                console.log(res);
            }, (err) => {
                resolve()
                console.log(err);
            }, () => {
            })
        })

    }

}

// 订购预计到货日
function getDetailArrivalDateOrder(params) {
    return new Promise((res, rej) => {
        _getDate(params).then(r => {
            res(r)
        }).catch(err => {
            res()
        })
    })

    function _getDate(params) {
        var action = isProduce ? "https://rainbow.misumi.com.cn" : "https://rainbow-stg.misumi.com.cn"
        return new Promise((resolve, reject) => {
            WebUtils.ajaxPostSubmitPayload(`${action}/eadp/api/getDetailArrivalDateService?sessionId=${userInfo.sessionId}`, params, (res) => {
                resolve(res)
                console.log(res);
            }, (err) => {
                resolve()
                console.log(err);
            }, () => {
            })
        })

    }

}

//   跳转我的售后
function goToMyAftersale() {
    jumpUprPage('myAftersale.html')
}


//   discountInfo接口
function getSeriesCodeApi(request) {
    return new Promise((resolve, reject) => {
        //根据当前环境确定地址
        if (userInfo != undefined && userInfo.userCode != undefined) {
            var url = WebUtils.discountApi("api/temporary/v1/discountInfo/series/search");
            var params = {};
            params.seriesCode = request;
            WebUtils.ajaxGetSubmit(url, params, function (res) {
                resolve(res);
            }, function (err) {
                resolve(null);
            }, function () {
            },)

        } else {
            resolve(null);
        }
    })


}

// 非组合
function suitSeriesApi(request) {
    return new Promise((resolve, reject) => {
        var param = request || {};
        var action = apiUrl.Campaign.urlList.getECSettingFileInfo()
        WebUtils.ajaxPostSubmitJson(action, JSON.stringify(param), function (result) { //success
            resolve(result);
        }, function (error) { //error
            resolve(null);
        }, function (XHR, TS) { //complete

        }, {"x-api-key": apiUrl.Campaign.xApiKey});
    });
}

function openBigImg(url) {
    var bigImgHtml = `<div class="bigSrc" style="position: fixed;background-color: rgba(0, 0, 0, 0.7);top: 0;left: 0;width: 100%;height: 100vh;z-index: 999999;">
    <div style="position: absolute;left: 50%;top: 50%;width:100%;transform: translate(-50%, -50%);display: flex;flex-direction: column;justify-content: space-around;align-items: center;">
     <img style="width:100%" src="${url}">
    </div>
  </div>`
    $('body').append(bigImgHtml)
    $('.bigSrc').unbind('click').bind('click', function () {
        $(this).remove()
    })
}

async function getInnerBigOrderThreshold(innercd) {
    let action = `${apiUrl.Customer.urlList.getInnerInfo({})}`
    return new Promise((resolve, reject) => {
        WebUtils.ajaxPostSubmitPayload(action, {innercd}, function (result) { //
            resolve(result);
        }, function (error) { //error
            resolve('');
        }, function (XHR, TS) { //complete
        }, {"x-api-key": apiUrl.Customer.xApiKey});
    });
};

// 渲染价格带
function renderDiscount(volumeDiscountList) {
    var volumeHtml = '';
    for (var i = 0; i < volumeDiscountList.length; i++) {
        var volumeDiscountObj = volumeDiscountList[i];
        volumeHtml += '<tr>';
        var minQuantity = volumeDiscountObj.minQuantity;
        var maxQuantity = volumeDiscountObj.maxQuantity;
        if (isNull(maxQuantity)) {
            maxQuantity = "";
        }
        var unitPrice = volumeDiscountObj.unitPrice;
        var daysToShip = gettVolumeDiscountDaysShip(volumeDiscountObj.daysToShip);
        volumeHtml += '<td>' + minQuantity + '~' + maxQuantity + '</td>';
        volumeHtml += '<td>' + priceFormat(unitPrice) + addFrom() + '</td>';
        volumeHtml += '<td>' + daysToShip + '</td>';
        volumeHtml += '</tr>';
    }
    return volumeHtml

}

// 神策埋点追加
function CartPageClick(type, name) {
    sensors.track("CartPageClick", {button_type: type, button_name: name});
}

function ConfirmOrderClick(type, name) {
    sensors.track("ConfirmOrderClick", {button_type: type, button_name: name});
}

function ConfirmQuotationClick(type, name) {
    sensors.track("ConfirmQuotationClick", {button_type: type, button_name: name});
}

function OrderFinishPageClick(type, name) {
    sensors.track("OrderFinishPageClick", {button_type: type, button_name: name});
}

function QuoteFinishPageClick(type, name) {
    sensors.track("QuoteFinishPageClick", {button_type: type, button_name: name});
}

// 显示loading
function showFullLoading() {
    loadingClass.showLoading()
}

// 隐藏loading
function hideFullLoading() {
    loadingClass.closeLoading()
}

// 完善企业弹窗
function perfectModal(fromPage, popupObj) {
    const text = `<div class="cou-info-modal modal-common no-prefect-content">
                                      <img class="tips-icon" src="../images/returnImg/img20210511_3.png">
                                      <div class="common-close close-new-modal"></div>
                                      <div class="text2">您尚未完善企业信息</div>
                                      <div class="text1">完善企业信息后，将为您开放订购/报价权限 </div>
                                      <div class="text-blue counPrefectModal" style="">完善企业信息，领新客专享大礼包</div>
                                      <div class="btn-content">
                                         <div class="btn1 join-enterprise">加入企业</div>
                                         <div class="btn2 perfect-enterprise">完善企业信息</div>
                                      </div>
                                  </div>`
    const modalObj = new modal({
        mask: true, content: text
    })
    getWsCouponApi().then(res => {
        if (res.returnFlg === 0 && res.status === 0) {
            $('.counPonCartModal').show()
        } else {
            $('.counPonCartModal').hide()
        }
    })
    // 加入企业点击事件
    $('.join-enterprise').off('click').on('click', () => {
        if (popupObj) popupObj.close()
        localStorage.setItem('redirect', JSON.stringify({
            from: 'writeBlessing', url: location.href
        }))
        jumpUprPageNew('enterpriseJoin.html')
    })
    // 完善企业信息点击事件
    $('.perfect-enterprise').off('click').on('click', () => {
        if (popupObj) popupObj.close()
        localStorage.setItem('redirect', JSON.stringify({
            from: 'writeBlessing', url: location.href
        }))
        jumpUprPageNew('enterpriseInfoPrefect.html')
    })
}

// 需补差价
function lowVolumeChargeMessage(param) {
    let text = ''
    if (!isNull(param.lowVolumeCharge)) {
        text += `订购数量${param.quantity}件时，每件需加收 ¥${param.lowVolumeCharge.charge}(未税)/件`
        if (param.lowVolumeCharge.chargeList && param.lowVolumeCharge.chargeList.length > 0) {
            let chargeListLength = param.lowVolumeCharge.chargeList.length
            text += param.lowVolumeCharge.chargeList[chargeListLength - 1].maxQuantity ? param.lowVolumeCharge.chargeList[chargeListLength - 1].maxQuantity > 0 ? `，数量满${param.lowVolumeCharge.chargeList[chargeListLength - 1].maxQuantity + 1}个无需加价。` : param.lowVolumeCharge.chargeList[chargeListLength - 1].minQuantity ? `，数量满${param.lowVolumeCharge.chargeList[chargeListLength - 1].minQuantity}个无需加价。` : '。' : '。'
        } else {
            text += '。'
        }
        if (!isNull(text)) {
            let lowVolumeChargeHtml = ''
            lowVolumeChargeHtml += `<div class="lowVolume">
            <div class="lowVolumeChargeText">【小数量订购需加价】<a target="_blank"  href="https://www.misumi.com.cn/cmsweb/view/guide_mobile/5121/#li2">小数量订购说明</a></div>
            <div class="out-of-lowVolumeChargeMessage">${text}</div>
            </div>`
            if ($('.priceDivFloat').find('.lowVolume').length > 0) {
                $('.lowVolume').remove()
                $('.priceDivFloat').prepend(lowVolumeChargeHtml)
            } else {
                $('.priceDivFloat').prepend(lowVolumeChargeHtml)
            }
        } else {
            if ($('.priceDivFloat').find('.lowVolume').length > 0) {
                $('.lowVolume').remove()
            }
        }
    } else {
        if ($('.priceDivFloat').find('.lowVolume').length > 0) {
            $('.lowVolume').remove()
        }
    }
}

// 用户信息加密
function userEncryption() {
    return new Promise((resolve, reject) => {
        const url = isProduce ? 'https://chat.misumi.com.cn/misumi/channel/userinfo_encryption' : `https://chat-stg.misumi.com.cn/misumi/channel/userinfo_encryption`
        const action = `${url}?sessionId=${userInfo.sessionId}`;
        WebUtils.ajaxGetSubmit(action, {}, function (result) {
            resolve(result);
        }, function () {

        }, function () {

        });
    })

}


// 替代品截取
function extractFirstModel(str) {
    if (str) {
        const regex = /<([^>]+)>/;
        const match = str.match(regex);
        return match ? match[1] : null;
    } else {
        return ''
    }

}

// 型号获取
function partNumberToLink(text) {
    var fIndex = text.indexOf("&lt;") + 4;
    var lIndex = text.indexOf("&gt;");
    var hrefText = `<span style="color:#003399;margin-left:5px;">${text.substring(fIndex, lIndex)}</span><br/>`;
    return {
        partNumber: text.substring(fIndex, lIndex),
        msg: text.replace(text.substring(fIndex - 4, lIndex + 4), hrefText).replace('。', ' ').concat('。')
    }
}

// 替代品跳转
function SubstituteJumpClick(discountPartNumber) {
    if (!isNull(discountPartNumber)) {
        try {
            var requestBody = {
                requestList: [{
                    apiId: "API011", request: {
                        keyword: discountPartNumber, size: 10
                    }
                }, {
                    apiId: "API012", request: {
                        keyword: discountPartNumber, size: 10
                    }
                }]
            };
            var action = WebUtils.preEcApi(api_batch);
            WebUtils.ajaxPostSubmitJson(action, JSON.stringify(requestBody), function (result) {
                let responseList = result.responseList ? result.responseList : []
                let partNumberList = responseList.find(el => el.apiId == "API012").response.partNumberList
                let seriesCodeItem = partNumberList.find(el => el.partNumber == discountPartNumber)
                if (!isNull(seriesCodeItem) && !isNull(seriesCodeItem.seriesCode)) {
                    gotoProductInfo(seriesCodeItem.seriesCode, discountPartNumber, '', '', true);
                } else {
                    var url = jumpUrl + "/vona2/result/?Keyword=" + encodeURIComponent(discountPartNumber) + '&isDiscount=1';
                    window.location.href = url;
                }
            }, function (error) {
                var url = jumpUrl + "/vona2/result/?Keyword=" + encodeURIComponent(discountPartNumber) + '&isDiscount=1';
                window.location.href = url;
            }, function (XHR, TS) { //complete

            })

        } catch (err) {

        }
    }
}

// 注册登录记录神策来源
function sourcePageSensors() {
    let source_page = ''
    let getUrlParam = parseUrlQueryAfterDecode()
    if (!isNull(getUrlParam.sourcePage)) {
        if (getUrlParam.sourcePage == 'index') {
            source_page = '首页底部-注册登录'
        } else if (getUrlParam.sourcePage == 'class') {
            source_page = '商品分类页底部-注册登录'
        } else if (getUrlParam.sourcePage == 'endClass') {
            source_page = '商品末端页底部-注册登录'
        } else if (getUrlParam.sourcePage == 'cart') {
            source_page = 'Tarbar购物车-注册登录'
        } else if (getUrlParam.sourcePage == 'my') {
            source_page = 'Tarbar我的-注册登录'
        } else if (getUrlParam.sourcePage == 'indexGotEnrprise') {
            source_page = '首页底部-完善企业信息'
        } else if (getUrlParam.sourcePage == 'classGotEnrprise') {
            source_page = '商品分类页底部-完善企业信息'
        } else if (getUrlParam.sourcePage == 'endClassGotEnrprise') {
            source_page = '商品末端页底部-完善企业信息'
        }
    }
    return source_page
}

// 零点清除
function clearLocalStorageAtMidnight(key) {
    let keyValue = localStorage.getItem(key)
    if (!keyValue) {
        return true
    }

    let now = new Date();
    let midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59); // 当天23:59:59
    let timeUntilMidnight = midnight - now; // 计算当前时间到午夜的毫秒数
    let daytime = midnight - new Date(keyValue)
    console.log(isSameDay(now, new Date(keyValue)))

    // 如果时间已经过了当天的零点，则清空localStorage
    if (!isSameDay(now, new Date(keyValue))) {
        console.log('1111')
        localStorage.removeItem(key)
        return true
    } else {
        if (timeUntilMidnight <= 0) {
            console.log('2222')
            localStorage.removeItem(key)
            return true
        } else {
            if (timeUntilMidnight > daytime) {
                console.log('33333')
                localStorage.removeItem(key)
                return true
            } else {
                console.log('444')
                return false
            }
            // 否则，设置一个延迟，在当天零点时执行清空操作
        }
    }
}


function isSameDay(date1, date2) {
    return (date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate());
}

function r(size) {
    const baseSize = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--base-size'));
    return size * baseSize;
}

function estimateDateAlter2(e) {

    new MessageModal({
        title: "温馨提示",
        text: "预计到货日仅供参考，受库存调拨、配送线路、天气情况等影响，实际到货时间可能有差异。",
        isAlert: true,
        onClose: () => {
            this.visibleOfDeleteFailedMessageModal = false
        }
    });
    e.stopPropagation()

}

// 弹出换绑手机号弹窗
function openChangePhonePopup(str, isTips) {
    $('body').css({
        overflow: 'hidden',
    })
    // 创建mask
    const mask = $("<div></div>")
    mask.attr('id', 'change-popup-mask')
    mask.css({
        position: 'absolute',
        width: '100%',
        height: '100%',
        zIndex: '9998',
        background: 'rgba(0,0,0,0.5)',
        left: 0,
        top: 0,
        display: 'flex',
        algignItems: 'center',
        justifyContent: 'center'
    })
    const content = $("<div></div>")
    content.attr('id', 'change-popup')
    content.css({
        position: 'absolute',
        width: r(7.02),
        zIndex: '9998',
        background: '#fff',
        left: '50%',
        top: '50%',
        transform: 'translate(-50%,-50%)',
        borderRadius: r(0.1),
        display: 'flex',
        flexDirection: 'column',
    })
    const close = $("<div></div>")
    close.attr('id', 'change-close')
    close.css({
        position: 'absolute',
        width: r(0.3),
        height: r(0.3),
        right: r(0.25),
        top: r(0.25),
        background: 'url(/static/html/images/icon/ic_popup_close.png) no-repeat',
        backgroundSize: '100% 100%'
    })
    const icon = $("<div></div>")
    icon.attr('id', 'change-icon')
    icon.css({
        width: r(0.8),
        height: r(0.8),
        background: 'url(/static/html/images/returnImg/imgvx20210810133930.png) no-repeat',
        backgroundSize: '100% 100%',
        marginTop: r(0.6),
        marginLeft: 'auto',
        marginRight: 'auto'
    })
    const text = $(`<div>${str}</div>`)
    text.css({
        marginTop: r(0.4), color: '#333333', fontSize: r(0.28), paddingLeft: r(0.3), paddingRight: r(0.3)
    })
    let btn
    if (!isTips) {
        btn = $("<div>换绑手机号</div>")
    } else {
        btn = $("<div>我知道了</div>")
    }
    btn.css({
        background: '#FFCC00',
        color: '#4a4a4a',
        width: r(2.48),
        height: r(0.72),
        lineHeight: r(0.72) + 'px',
        textAlign: 'center',
        fontSize: r(0.28),
        borderRadius: r(0.05),
        display: 'inline-block',
        marginTop: r(0.6),
        marginBottom: r(0.6),
        marginLeft: 'auto',
        marginRight: 'auto'
    })
    close.on('click', function () {
        closeChangePhonePopup()
    })
    btn.on('click', function () {
        if (!isTips) {
            closeChangePhonePopup()
            jumpUprPageNew('myInfoSet.html', {changePhone: 1, backUrl: window.location.href})
        } else {
            closeChangePhonePopup()
        }
    })
    if (!isTips) {
        content.append(close)
    }
    content.append(icon)
    content.append(text)
    content.append(btn)
    $('body').append(mask)
    $('body').append(content)
}

// 关闭换绑手机号弹窗
function closeChangePhonePopup() {
    $('body').css({
        overflow: '',
    })
    $('#change-popup-mask').remove()
    $('#change-popup').remove()
}

function yidunCheckFun(phone, scene = 'login') {
    return new Promise((r) => {
        try {
            loadJs_(`${location.origin}/static/html/js/dist/YiDunProtector-Web-2.0.7.js`, async function () {
                const YiDunNeg = createNEGuardian({appId: 'YD00033342199571', timeout: 6000})
                const result = await YiDunNeg.getToken()
                if (result.code === 200 || result.code === 201 && phone) {
                    const apiResult = await riskYiDunCheck({
                        platform: 'mbSite', token: result.token, phone: phone.replace(/\s/g, ""), scene: scene
                    })
                    if (scene === 'verify') {
                        r(apiResult)
                    } else {
                        if (apiResult && apiResult.masterData && apiResult.masterData.state == 'rejected') {
                            localStorage.setItem('change-phone-popup', apiResult.masterData.rejectReason)
                        }
                        r(apiResult)
                    }

                } else {
                    r(false)
                }
            })

        } catch (e) {
            console.log(e)
            r(false)
        }
    })

}

function sensorsProductClick(RecommendObj) {
    if (isMiniProgram()) {
        sensors.track("ProductClick", RecommendObj);
    }
}

function sensorsPageSort(RecommendObj) {
    if (isMiniProgram()) {
        sensors.track("PageSort", RecommendObj);
    }
}

function sensorsfilterResult(RecommendObj) {
    if (isMiniProgram()) {
        sensors.track("FilterResult", RecommendObj);
    }
}

function sensorsCodeFix(RecommendObj) {
    if (isMiniProgram()) {
        sensors.track("CodeFix", RecommendObj);
    }
}

function reloadPage1() {
    const userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    //选择型号前判断是否登录
    const clearModel = sessionStorage.getItem('clearModel')
    sessionStorage.removeItem('clearModel')
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        if (clearModel) {
            location.replace(location.origin + location.pathname)
            return true;
        } else {
            localStorage.setItem('redirect', JSON.stringify({
                from: 'complexProduct',
                url: location.href,
                isSelectModel: 1
            }))
            setTimeout(() => {
                showLoginDialog();
            }, 1000)
            return true;
        }
    }
}

function reloadPageDetails() {
    const userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {}
    if (isNull(userInfo) || isNull(userInfo.sessionId)) {
        if (!isNull(getUrlParam("HissuCode"))) {
            sessionStorage.removeItem('clearModel')
            const url = location.origin + location.pathname
            window.location.replace(url);
            return
        }
    }
    var isBack = sessionStorage.getItem('isBack')
    if (isBack && isBack == 'true') {
        var redirect = localStorage.getItem('redirect')
        localStorage.removeItem('redirect')
        sessionStorage.removeItem('isBack')
        if (redirect) {
            redirect = JSON.parse(redirect)
            if (redirect.url) {
                window.location.replace(redirect.url);
            } else {
                location.reload()
            }

        }
    }
}
