var smsFlag=false;
var smsShowFun=null;
var hasScroll=false;
var isWeixin = function(){
    var ua = navigator.userAgent.toLowerCase();  
    return ua.match(/MicroMessenger/i) == "micromessenger"
}
$(function(){
    //首页执行，灰色主题
    if(window.pageObj && window.pageObj.isHomePage==1){
        gray()
    }
    if(tenant.unittype!='portal-saas-mall'){
        //节日挂件
        festival()
        //智慧客服
        smartServiceInit()
    }
    //防钓鱼
    if(tenant.tenantId!=268516 && tenant.unittype!='portal-saas-mall'){
        preventFish()
    }
    if(isWeixin() && tenant.unittype!='portal-saas-mall'){
        wxShare()
    }
    //微信小程序
    if(window.__wxjs_environment === 'miniprogram'){
        $require(['static/js/jweixin.js','pl_util'],function(){
            wx.miniProgram.postMessage({
                data: {
                    shareTitle:encodeURIComponent(document.title),
                    shareDesc:getmeta("description"),
                    shareUrl:encodeURIComponent(location.href)
                }
            })
        })
    }
})
//通过name获取对应meta的content值
function getmeta(name) {
    var _metas = document.getElementsByTagName("meta")
    for (var i = 0, _item; (_item = _metas[i++]); ) {
        if (_item.getAttribute("name") && _item.getAttribute("name").toLowerCase() === name) {
            return encodeURIComponent(_item.content)
        }
    }
}
//灰色主题
function gray(){
    $require(['cmsAjax'],function(c){
        let url = window.location.origin + "/ndesigner/api/gray"
        c.cmsAjax.postJson(url).then(function(res){
            if(res.code == 200){
                $("html")[0].style="filter:progid:DXImageTransform.Microsoft.Basiclmage\(grayscale=1\);-webkit-filter\:grayscale\(100%\)\;"
            }
        })
    })
}
//节日挂件
function festival(){
    if(!isFrontEnv()){
        return
    }
    $require(['cmsAjax'],function(c){
        let url = "/fwebapi/cms/lowcode/festivalPendant/getSettings"
        c.cmsAjax.get(url).then(function(resp){
            if(resp.data && resp.data.code == 200 && resp.data.settings){
                let res = resp.data.settings
                if(res.location==1 && window.pageObj && window.pageObj.isHomePage!=1){
                    return
                }
                let canTime = (res.showTime && res.showTime.length==2 && res.nowTime>=res.showTime[0] && res.nowTime<=res.showTime[1]) || !res.showTime || res.showTime.length==0
                if(res.isOpen && canTime){
                    $require(['static/js/restival.js'],function(r){
                        r.init(res)
                    })
                }
            }
        })
    })
}
//智慧客服
function smartServiceInit(){
    if(!isFrontEnv()){
        return
    }
    $(window).on('mousemove scroll touchmove tap click keydown',function(){
        if(!hasScroll){
            hasScroll = true
            getSmSvs(function(resp){
                $require([`css!/npublic/commonjs/smartService/t.css`,'static/js/smartService.js'],function(r,smartService){
                    let set = {}
                    try{
                        set = JSON.parse(resp.setting.colorLayout)
                    }catch(e){}
                    if(set.entranceLocation==1){
                        let dom = `<a href="javascript:;" smartService class="smartIcon ${set.windowLocation=='left'?'leftIcon':''}" style="color:${set.windowColor};">
                            <svg t="1691993598192" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="814" width="200" height="200"><path d="M508.30872719 128.08273435c200.36824869 0 362.83837999 164.57253407 362.83837996 367.57335931 0 203.01910646-162.45184851 367.59164208-362.83837996 367.59164209v-55.13783256c170.33129377 0 308.41353791-139.89213981 308.41353633-312.43552832 0-172.57995248-138.08224413-312.45380951-308.41353633-312.45380952s-308.41353791 139.89213981-308.41353791 312.43552831c0 5.48453223 0.12797313 10.93250049 0.40219903 16.34390634H145.81770106c-0.23766351-5.41140585-0.36563506-10.8593741-0.36563663-16.34390634C145.45206443 292.65526841 307.94047692 128.08273435 508.32700838 128.08273435z" p-id="815"></path><path d="M508.30872719 240.40595711c139.16086813 0 251.95941786 114.27937278 251.95941629 255.25013655 0 140.98904501-112.79854975 255.26841777-251.95941629 255.26841777-36.65495788 0-71.46345612-7.91600767-102.87154529-22.1757924l-65.81438835 34.62568148c-9.89044049 5.19202354-22.06610207 1.27972351-27.18499926-8.72040577a20.65840542 20.65840542 0 0 1-2.01099519-12.76067896l12.10253519-73.76696156a256.18250777 256.18250777 0 0 1-66.18002497-172.47026056c0-140.97076381 112.79854975-255.25013657 251.95941787-255.25013655zM381.28695667 446.66093709c-24.4975775 0-44.33330364 20.10995203-44.33330366 44.91832098 0 24.80836739 19.85400733 44.91831942 44.33330366 44.91831943 24.4975775 0 44.35158484-20.10995203 44.35158486-44.91831943 0-24.80836739-19.85400733-44.91831942-44.35158486-44.91832098z m127.00348775 0c-24.4975775 0-44.35158484 20.10995203-44.35158488 44.91832098 0 24.80836739 19.85400733 44.91831942 44.35158488 44.91831943s44.33330364-20.10995203 44.33330363-44.91831943c0-24.80836739-19.85400733-44.91831942-44.33330363-44.91832098z m126.98520652 0c-24.4975775 0-44.35158484 20.10995203-44.35158484 44.91832098 0 24.80836739 19.85400733 44.91831942 44.35158484 44.91831943s44.35158484-20.10995203 44.35158484-44.91831943c0-24.80836739-19.85400733-44.91831942-44.35158484-44.91832098zM183.47815657 388.70771279l43.82141265 251.79488075a34.91819015 34.91819015 0 0 1-27.33125199 40.36615843l-0.65814374 0.10969033c-62.21287819 11.11531881-121.53723669-30.96932612-132.50630275-93.9866024L56.71233074 529.00205007c-10.96906446-63.03555904 30.5671271-123.12775168 92.79828807-134.24307046l33.96753776-6.06954959zM840.52513489 388.70771279L790.707299 674.89061152l33.98581895 6.06954959c62.21287819 11.11531881 121.53723669-30.96932612 132.50630273-93.98660398l10.09153845-57.97150706c10.96906446-63.03555904-30.5671271-123.12775168-92.7982881-134.24307046l-33.96753614-6.06954959zM464.96263993 808.10990319h86.6738933c23.94912413 0 43.32780605 19.65290783 43.32780446 43.89454063 0 24.25991557-19.37868034 43.91282183-43.32780446 43.91282183h-86.6556121c-23.94912413 0-43.36437003-19.65290783-43.36437003-43.91282183 0-24.2416328 19.41524431-43.89454063 43.34608883-43.89454063z" p-id="816"></path></svg>
                        </a>`
                        $("body").append(dom)
                        $(".smartIcon").hover(function(){
                            $(this).css({
                                "background-color": set.windowColor,
                                "color": "#fff"
                            })
                        },function(){
                            $(this).css({
                                "background-color": "#fff",
                                "color": set.windowColor
                            })
                        })
                    }
                    $(document).on("click","[smartService]",showAndInit)
                    //主动关闭标识
                    let smartServiceClose = sessionStorage.getItem('smartServiceClose')
                    if(set.showFlag==1 && resp && smartServiceClose!='true'){
                        showAndInit()
                    }
                    function showAndInit(){
                        if(smsShowFun){
                            if($(".smartService.show").length>0){
                                smsShowFun.closeDialog()
                                return  
                            }
                            if(smsFlag){
                                smsShowFun.showFun()
                            }else{
                                smsShowFun()
                            }
                            return
                        }
                        smsFlag = true
                        smsShowFun = new smartService(resp)
                        if(window.ZQSensorsObj){
                            let obj = {
                                tenantId: tenant.tenantId, 
                                iBusinessCode : "01",
                                iBusinessName : "智慧客服业务线",
                                iBusinessCustId : localStorage.getItem(`account_${tenant.tenantId}`)
                            }
                            ZQSensorsObj.track('SmartServiceWakeUp',obj);
                        }
                    }
                })
            })
        }
    })
    //请求接口数据
    function getSmSvs(callback){
        $require(['cmsAjax'],function(c){
            let domain = __ce.smartServiceUrl || 'https://web-visitor.yun300.cn'
            let url = `${domain}/visitormanager/intelligent/front/checkAndRegister?tenantId=${tenant.tenantId}&instance=${tenant.bossProductInstance}`
            let data = {
                account:localStorage.getItem(`account_${tenant.tenantId}`)
            }
            c.cmsAjax.postJson(url,data).then(function(res){
                if(res.status==200 && res.data){
                    localStorage.setItem(`account_${tenant.tenantId}`,res.data.account)
                    callback(res.data)
                }
            })
        })
    }
}
//防钓鱼
function preventFish(){
    var req = location.hostname
    var rel = getCookie('realhost') || ""
    if(rel && rel != req){
        var url = "/repository/cheat?req="+req+"&rel="+rel
        $.ajax({
            url:url
        })
    }
}
//自定义微信分享
function wxShare(){
    $require(['cmsAjax','static/js/jweixin.js','pl_util'],function(c){
        let url = "/fwebapi/cms/api/tdk/getWxShareInfo"
        let data = {
            pageUrl:location.href,
            appCode:pageObj.appId,
            tid:pageObj.contentType,
            pageType:pageObj.pageType,
            isHomePage:pageObj.isHomePage,
            pageId:pageObj.pageId,
            contentId:pageObj._detailId,
            pageName:pageObj.name
        }
        function imgxaf(src,v){
            var imgParam = src.indexOf('?')>-1 ? src.split('?')[1] : "";
            var imgSrc = src.split('?')[0]
            var paramStr = imgParam ? "?" + imgParam : "";
            return imgSrc + "_" + v + "xaf" + imgSrc.substr(imgSrc.lastIndexOf('.')) + paramStr
        }
        c.cmsAjax.postJson(url,data).then(function(resp){
            let data = resp.data
            if(data.data){
                data = data.data
            }
            if(data.wxJsConfig){
                let obj = data.wxJsConfig
                let content = data.wxShareContent
                let sharObj = {
                    title: content.title, // 分享标题
                    desc: content.desc, // 分享描述
                    link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: imgxaf($.handleDataImg(content.imgUrl),104)
                }
                console.log("分享数据：",sharObj)
                wx.config({
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: obj.appId, // 必填，公众号的唯一标识
                    timestamp: obj.timestamp, // 必填，生成签名的时间戳
                    nonceStr: obj.nonceStr, // 必填，生成签名的随机串
                    signature: obj.signature,// 必填，签名
                    jsApiList: ['updateAppMessageShareData','updateTimelineShareData'] // 必填，需要使用的JS接口列表
                });
                wx.ready(function () {   //需在用户可能点击分享按钮前就先调用
                    wx.updateAppMessageShareData(sharObj)
                    wx.updateTimelineShareData(sharObj)
                }); 
            }
            
        })
    })
}