/* eslint-disable */
/*================================*/
/*========   XGL VUE PLUGINS  =======*/
/*================================*/
import axios from 'axios'
import qs from "qs";
import {
    TweenMax,
    TimelineMax
} from 'gsap'

"use strict"
let def, deviceInfo, viewportScale;
/**
 * 
 * [初始化公共插件方法]
 * @param  {[string]} opt [带入参数]
 * 
 **/
let initial = function (opt) {
    // 默认参数
    var _def = {
        debug: false,
        version: '1.2.0', //当前版本号
        resourceDomain: 'cdn.xglpa.com', //资源域名
        ajaxUrl: '', //ajax请求domain- 使用ajax方法必传 
        ajaxFailMessage: '当前参与人数过多，请稍后重试', //ajax错误 默认显示信息
        btnEnable: true, //默认按钮可点击状态
        envDetect: true, //是否检测浏览器环境 
        formalURL: '', //正式上线地址
        targetEnv: '', //上线环境  wx-微信 | jgj-金管家 | zhane-展E宝  ['wx','jgj','zhan
        PALifeOpenVer: 1.6, //金管家js版本号
        PALifeWebSDKUrl: { //金管家外部分享方法
            test: '//stg2-lilith.cdn.lifeapp.pingan.com.cn/lilith/lib/PALifeWebSDK.1.0.js',
            product: '//elis-ecocdn.pingan.com.cn/lilith/lib/PALifeWebSDK.1.0.js'
        },
        jgjEventId: '', //金管家trackEvent event-id    目标环境为jgj时为必须
        jgjLabelId: '', //金管家trackEvent label-id 

        wxJsConfigUrl: 'https://wx.xfhd.net/wxapi/api/jsconfig?appid=wx41d80a1bb01f658d', //默认szxgl 初始化
        /*
        信广龙互动公众号：
        appid：wx41d80a1bb01f658d
        js安全域名：*.szxgl.cn; *.xfhd.net; *.xglpa.com

        信蜂互动公众号：
        appid：wx35766a64d73d08a9
        js安全域名：*.xglpa.com; xgl.lx666.wang; h5.thinkxgl.com
        */
        wxAutoInitShare: true, //微信初始化后自动设置分享
        watchLand: false, //检测 横屏提示
        demoConfig: { //是否为开发模式 debug样式显示
            visible: false, //是否默认显示
            logo: true, //是否显示logo
            position: 'bottomRight', //bottomRight - 右下角 | bottom - 居中底部
            language: 'CN', // CN - 开发版 | EN - Demo
            text: '', //自定义文字 三个字以内最佳 | language无效
            touchHide: true //是否点击后隐藏
        },
        wxShareConfig: {
            title: '默认分享标题', //分享标题
            desc: '默认分享描述', //分享描述
            url: '', //分享url
            imgUrl: '', //分享图片url
            wxReady: function () { }
        },
        envHandle: { //根据不同浏览器环境初始化方法
            pc: function () { }, //如若是PC端  初始化
            mobile: function () { }, //如若是非PC端 即移动端 初始化
            ios: function () { }, //如若是苹果端 初始化xxx
            adr: function () { }, //如若是安卓端 初始化xxx
            wx: function () { }, //如若目标环境是微信   初始化xxx
            jgj: function () { }, //如若目标环境是金管家 初始化xxx
            zhane: function () { }, //如若目标环境是zhane 初始化xxx
            //=======================       ==========//
            notWX: function () { }, //如若是非微信环境      初始化
            notJGJ: function () { }, //如若是非金管家华景    初始化 
        }
    };
    def = _extend(_def, opt, true);

    //初始化自身内部方法
    _initSlef();

    //开始检测浏览器环境
    if (def.envDetect || def.targetEnv != '') detectEnv();

    if (def.demoConfig.visible) showDemo();

    //是否检测屏幕横竖方向
    if (def.watchLand) orientation();

    //检测是否为正式环境
    if (def.formalURL != '' && def.formalURL != undefined && def.formalURL != null) {
        checkFormalEnv()
    } else {
        window.formalEnv = 'plugin > formalURL is not defined';
    }

    _print('xgl-vue-plugins version ' + _def.version)

    //目标环境初始化
    handleTargetEnv();

}

//初始化插件自身内部方法
let _initSlef = function () {
    Function.prototype.makeMulti = function () {
        var l = new String(this)
        l = l.substring(l.indexOf("/*") + 3, l.lastIndexOf("*/"))
        return l
    }
    //原型链扩展once方法
    Element.prototype.once = function (type, callback) {
        var handle = function () {
            callback()
            removeEventListener(type, handle)
        }
        addEventListener(type, handle)
    }

    //缩放弹窗
    try {
        //检测viewport 缩放
        var viewport = document.getElementsByTagName('meta')['viewport'];
        var content = viewport.getAttribute('content').split(',');
        content.forEach((item, index) => {
            if (item.indexOf('initial-scale') > -1) viewportScale = item.replace('initial-scale=', '')
        })
    } catch (e) {
        _print('缩放检测失败', e)
    }

}
//原生实现对象融合
let _extend = function (o, n, override) {
    for (var key in n) {
        if (n.hasOwnProperty(key) && (!o.hasOwnProperty(key) || override)) {
            o[key] = n[key];
        }
    }
    return o;
}
//打印方法
let _print = function (params) {
    def.debug && console.log(...arguments)
}
//增加样式
let _addStyle = function (styles) {
    var element = document.createElement("style");

    element.type = "text/css";

    try {
        element.appendChild(document.createTextNode(styles));

    } catch (ex) {

        element.styleSheet.cssText = styles; //针对IE

    }

    var head = document.getElementsByTagName("head")[0];

    head.appendChild(element);
}
//原生addClass
let _addClass = function (elem, className) {
    if (!className) return;

    var els = Array.isArray(elem) ? elem : [elem];

    els.forEach((el) => {
        if (el.classList) {
            el.classList.add(className.split(' '));
        } else {
            el.className += ` ${className}`;
        }
    });
}
//原生removeClass
let _removeClass = function (elem, className) {
    if (!className) return;

    var els = Array.isArray(elem) ? elem : [elem];
    els.forEach((el) => {
        if (el.classList) {
            el.classList.remove(className.split(' '));
        } else {
            el.className = el.className.replace(new RegExp(`(^|\\b)${className.split(' ').join('|')}(\\b|$)`, 'gi'), ' ');
        }
    });
}
//原生实现append
let _append = function (parent, text) {
    if (typeof text === 'string') {
        var temp = document.createElement('div');
        temp.innerHTML = text;
        // 防止元素太多 进行提速
        var frag = document.createDocumentFragment();
        while (temp.firstChild) {
            frag.appendChild(temp.firstChild);
        }
        parent.appendChild(frag);
    } else {
        parent.appendChild(text);
    }
}
//原生实现remove
let _remove = function (selectors) {
    selectors.removeNode = [];
    if (selectors.length != undefined) {
        var len = selectors.length;
        for (var i = 0; i < len; i++) {
            selectors.removeNode.push({
                parent: selectors[i].parentNode,
                inner: selectors[i].outerHTML,
                next: selectors[i].nextSibling
            });
        }
        for (var i = 0; i < len; i++)
            selectors[0].parentNode.removeChild(selectors[0]);
    } else {
        selectors.removeNode.push({
            parent: selectors.parentNode,
            inner: selectors.outerHTML,
            next: selectors.nextSibling
        });
        selectors.parentNode.removeChild(selectors);
    }
}
/**
 * [异步加载js]
 * @param  {[string]} src [js文件路径]
 * @param  {[function]} callback [加载完成回调函数]
 */
let loadJs = function (src, callback) {
    var _ = document.createElement('script');
    _.async = 'async';
    _.src = src;
    _.onload = callback || function () { };
    document.getElementsByTagName('body')[0].appendChild(_);
}
/*
 * [目标环境预处理]
 */
let handleTargetEnv = function () {
    def.targetEnv = def.targetEnv.toLowerCase();
    // loadJs('//res.wx.qq.com/open/js/jweixin-1.2.0.js', () => {
    //     // loadJs('//res.wx.qq.com/open/js/jweixin-1.6.0.js', () => {
    //     wxSdkInitialize(def.wxAutoInitShare);
    //     wx.ready(() => {
    //         console.log('======> 微信JSSDK初始化ready成功-loadJs <=======');
    //         _print('======> 微信JSSDK初始化ready成功-loadJs <=======');
    //         def.envHandle.wx && def.envHandle.wx();
    //     })
    //     console.log(12312321);
    //     console.log(wx);
    // })
    // //目标环境包含 微信
    if (def.targetEnv.indexOf('wx') > -1) {
        try {
            if (!wx) return
            wxSdkInitialize(def.wxAutoInitShare);
            wx.ready(() => {
                console.log('======> 微信JSSDK初始化ready成功-wx <=======');
                _print('======> 微信JSSDK初始化ready成功-wx <=======');
                def.envHandle.wx && def.envHandle.wx();
            })
        } catch (e) {
            loadJs('//res.wx.qq.com/open/js/jweixin-1.2.0.js', () => {
                // loadJs('//res.wx.qq.com/open/js/jweixin-1.6.0.js', () => {
                wxSdkInitialize(def.wxAutoInitShare);
                wx.ready(() => {
                    console.log('======> 微信JSSDK初始化ready成功-loadJs <=======');
                    _print('======> 微信JSSDK初始化ready成功-loadJs <=======');
                    def.envHandle.wx && def.envHandle.wx();
                })
            })
        }
    }

    //目标环境包含 金管家
    if (def.targetEnv.indexOf('jgj') > -1) {
        try {
            if (!PALifeOpen) return
            PALifeOpen.config();
            _print('======> 金管家JSSDK初始化成功 <=======');
            def.envHandle.jgj && def.envHandle.jgj();
            jgjReady();
        } catch (e) {
            _print('======> 金管家JSSDK尚未加载，即将开始加载' + def.PALifeOpenVer + '版本JSSDK <=======');
            loadJs('//elis-ecocdn.pingan.com.cn/lilith/lib/PALifeOpen.' + def.PALifeOpenVer + '.min.js', () => {
                PALifeOpen.config();
                _print('======> 金管家JSSDK初始化成功 <=======');
                def.envHandle.jgj && def.envHandle.jgj();
                jgjReady();
            })
        }

    }

    //目标环境包含 展e宝
    if (def.targetEnv.indexOf('zhane') > -1) {
        loadJs('//salescdn.pa18.com/salesinfo/eLifeAssist/common/wxRecord.js', () => {
            def.envHandle.zhane && def.envHandle.zhane();
            _print('=====> 展E宝wxRecord初始化成功 <======');
        })
    }
}

/**
 * @description: 金管家JSSDK准备就绪
 * @param {callbackFun} 执行回调函数
 * @return {type} 
 */
let jgjReady = function (callbackFun) {
    callbackFun && callbackFun();
};
/**
 * [微信JSSDK初始化]
 * @param  {[string]} justInit [仅仅初始化]
 */
let wxSdkInitialize = function (setShare) {
    rebuildAjax.get(def.wxJsConfigUrl, {
        url: window.location.href.split("#")[0]
    })
        .then(data => {
            if (data.ret == 0) {
                wx.config({
                    beta: true,
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.nonceStr,
                    signature: data.signature,
                    jsApiList: [
                        'onMenuShareAppMessage',
                        'onMenuShareWechat',
                        'chooseImage',
                        'previewImage',
                        'uploadImage',
                        'downloadImage',
                        'previewFile',
                        'getNetworkType',
                        'openLocation',
                        'getLocation',
                        'onHistoryBack',
                        'hideOptionMenu',
                        'showOptionMenu',
                        'hideMenuItems',
                        'showMenuItems',
                        'hideAllNonBaseMenuItem',
                        'showAllNonBaseMenuItem',
                        'closeWindow',
                        'scanQRCode',
                        'selectEnterpriseContact',
                        'openEnterpriseChat',
                        'chooseInvoice'
                    ]
                });
            } else {
                _print("js授权失败：" + data.msg);
            }
        })
        .catch(err => {
            console.log(err)
        })
    if (setShare) {
        wx.ready(() => {
            wxShare();

            //微信ready回调
            try {
                def.wxShareConfig.wxReady && def.wxShareConfig.wxReady(this);
            } catch (e) {
                _print('<wx插件>初始化失败');
            }

        });
    }
}
/**
 * [微信JSSDK初始化分享方法]
 * @param  {[object]} argument [参数]
 * argument {
 *      @param  {[function]} argument [参数]
 * }
 */
let wxShare = function (args) {
    let _def = {
        url: '', //分享地址
        title: '', //分享标题
        desc: '', //分享描述
        imgUrl: '', //分享图标地址
        shareSuccess: function (type) { }, //分享成功回调 type  = 1- 发送给朋友 | 2 - 朋友圈
        shareCancel: function (type) { }, //分享取消回调 type  = 1- 发送给朋友 | 2 - 朋友圈
        shareFail: function (type) { } //分享失败回调 type  = 1- 发送给朋友 | 2 - 朋友圈
    }

    let opts = _extend(_def, args, true);

    let url, desc, title, imgUrl;

    url = opts.url ? opts.url : def.wxShareConfig.url;
    title = opts.title ? opts.title : def.wxShareConfig.title;
    desc = opts.desc ? opts.desc : def.wxShareConfig.desc;
    imgUrl = opts.imgUrl ? opts.imgUrl : def.wxShareConfig.imgUrl;

    _print(
        '微信分享设置完成\n【分享url】=> ' + url +
        '\n【分享标题】=> ' + title +
        '\n【分享描述】=> ' + desc +
        '\n【分享图片】=> ' + imgUrl
    )
    wx.onMenuShareAppMessage({
        title: title,
        desc: desc,
        link: url,
        imgUrl: imgUrl,
        success: (res) => {
            opts.shareSuccess && opts.shareSuccess(1);
            _hmt.push(["_trackEvent", "发给朋友", "发给朋友success"]);
            _print('发给朋友-发给朋友success');
        },
        cancel: (res) => {
            opts.shareCancel && opts.shareCancel(1);
            _hmt.push(["_trackEvent", "发给朋友", "发给朋友cancel"]);
            _print('发给朋友-发给朋友cancel');
        },
        fail: (res) => {
            opts.shareFail && opts.shareFail(1);
            _hmt.push(["_trackEvent", "发给朋友", "发给朋友fail"]);
            _print('发给朋友-发给朋友fail');
        }
    });
    wx.onMenuShareTimeline({
        title: title,
        link: url,
        imgUrl: imgUrl,
        success: (res) => {
            opts.shareSuccess && opts.shareSuccess(2);
            _hmt.push(["_trackEvent", "分享到朋友圈", "分享到朋友圈success"]);
            _print('分享到朋友圈-分享到朋友圈success');
        },
        cancel: (res) => {
            opts.shareCancel && opts.shareCancel(2);
            _hmt.push(["_trackEvent", "分享到朋友圈", "分享到朋友圈cancel"]);
            _print('分享到朋友圈-分享到朋友圈cancel');
        },
        fail: (res) => {
            opts.shareFail && opts.shareFail(2);
            _hmt.push(["_trackEvent", "分享到朋友圈", "分享到朋友圈fail"]);
            _print('分享到朋友圈-分享到朋友圈fail');
        }
    });
}
/**
 * [金管家JSSDK分享方法]
 * @param  {[object]} argument [参数]
 * argument {
 *      url:    '',                     //分享地址      {[string]}
 *      title:  '',                     //分享标题      {[string]}
 *      desc:   '',                     //分享描述      {[string]}
 *      imgUrl: '',                     //分享图标地址   {[string]}
 *      shareTypes: '',                 //以 "|" 为分隔符 WXHY:微信好友 ;WXPYQ:微信朋友圈 ;XLWB:新浪微博 ;DX:短信  {[string]}
 *      shareSuccess: function(){},     //分享成功回调   {[Function]}
 *      shareCancel : function(){},     //分享取消回调   {[Function]}
 *      shareFail   : function(){}      //分享失败回调   {[Function]}
 * }
 */
let jgjShare = function (args) {
    let _def = {
        url: '', //分享地址
        type: '', //分享图专用
        title: '', //分享标题
        desc: '', //分享描述
        imgUrl: '', //分享图标地址
        shareTypes: 'WXHY|WXPYQ|XLWB|DX', //以 "|" 为分隔符 WXHY:微信好友 ;WXPYQ:微信朋友圈 ;XLWB:新浪微博 ;DX:短信  {[string]}
        shareSuccess: function () { }, //分享成功回调
        shareCancel: function () { }, //分享取消回调
        shareFail: function () { } //分享失败回调
    }

    let opts = _extend(_def, args, true);
    try {
        PALifeOpen.share({
            title: opts.title,
            content: opts.desc,
            extention: opts.url,
            imageUrl: opts.imgUrl,
            shareTypes: opts.shareTypes,
            type: opts.type
        },
            function success(rsp) {
                //成功分享返回
                if (rsp.ret == 0) {
                    opts.shareSuccess && opts.shareSuccess(rsp);
                }
                //取消分享返回
                else if (rsp.ret == -1) {
                    opts.shareCancel && opts.shareCancel(rsp);
                }
                //分享失败返回
                else if (rsp.ret == -2) {
                    opts.shareFail && opts.shareFail(rsp);
                }
            },
            function error(e) {
                _print(e);
            }
        )
    } catch (e) {
        _print('<xgl插件>初始化分享失败');
    }
}
/**
 * [初始化BGM]
 * @param  {[string]} src [js文件路径]
 * @param  {[boolean]} autoplay [加载完成回调函数]
 */
let loadMusic = function (mediaSrc, handPlay) {
    var bgAudio = null;

    var options_audio = {
        preload: 'preload',
        loop: 'loop',
        volume: 1,
        autoplay: handPlay ? '' : 'autoplay'
    };
    //loading音效
    bgAudio = new Audio();
    bgAudio.src = mediaSrc;
    for (var key in options_audio) {
        if (options_audio.hasOwnProperty(key) && (key in bgAudio)) {
            bgAudio[key] = options_audio[key];
        }
    }

    bgAudio.mute = false;

    //针对当前viewport缩放 music icon自适应
    let currentScale = 1;
    if (viewportScale && viewportScale != 1) {
        currentScale = 1 / viewportScale * .95;
    } else if (deviceInfo.system == 'Android' && viewportScale != 1) {
        currentScale = 1.65;
    }

    let styles = `.xglMusicBtn {-webkit-transform:scale(${currentScale});transform:scale(${currentScale});background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyCAMAAACd646MAAAAwFBMVEUAAACxsbG9zN2Hpsm0tLTp6enR0dHs7OyDoMGDosTJycmHpsnq6uqDocKDocO7u7uDo8XNzc2DocOGpcja2tqIpsrt7e2EpMaFpMfd3d2HpsmDosTPz8/k5OTCwsLGxsbMzMyDoMK+vr6Eo8XFxcWIpsm1tbWDosSDosWEpMbS0tKDosS/v7+FpMeFpcfc3Nzf39/j4+O4uLiEo8bV1dWFpcfW1taGpcjh4eHm5ubDw8OEo8XY2NiGpciDn8Cvr69Lr7hGAAAAPnRSTlMA9gUm7iB9EvfZnD4Y7uHRvonnXVcRDJp/SjDHhC+3ppHzx7arHebQxI51ysGGdlBENd6obWtnSD0nsK9fVBEYRG8AAAR1SURBVFjD7VfXmqowEEZFsYAK2AtiX9uuvS95/7c6SSBMIEH9vnO7c6EYnPkz7U9G+ZP/lsz3eG4ZhlUYtzIfKWjbpTtxnElx2dY/UpgeDI8T49F5o9A4OykUSmp91N9CdD1B5qVXTvTUwLyaYjhu9iXGgVrNz5t2aZop/TZXQ7pQTVQ4U4iK++xnNS3br5kjCpN74YZFLBZsfs2mrg3lzjTuxGRxx6/1qWujRGdaBEIwl6Ew3zKFNoEQzGkmcWabVFVGXmrLzmOUjSwh64rUVr+CYX6Uj+WL5qMMvryTHs3HAKNsP8Voel6LfBcwSucThRpCbfJdxCi6sOOCtO9wdTWVwJd8dMdFTaaAq6tGHya46MQdf0lUShCmfFDJsOOeRCELYdojFK3ktEfCIkoVry8ArwMKKRIWUXIIewJ4esyYJXPew/IInru4vnljE5nCHlteBs8mrm/ekYS02gTE4v4U5k2FXfKyQ1ju3J+4vC08r6xIpOARqbPa8LwxZETqSJGSSoPVBniFBdPJCX7xDg5XEKQOFBimk6tMIYVGLgRJ5wusjrerSGRDCopr9iELalpFM5nCDykortlHXFBtultRDOJgE6OUwvJYsNAXZQoOcfCJUbJhedS4JjnIqMx3sBz62WLNdEboKKMyhPY+pewZgUIzdeXE9MDRCtqwSxcurD5MOTEdg/bD9GjShRtCA66IbEGDGi8xj6bBg8GKqC9RqARx0nGnNqhrKeSwl2XfGgjb99B/WgW5qLOViW8NhO17xNrQz0V6xlYEEAhiM2yjcQRkEAdhps9hGy1DEAjXr5RSplAYH4RrRoLEQM7xcHVl7PgNhJIxjAzlSJb4nowdt8AC+nqtBRw54Er4ETamfbqwGAJyrISfXAmnd9cbiyEgiyVsA3V90StRta5MJSwAzQg77M3IlSjXUBoppEqIv8aTsO9G3gskjXc9lxyTHcavqq9ZQb7M0njXruSYzAoESVi30LUIZlkoBiBIWsNXxrpF08GfyiBWDECQwISWb8W7kASvNtPIkQ5UD0x4962oN5Jg90fjDUqpXvFJcANWqvCoJBxaWZ91IfxLkfiRFqUpi1ZPFVA7YnMWeJpyaPXk4NzVxeYsiheJjMcSMWZtB/LLHGEnCmrTcPmJWCK0jl8jURx3Q/t7jj9Xm99WwYtTJlyJICspTXGxIfOn3yYFsBPpMn65t2imYf4RbmFGrBLuNNNrxES4ha3JezGtBg08FfEQqy/qUYUZjZDpjz7qWZwrag3pZXFYVzKL6ry7mCrvJYvNjxqKVsu5JtgTRbxktaRvqiXpgIBR1LbszS6XOANdCEr5Ihz1K6CxqNzIfXFwkw1B+0Rf6mU6zp0iXqwodMLgO6Hj3DXin6kiIH35OEIkXzicLp1OyW7OfcYcJyo8Z3QwLZ6vN13P7p5uBQbTZGeqkhG782qKz83CEZ7N2jBiJ8I0LR7BOGTeKKSfdxWFknKOwFcvcU6PVdkyyvPxt4Agd+d6NAeOM3CXW135k/+UfwcV76iwOsJqAAAAAElFTkSuQmCC); position: absolute; top: 3%; right: 3%; width: 30px; height: 30px; z-index: 888; overflow: hidden; visibility: visible; -webkit-animation:musicAni 3s linear infinite; animation:musicAni 3s linear infinite; background-size:60px 30px; } .xglMusicBtn.musicPause{-webkit-animation:none; animation:none; background-position:30px 0;opacity:.5; } @-webkit-keyframes musicAni {0% {-webkit-transform:scale(${currentScale}) rotate(0deg); } 100% {-webkit-transform:scale(${currentScale}) rotate(360deg); } } @keyframes musicAni {0% {transform:scale(${currentScale}) rotate(0deg); } 100% {transform:scale(${currentScale}) rotate(360deg); } }`;

    _addStyle(styles);

    _append(document.body, '<div class="xglMusicBtn" id="xglMusicBtn"></div>');
    // TweenMax.set('.musicBtn',{autoAlpha:1})

    // document.body.once('mousedown', function(){
    //     if (bgAudio.paused && !handPlay) {
    //         bgAudio.play();
    //     }
    // })

    var musicBtn = document.getElementById('xglMusicBtn');
    musicBtn.addEventListener('mousedown', (e) => {
        _print(bgAudio.paused)
        e.stopPropagation();
        if (!bgAudio.paused) {
            _addClass(e.currentTarget, 'musicPause');
            bgAudio.pause();
            bgAudio.mute = true;
            // TweenMax.set('.musicBtn',{autoAlpha:.5})
        } else {
            _removeClass(e.currentTarget, 'musicPause');
            bgAudio.play();
            bgAudio.mute = false;
            // TweenMax.set('.musicBtn',{autoAlpha:1})
        }
    }, false)

    //页面处于后台时
    // document.addEventListener("visibilitychange", function(e){
    //     if(e.target.visibilityState == 'hidden'){
    //         $(this).addClass('musicPause');
    //         bgAudio.pause();
    //         bgAudio.mute = true;
    //     }
    //     if(e.target.visibilityState == 'visible' && !$('.musicBtn').hasClass('musicPause')){
    //         $(this).removeClass('musicPause');
    //         bgAudio.play();
    //         bgAudio.mute = false;
    //     }
    // }, false);

    //直接播放
    if (deviceInfo.app != 'WX') {
        !handPlay && bgAudio.play();
    } else {
        document.addEventListener("WeixinJSBridgeReady", function () {
            WeixinJSBridge.invoke('getNetworkType', {}, function (e) {
                bgAudio.play();
            });
        }, false);
    }


    return bgAudio;
}
/**
 * [setTimeout es6写法]
 * @param  {[Number]} time [延迟时间 毫秒ms]
 * 
 */
let sleep = function (time) {
    return new Promise((resolve) => setTimeout(resolve, time));
}
/**
 * [字符串截取 包含对中文处理]
 * @param  {string} str   [传入需要截取的字符串]    不可空
 * @param  {number} count [需要截取的长度]         不可空
 * @param  {boolean} needPoints [是否需要在结尾处添加...]         可空
 * return  [string]
 */
let cutString = function (str, count, needPoints) {
    if (str.replace(/[\u4e00-\u9fa5]/g, "**").length <= count) {
        return str;
    } else {
        var len = 0;
        var tmpStr = "";
        for (var i = 0; i < str.length; i++) { //遍历字符串
            if (/[\u4e00-\u9fa5]/.test(str[i])) { //中文 长度为两字节
                len += 2;
            } else {
                len += 1;
            }
            if (len > count) {
                break;
            } else {
                tmpStr += str[i];
            }
        }
        return tmpStr + (needPoints ? '..' : '');
    }
}
/**
 * [十进制转十六进制 Unicode编码]
 * @param  {[array]} str     [传入原数组]    不可空
 * return  [array]
 */
let decToHex = function (str) {
    var res = [];
    for (var i = 0; i < str.length; i++)
        res[i] = ("00" + str.charCodeAt(i).toString(16)).slice(-4);
    return "\\u" + res.join("\\u");
}
/**
 * [十六进制转十进制 Unicode解码]
 * @param  {[array]} str     [传入原数组]    不可空
 * return  [array]
 */
let hexToDec = function (str) {
    str = str.replace(/\\/g, "%");
    return unescape(str);
}
/**
 * [数组随机排序]
 * @param  {[array]} arr     [传入原数组]    不可空
 * return  [array]
 */
let randomSortArray = function (array) {
    var arr = array;
    array.sort(function () {
        return 0.5 - Math.random()
    })
    return arr
}
/**
 * [生成范围随机数]
 * @param  {[string|number]} min    [传入原数组]    不可空
 * @param  {[string|number]} max    [取出元素的个数] 不可空
 * return  [number]
 */
let rangeRandom = function (min, max) {
    let _min = Number(min),
        _max = Number(max),
        Range = _max - _min,
        Rand = Math.random();
    return (_min + Math.round(Rand * Range));
}
/**
 * [随机从数组中取出几个元素]
 * @param  {[array]} arr     [传入原数组]    不可空
 * @param  {[string]} count   [取出元素的个数] 不可空
 * return  [array]
 */
let getRandomElements = function (arr, count) {
    var shuffled = arr.slice(0),
        i = arr.length,
        min = i - count,
        temp, index;
    while (i-- > min) {
        index = Math.floor((i + 1) * Math.random());
        temp = shuffled[index];
        shuffled[index] = shuffled[i];
        shuffled[i] = temp;
    }
    return shuffled.slice(min);
}
/**
 * [根据当前url生成带随机参数的url * 为了兼容老版本安卓无法reload的问题]
 * @param  {[string]} url     [需要更新的url地址] 不可空
 * @param  {[string]} key     [参数名] 可空
 * 
 */
let updateUrl = function (url, key) {
    var key = (key || 't') + '='; //默认是"t"
    var reg = new RegExp(key + '\\d+'); //正则：t=1472286066028
    var timestamp = +new Date();
    if (url.indexOf(key) > -1) { //有时间戳，直接更新
        return url.replace(reg, key + timestamp);
    } else { //没有时间戳，加上时间戳
        if (url.indexOf('\?') > -1) {
            var urlArr = url.split('\?');
            if (urlArr[1]) {
                return urlArr[0] + '?' + key + timestamp + '&' + urlArr[1];
            } else {
                return urlArr[0] + '?' + key + timestamp;
            }
        } else {
            if (url.indexOf('#') > -1) {
                return url.split('#')[0] + '?' + key + timestamp + location.hash;
            } else {
                return url + '?' + key + timestamp;
            }
        }
    }
}
/**
 * [cookie的存、取]
 * @param  {[string]} name    [cookie名] 不可空
 * @param  {[string]} value   [cookie值] 可空 | 当为空时为取cookie方法
 * @param  {[object]} options [配置参数] 
 * options = {
 *     @param  {[date or number]} expires  [过期参数]
 *     @param  {[string]} path       [cookie存储路径]                  
 *     @param  {[string]} domain     [域名]      
 *     @param  {[string]} secure     [安全]                
 * }
 * 
 */
let getSetCookie = function (name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options = _extend({}, options, true);
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = $.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}
/**
 * [截取页面url传递字符串]
 * @param  {[string]} name    [参数名] 不可空             
 * return  {string}
 * 
 */
let getQueryString = function (name) {

    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
//检测是否为正式环境
let checkFormalEnv = function () {
    if (window.location.href.toLowerCase().indexOf(def.formalURL) > -1) {
        window.formalEnv = true;
        return true;

    } else {
        window.formalEnv = false;
        return false;
    }
}
/** [detectEnv()方法，用以检测环境]
 *  针对开发常用环境提供检测
 *  PC     MAC | Windows | Safria | Chrome | Maxthon
 *  Mobile     = Android | IOS | WX | JGJ 
 *  screenSize = 1 - 类似华为部分带bar的矮屏 | 2 - 普通手机屏幕尺寸 iphone 5 6 7 8 普通安卓 等 | 3 - iphoneX及安卓大屏
 */
let detectEnv = function () {
    var ua = navigator.userAgent.toLowerCase();
    var info = {
        device: 'Unknow', //设备
        system: 'Unknow', //系统
        app: 'Unknow', //软件
        brand: 'Unknow' //手机品牌
    }




    if (!!ua.match(/applewebkit.*mobile.*/)) { //移动端
        def.envHandle.mobile && def.envHandle.mobile();
        info.device = 'Mobile';
        if (ua.indexOf('android') > -1 || ua.indexOf('linux') > -1 || ua.indexOf('adr') > -1) { //android){   //安卓
            def.envHandle.adr && def.envHandle.adr();
            info.system = 'Android';
            if (ua.indexOf('huawei') > -1 || ua.indexOf('honor') > -1) {
                info.brand = 'HUAWEI'
            }
            if (ua.indexOf('mx') > -1) {
                info.brand = 'MEIZU'
            }
            if (ua.indexOf('vivo') > -1) {
                info.brand = 'VIVO'
            }
            if (ua.indexOf('oppo') > -1) {
                info.brand = 'OPPO'
            }
            if (ua.indexOf('letv') > -1) {
                info.brand = 'LETV'
            }
            if (ua.indexOf('SM-') > -1) {
                info.brand = 'SAMSUNG'
            }
            try {
                if ((ua.match(/mi/i).length == 1 && ua.match(/MicroMessenger/i) != "micromessenger") || (ua.match(/mi/i).length > 1 && ua.match(/MicroMessenger/i) == "micromessenger") || ua.indexOf('hm') > -1 || ua.indexOf('redmi') > -1) {
                    info.brand = 'MI'
                }
            } catch (e) {

            }
        } else { //苹果
            def.envHandle.ios && def.envHandle.ios();
            info.system = 'IOS';
            info.brand = 'APPLE'
        }
    } else { //PC端
        def.envHandle.pc && def.envHandle.pc();
        info.device = 'PC';
        if (ua.match(/mac/i)) {
            info.system = 'Mac';
        } else {
            info.system = 'Windows';
        }
    }
    if (ua.match(/MicroMessenger/i) == "micromessenger") { //微信
        if (ua.match(/MicroMessenger/i) == "wxwork") {
            // 企业微信
            info.app = 'WX';
        } else {
            // 微信
            info.app = 'WX';
        }
    } else { //非微信
        def.envHandle.notWX && def.envHandle.notWX();

        if (ua.match(/safari/i)) {
            info.app = 'Safria';
        }
        if (ua.match(/chrome/i)) {
            info.app = 'Chrome';
        }
        if (ua.match(/maxthon/i)) {
            info.app = 'Maxthon';
        }
    }

    if (ua.match(/pars/i)) { //平安金管家
        info.app = 'JGJ';
    } else { //非平安金管家
        def.envHandle.notJGJ && def.envHandle.notJGJ();
    }
    window.system = info.system;

    //screen type

    if (window.innerWidth / window.innerHeight >= 0.66) { //华为
        // window.minScreen  = info.minScreen      = true;
        window.screenSize = info.screenSize = 1;
    }

    if (window.innerWidth / window.innerHeight >= 0.56 && window.innerWidth / window.innerHeight < 0.66) { //ihpne5 6 7 8 普通安卓分辨率
        // window.normalScreen = info.normalScreen = true;
        window.screenSize = info.screenSize = 2;
    }

    if (window.innerWidth / window.innerHeight < 0.56) { //X screen 640*1386 wechat(640*1277) || 750*1624  wechat(750*1496)
        window.X = info.xScreen = true;
        window.screenSize = info.screenSize = 3;
    } else {
        window.X = info.xScreen = false;
    }

    deviceInfo = info;
    window.deviceInfo = deviceInfo;
}

let getJGJOpenIdAndToken = function (config = {}) {
    return new Promise((resolve, reject) => {
        if (deviceInfo.app !== "JGJ") {
            console.warn("<- 当前未在金管家环境,获取openid失败 ->");
            return;
        }
        const starttime = new Date().getTime();
        console.log('准备请求金管家openToken,当前时间戳=>', starttime)
        PALifeOpen.getOpenId({
            appId: config.appId ? config.appId : process.env.VUE_APP_APPID
        },
            (result) => {
                //调用成功返回
                console.debug("success ", result);
                if (result.ret == 0) {
                    //返回结果成功
                    let openId = result.data.openId;
                    let openToken = result.data.openToken;

                    //是否为单独刷新opentoken的请求
                    if (!config.refreshOpenToken) {
                        console.log("user openToken\n\n", openToken);
                        console.log("user openId\n\n", openId);
                        const lasttime = new Date().getTime();
                        console.log('请求金管家openToken成功,用时=> ', (lasttime - starttime) / 1000, 's')
                    }

                    resolve({
                        openId: openId,
                        openToken: openToken,
                    });
                }
            },
            (e) => {
                // 调用异常返回
                console.log(e, "请求获取openId&openToken未成功");
            }
        );
    });
};
/**
 * [金管家|百度统一添加埋点]
 * @param  {[string]} des1    [描述1] 不可空  
 * @param  {[string]} des2    [描述1] 可空   
 * @param  {[function]} callback [回调] 可空
 * callback ：{
 *     @param  {[function]} jgjSuccess [金管家成功回调]  可空
 *     @param  {[function]} jgjFail    [金管家失败回调]  可空
 *     @param  {[function]} bdSuccess  [百度统计成功回调] 可空
 *     @param  {[function]} bdFail     [百度统计失败回调] 可空
 * }   
 */
let addTrackEvent = function (options = '', labelDes = '', action = '', wx = false, uid = '', prod = true, callback = {
    jgjSuccess: function () { },
    jgjFail: function () { },
    bdSuccess: function () { },
    bdFail: function () { }
}) {

    let _default = {
        eventTitle: '', //事件标题
        eventDes: '', //事件描述
        labelTitle: '', //标签标题
        labelDes: '', //标签描述

        labelId: '', //局部事件-lableid
        eventId: '', //标签描述-eventid

        wx: false, //微信外部埋点
        action: '', //新埋点方法 action =>  read || share
        uid: '', //外部方法uid
        prod: true, //外部埋点 是否正式环境
        callback: {
            jgjSuccess: function () { }, //金管家埋点成功回调
            jgjFail: function () { }, //金管家埋点失败回调
            bdSuccess: function () { }, //百度埋点成功回调
            bdFail: function () { } //百度埋点失败回调
        }
    }
    let opts = {};
    if (arguments.length === 1 && typeof (options) === 'object') {
        opts = _extend(_default, options, true);
        if (opts.eventTitle != '' && opts.labelTitle == '') opts.labelTitle = opts.eventTitle
        if (opts.eventDes != '' && opts.labelDes == '') opts.labelDes = opts.eventDes

        if (opts.labelTitle != '' && opts.eventTitle == '') opts.eventTitle = opts.labelTitle
        if (opts.labelDes != '' && opts.eventDes == '') opts.eventDes = opts.labelDes
    } else {
        opts.labelTitle = options;
        opts.labelDes = labelDes;
        opts.callback = callback;
        opts.action = action;
        opts.uid = uid;
        opts.wx = wx;
        opts.prod = prod;
        if (opts.labelTitle != '' && !opts.labelDes) opts.labelDes = opts.labelTitle
    }

    if (!opts.labelId || !opts.eventId) {
        opts.labelId = def.jgjLabelId;
        opts.eventId = def.jgjEventId;
    }

    _print('准备埋点=>>>>', opts.labelTitle, opts.labelDes)

    //加入金管家埋点
    try {
        const param = {
            event: opts.eventId + (opts.eventTitle || opts.eventDes ? (opts.eventTitle + '-' + opts.eventDes) : ''), // 
            label: opts.labelId + opts.labelTitle + '-' + opts.labelDes
        }
        PALifeOpen.trackEvent(
            param,
            (data) => {
                _print(`金管家埋点old \n ${param.event} \n ${param.label} \n success`, data);
                opts.callback.jgjSuccess && opts.callback.jgjSuccess(data);
            },
            (data) => {
                _print(`金管家埋点old \n ${param.event} \n ${param.label} \n failed`, data);
                opts.callback.jgjFail && opts.callback.jgjFail(data);
            }
        )
    } catch (e) {
        _print('金管家内old埋点失败')
        callback.jgjFail && callback.jgjFail();
    }

    //加入金管家埋点(内新)
    try {

        if (Number(def.PALifeOpenVer) >= 1.5) {
            const param = {
                eventId: opts.eventId,
                labelId: opts.labelId,
                e_t: opts.eventTitle ? opts.eventTitle : opts.labelTitle,
                e_d: opts.eventDes ? opts.eventDes : opts.labelDes,
                l_t: opts.labelTitle,
                l_d: opts.labelDes
            }
            PALifeOpen.invoke('device', 'addRecord', {
                eventId: param.eventId,
                labelId: param.labelId,
                "parameters": { // 扩展参数
                    ext: JSON.stringify({
                        act_action: opts.action,
                        e_t: param.e_t,
                        e_d: param.e_d,
                        l_t: param.l_t,
                        l_d: param.l_d
                    }),
                }
            },
                (data) => {
                    // 调用接口成功后的回调函数
                    _print(`金管家埋点new \n ${JSON.stringify(param)}  \n success`, data);
                    opts.callback.jgjSuccess && opts.callback.jgjSuccess(data);
                },
                (data) => {
                    // 调用接口异常的回调函数
                    _print(`金管家埋点new \n ${JSON.stringify(param)}\n failed`, data);
                    opts.callback.jgjSuccess && opts.callback.jgjSuccess(data);
                }, {});
        }
    } catch (e) {
        _print('金管家内new埋点失败')
        callback.jgjFail && callback.jgjFail();
    }

    //加入金管家埋点(外新)
    let wxaddTrackEvent = () => {
        let param = {
            eventId: opts.eventId,
            labelId: opts.labelId,
            e_t: opts.eventTitle ? opts.eventTitle : opts.labelTitle,
            e_d: opts.eventDes ? opts.eventDes : opts.labelDes,
            l_t: opts.labelTitle,
            l_d: opts.labelDes
        }
        PALifeWebSDK.addRecord(
            param.eventId,
            param.labelId, {
            isProd: opts.prod, //
            uid: opts.uid, //
            ext: {
                act_action: opts.action, //openId read share
                e_t: param.e_t,
                e_d: param.e_d,
                l_t: param.l_t,
                l_d: param.l_d
            }
        })
    }

    if (opts.wx) {
        try {
            let param = {
                eventId: opts.eventId,
                labelId: opts.labelId,
                e_t: opts.eventTitle ? opts.eventTitle : opts.labelTitle,
                e_d: opts.eventDes ? opts.eventDes : opts.labelDes,
                l_t: opts.labelTitle,
                l_d: opts.labelDes
            }
            if (!PALifeOpen) return

            wxaddTrackEvent();
            _print(`======> 金管家微信外部埋点成功 <=======\n ${JSON.stringify(param)}`);
        } catch (e) {
            _print('金管家微信外部埋点JSSDK开始加载')
            loadJs(def.PALifeWebSDKUrl[opts.prod ? 'product' : 'test'], () => {
                let param = {
                    event: opts.eventId,
                    label: opts.labelId,
                    e_t: opts.eventTitle ? opts.eventTitle : opts.labelTitle,
                    e_d: opts.eventDes ? opts.eventDes : opts.labelDes,
                    l_t: opts.labelTitle,
                    l_d: opts.labelDes
                }
                wxaddTrackEvent();
                _print(`======> 金管家微信外部埋点成功 <=======\n ${JSON.stringify(param)}`);
            })
        }
    }

    //加入百度统计
    try {
        _hmt && _hmt.push(['_trackEvent', opts.labelTitle, opts.labelDes]);
        opts.callback.bdSuccess && opts.callback.bdSuccess();
    } catch (e) {
        _print('百度统计埋点失败|未引入百度统计代码')
        opts.callback.bdFail && opts.callback.bdFail();
    }
}

let rebuildAjax = {
    /**
     * get方法，对应get请求
     * @param {String} url [请求的url地址]
     * @param {Object} params [请求时携带的参数]
     */
    get(url, params) {

        return new Promise((resolve, reject) => {
            const starttime = new Date().getTime();
            axios.get(url.indexOf('http') > -1 ? url : (def.ajaxUrl + url), {
                params: params
            }).then(res => {
                const lasttime = new Date().getTime();
                console.log(`${url}\n接口get请求成功, 用时${(lasttime - starttime) / 1000} s`, res)
                resolve(res.data)
            }).catch(err => {
                reject(err)
            })
        })
    },
    /**
     * post方法，对应post请求
     * @param {String} url [请求的url地址]
     * @param {Object} params [请求时携带的参数]
     */
    post(url, params) {
        return new Promise((resolve, reject) => {
            const starttime = new Date().getTime();
            axios
                .post(
                    url.indexOf("http") > -1 ? url : def.ajaxUrl + url,
                    // post方式需特殊出处理
                    qs.stringify(params)
                )
                .then((res) => {
                    const lasttime = new Date().getTime();
                    console.log(`${url}\n接口post请求成功, 用时${(lasttime - starttime) / 1000} s`, res);
                    resolve(res.data);
                })
                .catch((err) => {
                    reject(err);
                });
        })
    },
    /**
     * postFormData方法，对应post请求，用来提交文件+数据
     * @param {String} url [请求的url地址]
     * @param {Object} params [请求时携带的参数]
     */
    postFormData(url, params) {
        return new Promise((resolve, reject) => {
            axios({
                headers: {
                    'Content-Type': 'multipart/form-data' // ;boundary=----WebKitFormBoundaryQ6d2Qh69dv9wad2u
                },
                // transformRequest: [function (data) { // 在请求之前对data传参进行格式转换
                //     const formData = new FormData()
                //     Object.keys(data).forEach(key => {
                //         formData.append(key, data[key])
                //     })
                //     return formData
                // }],
                url: url.indexOf('http') > -1 ? url : (def.ajaxUrl + url),
                method: 'post',
                data: params
            }).then(res => {
                console.log(`${url}接口form请求成功`, res)
                resolve(res.data)
            }).catch(err => {
                reject(err)
            })
        })
    }
}
/**
 * [orientation()方法,旋转屏幕提示]
 * return  null
 */
let orientation = function () {
    //生成dom和样式注入body
    var elements = '<div class="orientationMask hide" id="orientationMask"><div class="mask-box"><div class="mask-pic"><i></i></div><div class="msg">请将手机竖置继续浏览</div></div></div>';
    var styles = '.orientationMask {background: rgba(84,84,84,1); width: 100%; height: 100%; top: 0; left: 0; position: fixed; z-index: 9999; } .orientationMask.show{visibility:visible; // display: block; } .orientationMask.hide{visibility: hidden; // display: none; } .orientationMask .mask-box {width: 100%;  height: 252px; position: absolute; top: 50%; left: 0; margin-top: -119px; } .orientationMask .mask-pic {width: 194px; height: 194px; margin: 0 auto; text-align: center; } .orientationMask .msg {width: 100%; height: 25px; display: block; margin: 0rem auto; text-align:center; line-height: 0.2rem; font-size: 12px; color: #fff; } .orientationMask i {display: block; width: 128px; height: 194px; background:  url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAADCBAMAAABzgNefAAAABGdBTUEAALGPC/xhBQAAAAFzUkdCAK7OHOkAAAAVUExURQAAAAC37gC37gC37gC37gC37gC37kWCOQ4AAAAHdFJOUwD+ZLaSENr8BBf/AAAClElEQVRo3u2az27iMBDGrSx+AIdszgmEPZMWeg7U3C1ouGcpff9HWOcfJaaxzUwlutKMkAAJ/xiPx58j+WPsM+aK4WKzxgKmyBRSscYCYnAKfCalzIU4A8fvX0QbwBT2VTdewMrIde4fKyk1Zg0snngqm/cIlECgx3egAphA2DVSxGAJxEn7KYclcLwsfgZbw41IbCvkXkMR4TbABNy+lxIkyC0YK6yKIGUoR9aQVeFPA/DSGsoB4NmzPVYLZQPU0uKKvzbAH+ERuyFAhNdt7ROGbl5noLXtfWaPTE9yKBvZ4rMClYcoagUPxzemz8Y6jh8eBy9p0BqsRtlGcoGsYzv8vZ5oMirPZ5PYRGJqYOF7vE/a5lNgAKvPK6YYHDAi4z8c4GhF5QJkq1ebHMjnxAHYuPbi2Ql4l5ao3AD7U9Jb8x9WgOOkzJ0ZLB0noRNQYAFLAvwngIQABCAAAQhAAAIQgAAEIAABCEAAAhCAAAQgAAEIQAACfB+geHgGv63jee4ExB43XVaAmFqu2rL2rs0O8LjtswHeHP6D5r7RBmCltQa8ZC7AdezbG/+be2dfwORrw4E/II2bWb+IJQzAxa6xhLA0hAGCvqd+RVBAX4upN+A8nEL3w6PvFEwDQx61y1gNueMGBtNCcegNe4MBwbhT48bEMT/Vy3jaGXmObliAjWS/Nap4r5Eljb/sXX8rTSqG+d1t5jEyuN9OZAJY6TQ0DW0tN4BaUDgbf5Vm88YMF48HPNxXx7G2uABvbiyQNRQKOQNYDfn2MgNYCXqVDiqgv7O35KYCtoiTbtxcwBLgmwZQ6vGwBLTYx1K+fmDs1d1xsQC2fzf+tAC3b/MgN4Nb3CuB3IIHLICj3bkHLIA/XX35BwxCdt2mDVe/AAAAAElFTkSuQmCC) 0 0 no-repeat; background-size: 100% 100%; margin: 0 auto; -webkit-transform:scale(.5); -webkit-animation: maskAni 1.5s ease infinite alternate; animation: maskAni 1.5s ease infinite alternate; } /*横屏动画*/ @-webkit-keyframes maskAni {0% { -webkit-transform:rotate(-90deg) scale(.5); } 30% { -webkit-transform:rotate(-90deg) scale(.5); } 70% { -webkit-transform:rotate(0deg) scale(.5); } 100% { -webkit-transform:rotate(0deg) scale(.5);} } @keyframes maskAni {0% { transform:rotate(-90deg) scale(.5); } 30% { transform:rotate(-90deg) scale(.5); } 70% { transform:rotate(0deg) scale(.5); } 100% { transform:rotate(0deg) scale(.5);} }';
    _addStyle(styles);
    _append(document.body, elements);

    let mask = document.getElementById('orientationMask');
    if (window.matchMedia) {
        var mql = window.matchMedia('(orientation: portrait)');
        var handleOrientationChange = (mql) => {
            if (mql.matches)
                mask.setAttribute('class', 'hide orientationMask');
            else
                mask.setAttribute('class', 'show orientationMask');

        }
        mql.addListener(handleOrientationChange);
    } else {
        window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", checkDirect, false);

        var checkDirect = () => {
            if (window.orientation == 180 || window.orientation == 0) { //竖置
                mask.setAttribute('class', 'hide orientationMask');
            }
            if (window.orientation == 90 || window.orientation == -90) { //横置
                mask.setAttribute('class', 'show orientationMask');
            }
        }
    }
}
/**
 * [showTips()方法]
 * @param  {[function]} args [回调] 不可空
 * args = {
 *    message          : '请稍等',       //显示信息
 *    showDelay        : 0,             //显示延迟
 *    closeDelay       : 1500,          //自动延迟关闭时间 | autoClose = true 有效
 *    autoClose        : true,          //是否延迟自动关闭
 *    showOverlay      : false,         //是否显示半透明遮罩
 *    completeCallBack : function(){}   //自动关闭回调 |  autoClose = true 有效
 * }   
 * return  object
 */
let showTips = function (args) {
    let _def = {
        message: '请稍等', //显示信息
        showDelay: 0,
        closeDelay: 1500,
        autoClose: true,
        showOverlay: false,
        completeCallBack: function () { }
    }
    let opts = _extend(_def, args, true);


    let showIt = () => {
        //针对当前viewport缩放 弹窗自适应
        let currentScale = 1;
        if (viewportScale && viewportScale != 1) {
            currentScale = 1 / viewportScale * .95;
        } else if (deviceInfo.system == 'Android' && viewportScale != 1) {
            currentScale = 1.65;
        }

        //生成dom和样式注入body
        let elements = `<div class="_xgl_tips_container page-container" id="_xglTipsContainer"><div class="tips-con"><div class="tips"><div class="word">${opts.message}</div></div></div>`;
        let styles = `._xgl_tips_container{z-index:999; visibility:hidden; display: -webkit-box; -webkit-box-pack:center; -webkit-box-align:center; width:100%; height:100%; top:0; left:0; position:fixed; ${opts.showOverlay ? 'background:rgba(0,0,0,.5)' : ''} } ._xgl_tips_container .tips-con{word-break: break-all;-webkit-transform:scale(${currentScale});transform:scale(${currentScale});width:100%; min-height:161px; position:relative; } ._xgl_tips_container .tips{display: -webkit-box; -webkit-box-pack:center; -webkit-box-align:center; min-width:200px; max-width:300px; min-height: 40px; line-height: 30px; margin: auto; background-color:rgba(0,0,0,.75); border-radius:10px; font-size:14px; text-align:center; padding:10px 10px; color:#fff; overflow:hidden; box-shadow: 0 0 3px rgba(0,0,0,.85); }`;
        _addStyle(styles);
        _append(document.body, elements);
        let showAni = TweenMax.fromTo('#_xglTipsContainer', .4, {
            autoAlpha: 0
        }, {
            autoAlpha: 1,
            delay: opts.showDelay,
            onReverseComplete: () => {
                _remove(document.getElementById('_xglTipsContainer'));
                opts.completeCallBack && opts.completeCallBack();
                showAni.kill();
            }
        })

        if (opts.autoClose) {
            sleep(opts.closeDelay).then(() => showAni.reverse())
        } else {
            let container = document.getElementById('_xglTipsContainer');
            container.addEventListener('mousedown', () => {
                showAni.reverse()
            }, false)
        }

    }

    showIt();
}
/**
 * [btnTouched() 按钮点击反馈动效]
 * @param  {[function]} target    [目标]       不可空
 * @param  {[function]} callbacks [动画结束回调] 可空
 * return  object
 */
let btnTouched = function (target, callbacks, timeScale) {
    if (!def.btnEnable) return false
    def.btnEnable = false;


    let createAni = () => {
        let originScale = 1; //$(target).data('scale');  //DOM中原始缩放
        if (!originScale && (target.osx || target.osy)) {
            originScale = target.osx;
        }
        let timeline = new TimelineMax({
            onStart: () => { },
            onComplete: () => {
                callbacks && callbacks();
                def.btnEnable = true;
                timeline.kill();
            }
        });
        timeline
            .to(target, .4, {
                scaleX: (originScale ? originScale : 1) * .9,
                scaleY: (originScale ? originScale : 1) * .9
            })
            .to(target, .2, {
                scaleX: originScale ? originScale : 1,
                scaleY: originScale ? originScale : 1
            })

        timeline.timeScale(timeScale ? timeScale : 1)
    }

    createAni();
}
/**
 * [showDemo() 显示开发模式]
 * 
 * return  null
 */
let showDemo = function () {
    var _default = {
        visible: false, //是否默认显示
        logo: true, //是否显示logo
        position: 'bottomRight', //bottomRight - 右下角 | bottom - 居中底部
        language: 'CN', // CN - 开发版 | EN - Demo
        text: '', //自定义文字 三个字以内最佳 | language无效
        touchHide: true //是否点击后隐藏
    }

    let opts = _extend(_default, def.demoConfig, true);

    var text = opts.language === 'CN' ? '开发版' : 'Demo';
    var logoDiv = '<div class="_xgl-logo"></div>';
    var dom = '<div id="___xgl_demo" class="___xgl_dmeo___ ' + opts.position + '">' + (opts.logo ? logoDiv : '') + '<div class="_xgl-text">' + (opts.text != '' ? opts.text : text) + '</div></div>';
    var pointEvents = 'pointer-events:none;';

    _append(document.body, dom);

    const _string = function () {
        /*
         __    __   ______   __          _______   ________  _______   __    __   ______  
        |  \  |  \ /      \ |  \        |       \ |        \|       \ |  \  |  \ /      \ 
        | $$  | $$|  $$$$$$\| $$        | $$$$$$$\| $$$$$$$$| $$$$$$$\| $$  | $$|  $$$$$$\
         \$$\/  $$| $$ __\$$| $$ ______ | $$  | $$| $$__    | $$__/ $$| $$  | $$| $$ __\$$
          >$$  $$ | $$|    \| $$|      \| $$  | $$| $$  \   | $$    $$| $$  | $$| $$|    \
         /  $$$$\ | $$ \$$$$| $$ \$$$$$$| $$  | $$| $$$$$   | $$$$$$$\| $$  | $$| $$ \$$$$
        |  $$ \$$\| $$__| $$| $$_____   | $$__/ $$| $$_____ | $$__/ $$| $$__/ $$| $$__| $$
        | $$  | $$ \$$    $$| $$     \  | $$    $$| $$     \| $$    $$ \$$    $$ \$$    $$
         \$$   \$$  \$$$$$$  \$$$$$$$$   \$$$$$$$  \$$$$$$$$ \$$$$$$$   \$$$$$$   \$$$$$$ 
         */
    }

    if (def.debug) console.log(`%c` + _string.makeMulti(), 'color:#d7ac71')
    //添加样式以及适配viewport
    // console.log("%c   XGL - Debug Mode","height:70px;background: url(http://'+def.resourceDomain+'/scl/images/x-logo.gif) no-repeat left center;font-size: 70px;color:#d7ac71","\n");

    var logoImage = 'https://' + def.resourceDomain + '/resources/logo.png';

    var styles = '.___xgl_dmeo___{width:100%; height:40px; -webkit-transition:opacity .6s ease-out; transition:opacity .6s ease-out; box-shadow:0 0 30px #eee inset; position:fixed; left:40%; bottom:2%; z-index: 9999; ' + (opts.touchHide ? '' : pointEvents) + ' background: rgba(0,0,0,1);  -webkit-transform:rotate(-45deg); } .___xgl_dmeo___ ._xgl-logo{width: 100px; height:31px; position:absolute; top:2%; left:58%; opacity: 1; margin-left: -50px; background: url(' + logoImage + '); -webkit-transform:scale(.3); } .___xgl_dmeo___ ._xgl-text{line-height:40px; text-align:center; margin-left:-5%; font-size: 18px; color:#fff; font-weight:bold; color: #fff; text-shadow:1px 1px #9d9d9d,1.5px 1.5px #bbbbbb; }';

    var styles2 = '.___xgl_dmeo___{width:100%; height:40px; -webkit-transition:opacity .6s ease-out; transition:opacity .6s ease-out; position:fixed; left:0%; bottom:0%; z-index: 9999; background: rgba(0,0,0,.95); box-shadow: 0 0 20px #eee; ' + (opts.touchHide ? '' : pointEvents) + '  border-radius:15px 15px 0 0; } .___xgl_dmeo___ ._xgl-logo{width: 100px; height:31px; position:absolute; top:10%; left:60%; opacity: 1; margin-left: -50px; background: url(' + logoImage + '); -webkit-transform:scale(.5); } .___xgl_dmeo___ ._xgl-text{line-height:40px; text-align:center; font-size: 18px; color:#fff; font-weight:bold; color: #fff; margin-left: -10%; text-shadow:1px 1px rgba(197, 223, 248,0.8); }'

    var currentStyle = opts.position === 'bottomRight' && deviceInfo.device !== 'PC' ? styles : styles2;

    _addStyle(currentStyle);

    //绑定点击消失事件
    let targetEle = document.getElementById('___xgl_demo')
    targetEle.addEventListener('click', () => {
        targetEle.style.opacity = 0;
        targetEle.style.pointerEvents = 'none';
    }, false)


    var adaptViewPort = (argument) => {
        var scaleRatio = window.innerWidth / 375;
        var debugDemo = document.getElementById('___xgl_demo');
        var rotate = 'rotate(-45deg)';
        debugDemo.style.cssText = '-webkit-transform:scale(' + scaleRatio + ') ' + opts.position === 'bottomRight' ? rotate : '' + '';
    }
    adaptViewPort();

    //resize
    window.addEventListener('resize', function () {
        adaptViewPort();
    }, false)
}

// 格式化日期
let dateFormat = (date, fmt = 'YYYY-mm-dd HH:MM') => {
    /**
     * 调用方法
     * dateFormat("YYYY-mm-dd HH:MM", date)
     */
    let ret;
    const dateObj = new Date(date);
    const opt = {
        "Y+": dateObj.getFullYear().toString(),        // 年
        "m+": (dateObj.getMonth() + 1).toString(),     // 月
        "d+": dateObj.getDate().toString(),            // 日
        "H+": dateObj.getHours().toString(),           // 时
        "M+": dateObj.getMinutes().toString(),         // 分
        "S+": dateObj.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

// 判断页面是否滚动到底部
// 判断是不是滚动到底部了
let judeScrollBottom = (selecter = 'task-content') => {
    let flag = false;
    let page = document.getElementsByClassName(selecter)[0]
    let scrollTop = page.getBoundingClientRect().top * -1;
    var clientHeight = document.documentElement.scrollTop === 0 ? document.body.clientHeight : document.documentElement.clientHeight;
    // var scrollTop = document.documentElement.scrollTop === 0 ? document.body.scrollTop : document.documentElement.scrollTop;
    var scrollHeight = page.scrollHeight;
    // if (scrollTop != 0 && clientHeight + scrollTop == scrollHeight) {
    console.log(scrollHeight, scrollTop, scrollHeight - scrollTop - clientHeight < 30)
    if (scrollTop != 0 && (scrollHeight - scrollTop - clientHeight < 50)) {
        // console.log('‘到达底部’')
        flag = true;
    } else {
        flag = false;
    }
    return flag;
}


//实例化后将内部方法挂载到window对象下
// window.XGL = new XGLCommonPlugins();

export {
    btnTouched,
    showTips,
    orientation,
    rebuildAjax,
    detectEnv,
    addTrackEvent,
    checkFormalEnv,
    getQueryString,
    getSetCookie,
    updateUrl,
    jgjReady,
    getJGJOpenIdAndToken,
    getRandomElements,
    rangeRandom,
    randomSortArray,
    hexToDec,
    decToHex,
    cutString,
    sleep,
    loadMusic,
    jgjShare,
    wxSdkInitialize,
    wxShare,
    handleTargetEnv,
    loadJs,
    initial,
    dateFormat,
    judeScrollBottom
};