/**
 * 封装H5开发基本能力
 * milo：ams或星图用下面这个
 * <script src="//ossweb-img.qq.com/images/js/mobile_bundle/milo.js"></script>
 * milo：管线用下面这个
 * <script type="text/javascript" src="//ossweb-img.qq.com/images/js/miloweb/umd/v1.2.8/milo-web.js" charset="gbk"></script>
 * 星图要加这个
 * <script type="text/javascript" src="//game.gtimg.cn/images/js/ide/latest/ide.gbk.js"></script>
 * 通用js
 * <script type="text/javascript" src="https://ossweb-img.qq.com/images/js/mobile_bundle/util/zepto.js"></script>
 * <script src="//gameact.qq.com/comm-htdocs/js/game_area/yxzj_server_select.js"></script>
 * <script type="text/javascript" src="//game.gtimg.cn/images/js/xom/xom-2022012416.js" charset="utf-8" tcss-enable eas-enable tam-enable tam-id="qktqJDKeDQKaydgjyC" tdm-enable></script>
 * <script type="text/javascript" src="//pub.idqqimg.com/qqmobile/qqapi.js?_bid=152"></script>
 * 文档地址：https://iwiki.woa.com/pages/viewpage.action?pageId=1404354436
 */

/*
// Localize polyfill
var ActGlobal = {
    receiveFlag: 0
};
var ActFun = {
    Initial: function () {},
    ActSetShareData: function () {}
};
throw Error("Sent to blackhole"); // Send to blackhole
*/
window.ams_login_avoid_conflict = true; // 防止串号的开关
var ActConfig = {
    // 每次都需要改动的数据
    actUrl: "https://pvp.qq.com/cp/a20221008wgpfblfx/index.html", // 活动地址
    actName: 'a20221008wgpfblfx', // 蜘蛛上的活动名称
    iAMSActivityId: '', // 活动ID，ams直接填写活动号，星图填写活动号的加密ID
    openGameUrl: 'https://pvp.qq.com/d/a20210827mch/play.html?browser=start&noDownloadAlert=true', // 打开游戏的链接，一般不复用，需要联系产品提供
    wxOpenLink:'',
    // share: { // 分享数据
    //     title: '开荣耀盲盒，集王者英雄卡，兑超值好礼',
    //     desc: '峡谷荣耀盲盒来袭！和小元芳一起开启盲盒收集英雄卡吧！超多好礼等你兑换',
    //     imageUrl: 'https://game.gtimg.cn/images/yxzj/cp/a20211117blindbox/share.jpg',
    //     tail: '峡谷荣耀盲盒来袭！和小元芳一起开启盲盒收集英雄卡吧！超多好礼等你兑换', // 只在手Q生效，小尾巴
    // },
    nicknameSpan: '', // 展示微信名称或者QQ名称的span的id
    bindWindow: 0, // 绑定大区的时候是否弹出角色选择弹窗，0表示不弹出默认弹窗，1表示弹出默认弹窗
    checkBindId: 0, // 王者通用绑定模块查询绑定流程号
    roleBindId: 0, // 王者通用绑定模块确认绑定&更改绑定流程号，默认不允许更改绑定，需要在管理端更改
    bgType: 0, // 后台类型，0表示ams，1表示星图，2表示管线

    // 基本不需要改动的数据
    timeInterval: 2000, // 设置各个按钮点击频率的时间间隔，单位：毫秒
    commonAppid: 'wx1cd4fbe9335888fe', // 微信游戏号，由于王者appid限制，登录态只能用这个，用王者的会把游戏踢下线
    wxServiceType: 'txyxhdh', // 微信服务类型，腾讯游戏活动号的缩写
    specOpenIdFirst5: 'oQDeW', // 游戏公众号的前5位，用于判断是否是微信环境
    qqAppid: '1104466820', // 手Q王者appid
    wxAppid: 'wx95a3a4d7c627e07d', // 微信王者appid
    name: '王者荣耀', // 游戏名称
    appName: 'yxzj', // 游戏英文缩写
    msdkJsPath: '//img.ssl.msdk.qq.com/wiki/msdkJsAdapter.js', // 游戏内msdk的js文件
    qqApiJsPath: "//pub.idqqimg.com/qqmobile/qqapi.js?_bid=152", // mqq组件js文件
    appConfig: { // 登录使用的配置文件
        "avoidConflict": true, // 防止串号
        "WxAppId": 'wx1cd4fbe9335888fe', //微信游戏号
        "scope": "snsapi_userinfo"  //默认是 snsapi_base 静默授权，建议写成snsapi_userinfo,否则没办法获取昵称、头像等
    },
    loginErrorFunc: function () { // 登录遇到问题时执行的函数，仅针对移动端
        console.log("force to reload cookie");
        window.location.reload();
    },
}
var ActGlobal = { // 活动全局变量，一般用于记录活动过程中产生的数据或状态
    loginEnv: null, // 0：内嵌H5；1：游戏内msdk；2：王者营地；3：第三方浏览器；4：手Q；5：微信；6：X5内核浏览器
    lastClickTime: null, // 防止点击频率过高的初始化参数
    pageChar: 'utf-8', // 页面的编码，默认是UTF-8
    isLogin: false,
    isBindRole: false,
    checkRoleFinish: false,
    loadPageFinish: false,
    throttleLottery: false,
    //请求中的sData参数
    sData: {},
    roleInfo: {},
    //用户相关信息
    commonUser: {
        nickName: '',
        headimg: '',
        iUin: '',
        loginType: '',
        userOpenid:''
    },
    initData:{

    },
    //已绑定角色信息
    bindRoleInfo: {
        sArea: '',
        sPartition: '',
        sPlatId: '',
        sRoleId: '',
        sRoleName: '',
        sAreaName: '',
        sAmsNewRoleId: '',
        sRoletoken: '',
        sOpenid: '',
        sAppid: '',
    },
    //最近登录角色信息
    recentRoleInfo: {
        sArea: '',//qq(1,2), wx(3,4)
        sPartition: '',
        sPlatId: '',//ios(0), android(1)
        sRoleId: '',
        sRoleName: '',
        sAreaName: '',
        sHeadUrl: ''
    },
    // 一些可用的对象
    roleSelect: null, // biz.roleselector
    loginManager: null, // 管线的登录器
}
var ActFun = {
    /**
     * 初始化配置文件，必须首先执行
     * @param activityId ams或星图的活动号
     * @param nicknameSpan
     * @param bindWindow
     * @param checkBindId
     * @param roleBindId
     * @param bgType
     * @param timeInterval
     * @constructor
     */
    Initial: function (activityId, nicknameSpan, bindWindow, checkBindId, roleBindId, bgType, timeInterval = 1000) {
        var tempConfig = {
            iAMSActivityId: activityId, // 活动ID，ams直接填写活动号，星图填写活动号的加密ID
            nicknameSpan: nicknameSpan, // 展示微信名称或者QQ名称的span的id
            bindWindow: bindWindow, // 绑定大区的时候是否弹出角色选择弹窗，0表示不弹出默认弹窗，1表示弹出默认弹窗
            checkBindId: checkBindId, // 王者通用绑定模块查询绑定流程号
            roleBindId: roleBindId, // 王者通用绑定模块确认绑定&更改绑定流程号，默认不允许更改绑定，需要在管理端更改
            bgType: bgType, // 后台类型，0表示ams，1表示星图
            timeInterval: timeInterval, // 设置各个按钮点击频率的时间间隔，单位：毫秒
        }
        ActConfig = $.extend(ActConfig, tempConfig);
        $('body').append('<div class="hidden" style="display: none"></div>'); // 内嵌H5跳转用
        // if(bgType === 2){
        //     loadScript("//ossweb-img.qq.com/images/js/miloweb/umd/v1.1.6/milo-web.js", function () {
        //         console.log("milo-web load success~");
        //     });
        // }
    },
    /**
     * 查询是否登陆，
     */
    ActCheckLogin: function (loginCallback, unLoginCallback) {
        if (ActConfig.bgType === 2) { // 管线
            var pm = ActFun.loadLoginManager(null);
            pm.then(LoginManager => {
                // alert(2);
                ActGlobal.loginManager = LoginManager;
                return LoginManager.checkLogin();
            }).then(res => {
                // alert(3);
                globalRes = res;
                const { isLogin, userInfo } = res;
                ActFun.loginSuccess(userInfo, loginCallback);
            }).catch(err => {
                ActFun.loginFail(unLoginCallback);
            });
        } else { // ams和星图
            return; // Send to blackhole
            need("biz.login", function (LoginManager) {
                ActFun.loadLoginManager(LoginManager);
                ActGlobal.loginManager = LoginManager;
                LoginManager.checkLogin(function (userinfo) {
                    ActFun.loginSuccess(userinfo, loginCallback);
                }, function () {
                    ActFun.loginFail(unLoginCallback);
                }, ActConfig.appConfig);
            });
        }
    },
    /**
     * 加载loginManager
     */
    loadLoginManager: function (LoginManager) {
        return; // Send to blackhole
        if (ActConfig.bgType === 2) {
            return milo.Login.init({
                plat: milo.platform.isMobile() ? 'mobile' : 'pc',
                jumpWin: 'self',
                wxAvartarSize: 46,
                commonParams: {
                    iUseQQConnect: 0, // 设为1表示当前页面使用QQ互联登录态
                    // isPrivateLogin: false, // 是否私有登陆态，如果为true，则不共享game.qq.com中的代理登录态，为false，则从game.qq.com中读取和写入登录态，默认为false
                    // useAppLogin:[]//是否使用多渠道原生登录能力，详见：http://ams.oa.com/document/wiki/#/about?iId=250&siId=1-409
                },
                mobileParams: {
                    /**
                     * @cfg {object} oQQParams Pt QQ登录相关配置参数
                     */
                    oQQParams: {
                        appId: '21000501', //官网默认的pt登录appid
                        sUrl: '', //登录之后的跳转地址
                    },
                    /**
                     * @cfg {object} oWXParams 微信登录相关配置参数
                     */
                    oWXParams: {
                        appId: 'wx1cd4fbe9335888fe', //游戏在微信的appid，默认为腾讯游戏活动号
                        gameDomain: 'iu.qq.com', // 微信开放平台管理端里登记的回调域
                        redirectUri: '', //授权页面，默认为系统默认的comm-htdocs/login/milosdk/wx_mobile_redirect.html
                        sUrl: '', //授权成功返回的页面，默认为当前页面
                        scope: 'snsapi_base', //默认静默授权
                        lang: 'zh_CN', //返回的用户信息中省市的语言版本
                        openlink: '', //openlink，如果设置了，则在处理微信登录的时候，会从第三方跳到微信中
                    },
                    /**
                     * @cfg {object} oQQConnectParams QQ互联登录方式相关参数
                     */
                    oQQConnectParams: {
                        appId: '101491592',
                        scope: 'get_user_info',
                        state: 'STATE',
                        redirectUri: 'https://milo.qq.com/comm-htdocs/login/qc_redirect.html',
                        sUrl: '', //登录之后的跳转地址
                    },
                    /**
                     * @cfg {object} oWegameParams wegame互联登录方式相关参数
                     */
                    oWegameParams: {
                        clientId: '7019928239', //应用id
                        redirectUri: 'https://milo.qq.com/comm-htdocs/login/wegame_redirect.html', //回调地址
                        railGameId: '2000108', //游戏id
                        scope: 'openid profile', //作用域，可多选，空格分隔
                        state: 'STATE', //防csrf
                        lang: 'ZH_CN', //语言，默认为中文(ZH_CN)
                        extraParams: {},
                    }
                },
                pcParams: {
                    //公共的和显示相关的配置，每种登录还可以重新设置showParams到自己的配置项中，覆盖公共的showParams
                    //公共的和显示相关的配置，每种登录还可以重新设置showParams到自己的配置项中，覆盖公共的showParams
                    showParams: {
                        topTips: '微信和QQ是两个独立账号，账号信息不互通',//qcwx和qqwx联合登录的时候上面的提示语
                        zIndex: 999,//登录弹框的zIndex值
                        needMask: true,//登录弹框是否需要遮罩
                        canClose: true,//登录框可以被手动关掉
                        needReloadPage: true//默认授权成功后刷新页面
                    },

                    /**
                     * @cfg {object} oQQParams Pt QQ登录相关配置参数
                     */
                    'oQQParams': {
                        appId: '21000501',//官网默认的pt登录appid
                        callback: null,//登录成功后的回调
                        sUrl: '',//登录之后的跳转地址
                        style: '20',
                        innerParentId: '',
                        showParams: {}//会覆盖公共的showParams
                    },
                    /**
                     * @cfg {object} oWXParams 微信登录相关配置参数
                     */
                    'oWXParams': {
                        appId: 'wxfa0c35392d06b82f',//游戏在微信的appid，默认为腾讯游戏活动号
                        gameDomain: 'iu.qq.com',
                        lang: 'zh_CN',//返回的用户信息中省市的语言版本
                        callback: null,//登录成功后的回调
                        showParams: {}//会覆盖公共的showParams
                    },
                    /**
                     * @cfg {object} oQQConnectParams QQ互联登录方式相关参数
                     */
                    'oQQConnectParams': {
                        appId: "101491592",
                        scope: "get_user_info",
                        state: "STATE",
                        redirectUri: "https://milo.qq.com/comm-htdocs/login/qc_redirect.html",
                        sUrl: '',//登录之后的跳转地址
                        callback: null,//登录成功后的回调
                        showParams: {}//会覆盖公共的showParams
                    },
                    /**
                     * @cfg {object} oWegameParams wegame互联登录方式相关参数
                     */
                    'oWegameParams': {
                        clientId: '7019928239',//应用id
                        redirectUri: 'https://milo.qq.com/comm-htdocs/login/wegame_redirect.html',//回调地址
                        railGameId: '2000108',//游戏id
                        scope: 'openid profile',//作用域，可多选，空格分隔
                        state: 'STATE',//防csrf
                        lang: 'ZH_CN',//语言，默认为中文(ZH_CN)
                        callback: null,//登录成功后的回调
                        showParams: {}//会覆盖公共的showParams
                    }
                },
                logoutCallback: {
                    // freshWin: true, // 需要刷新页面（reload），不需要可以删除本行
                    callback: function () { // 初始化注销成功的回调逻辑
                        console.log('logout!')
                    },
                },
            });
        } else {
            LoginManager.init(
                {
                    appConfig: ActConfig.appConfig,
                    // loginBtn : 'ptLoginBtn', // 页面对应bottom的id
                    // wxloginBtn: 'wxloginBtn',
                    // logoutBtn : 'ptLogoutBtn',
                    loginBtn: '', // 由于是自动登录，所以按钮的功能不要加，除非要在浏览器登录
                    wxloginBtn: '',
                    logoutBtn: '',
                    loginedDiv: 'logined', // 页面对应已登录的div
                    unloginDiv: 'unlogin', // 页面对应未登录的div
                    userinfoSpan: 'userinfo', // 页面对应用于展示用户信息的span
                    iUseQQConnect: (typeof window.iUseQQConnect != 'undefined') ? window.iUseQQConnect : 0,
                    oQQConnectParams: {
                        appId: "101491592",
                        scope: "get_user_info",
                        state: "STATE",
                        redirect_uri: "https://milo.qq.com/comm-htdocs/login/qc_redirect.html"
                    }
                }
            );
        }
    },
    /**
     * 成功登陆回调
     */
    loginSuccess: function (userinfo, callback) {
        ActGlobal.isLogin = true;
        // 游戏内（包括内嵌H5和游戏内浏览器）或者王者营地
        if (ActFun.isMsdk()) {
            ActGlobal.commonUser.loginType = userinfo.loginType;
            ActGlobal.commonUser.iUin = milo.xss.filter(milo.request('openid'));
            /**
             * 王者营地里面没有newRoleId，只能通过IDIP查，或者结合绑定大区模块实现
             */
            if (ActFun.isYingDi()) { // 王者营地登录
                ActGlobal.loginEnv = 2;
                ActGlobal.bindRoleInfo = {
                    sOpenid: milo.xss.filter(milo.request('gameOpenid')), // 这里是王者的openid，如果要王者营地的openid用openid
                    sPartition: milo.xss.filter(milo.request('serverId')),
                    sArea: milo.xss.filter(milo.request('areaId')),
                    sRoleId: milo.xss.filter(milo.request('roleId')),
                    sServiceType: 'yxzj',
                    sAppid: milo.xss.filter(milo.request('appid')), // 这里是王者的appid
                    sRoleName: decodeURIComponent(milo.xss.filter(milo.request('roleName'))),
                    sPlatId: milo.xss.filter(milo.request('platid')),
                    sAmsNewRoleId: (milo.xss.filter(milo.request('serverId'))+"_"+milo.xss.filter(milo.request('gameOpenid')))
                }
            } else {
                // 实测，内嵌H5和msdk的userAgent是一样的，但是内嵌H5的window.innerWidth x window.innerHeight好像是固定的499 x 291,宽高比为1.7，msdk一般是2以上
                // ActGlobal.loginEnv = (window.navigator.userAgent.toLowerCase().match(/msdk/i) == 'msdk')? 1 : 0;
                ActGlobal.loginEnv = (typeof msdkiOSHandler === 'undefined') ? 6 : ((window.innerWidth / window.innerHeight < 2) ? 0 : 1);
                ActGlobal.bindRoleInfo = {
                    sOpenid: milo.xss.filter(milo.request('openid')),
                    sPartition: milo.xss.filter(milo.request('partition')),
                    sArea: milo.xss.filter(milo.request('area')),
                    sRoleId: milo.xss.filter(milo.request('roleid')),
                    sAmsNewRoleId: milo.xss.filter(milo.request('newRoleID')),
                    sServiceType: 'yxzj',
                    sAppid: milo.xss.filter(milo.request('appid')),
                    sPlatId: (milo.xss.filter(milo.request('area')) == '2' || milo.xss.filter(milo.request('area')) == '4') ? 0 : 1,
                }
            }
            ActGlobal.isBindRole = true
        } else if (ActFun.isWeiXin() || milo.cookie.get("acctype") == 'wx') {
            ActGlobal.loginEnv = 5;
            //检查微信是否是微信的cookie
            var loginOpenIdTmp = milo.cookie.get("openid");
            //cookie不存在
            if (loginOpenIdTmp == null) {
                ActGlobal.loginManager.logout(
                    {
                        logoutCallback: ActConfig.loginErrorFunc
                    }
                );
            }
            //微信openid不符合王者的格式
            if (loginOpenIdTmp.substr(0, 5) != ActConfig.specOpenIdFirst5 || milo.cookie.get('acctype') != 'wx') {
                ActGlobal.loginManager.logout(
                    {
                        logoutCallback: ActConfig.loginErrorFunc
                    }
                );
            }
            //获取微信用户信息
            ActGlobal.loginManager.getUserInfoByWxOpenId({
                "openid": milo.cookie.get("openid"),
                "access_token": milo.cookie.get("access_token")
            }, function (wxuser) {
                ActGlobal.commonUser.openId = wxuser.openid;
                ActGlobal.commonUser.iUin = wxuser.openid;

                if (ActGlobal.commonUser.nickName == '') {
                    try {
                        ActGlobal.commonUser.nickName = wxuser.def_nickname;
                    } catch (error) {
                        ActGlobal.commonUser.nickName = '';
                    }
                }
                $("#" + ActConfig.nicknameSpan).html(milo.xss.filterWxNickName(ActGlobal.commonUser.nickName));
                ActGlobal.commonUser.loginType = 'wx';
                // loginCallback();
            }, function (err) {
                ActGlobal.loginManager.logout(
                    {
                        logoutCallback: ActConfig.loginErrorFunc
                    }
                );
            });
        } else if (ActFun.isQQ()) {
            ActGlobal.loginEnv = 4;
            //手Q登录
            ActGlobal.commonUser.iUin = userinfo.userUin;
            try {
                ActGlobal.commonUser.nickName = decodeURIComponent(userinfo.nickName);
            } catch (error) {
                ActGlobal.commonUser.nickName = '';
            }
            if (ActGlobal.commonUser.nickName == '') {
                ActGlobal.commonUser.nickName = userinfo.userUin;
            }
            $("#" + ActConfig.nicknameSpan).html(milo.xss.filterWxNickName(ActGlobal.commonUser.nickName));
            ActGlobal.commonUser.loginType = 'qq';
            // loginCallback();
        } else {
            // 第三方浏览器
            ActGlobal.loginEnv = 3;
            ActGlobal.commonUser.iUin = userinfo.userUin;
            try {
                ActGlobal.commonUser.nickName = decodeURIComponent(userinfo.nickName);
            } catch (error) {
                ActGlobal.commonUser.nickName = '';
            }
            if (ActGlobal.commonUser.nickName == '') {
                ActGlobal.commonUser.nickName = userinfo.userUin;
            }
            $("#" + ActConfig.nicknameSpan).html(milo.xss.filterWxNickName(ActGlobal.commonUser.nickName));
            ActGlobal.commonUser.loginType = 'qq';
        }
        // 获取网页的编码格式
        callback();
    },
    /**
     * 登录失败回调
     */
    loginFail: function (callback) {
        //未登录回调
        if (ActFun.isWeiXin()) {
            //微信自动登录
            (ActConfig.bgType === 2) ? ActGlobal.loginManager.loginByWX() : ActFun.loginByWx();
        } else if (ActFun.isQQ()) {
            //手Q自动登录
            (ActConfig.bgType === 2) ? ActGlobal.loginManager.loginByQQ() : ActFun.loginByQQ();
        } else {
            callback();
        }
    },
    /**
     * 查询是否已绑定角色
     */
    ActCheckRoleBind: function (confirmButtonId, cancelButtonId, channelContentId, areaContentId, roleContentId, PIPSubmitId, PIPCancelId,
                                submitSuccEvent, submitFailEvent, cancelEvent, unBindCallBack, bindedCallBack,
                                failCallBack, ShowPIPFunc = null, cancelPIPCallBack = null) {
        unBindCallBack = typeof unBindCallBack == 'function' ? unBindCallBack : function () { };
        bindedCallBack = typeof bindedCallBack == 'function' ? bindedCallBack : function () { };
        failCallBack = typeof failCallBack == 'function' ? failCallBack : function () { };
        // 初始化绑定大区模块
        if (typeof YXZJServerSelect === "undefined") {
            // 这里是异步的，不太靠谱
            loadScript("//gameact.qq.com/comm-htdocs/js/game_area/yxzj_server_select.js", function () {
                console.log("load YXZJServerSelect success!");
                if (ActGlobal.loginEnv == 5 || (ActGlobal.bindRoleInfo.sAppid && ActGlobal.bindRoleInfo.sAppid.substr(0, 2) == 'wx')) { //加上抢先服
                    YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "微信-安卓(android)", v: "3", sk: "android", k: "weixin" }, { t: "微信-苹果(iOS)", v: "4", sk: "ios", k: "weixin" }, { t: "微信-安卓抢先服(android)", v: "7", sk: "android", k: "weixin" }];//
                    //{t: "微信-苹果抢先服(iOS)", v: "7", sk: "ios", k: "weixin" }
                } else {
                    YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "手Q-安卓(android)", v: "1", sk: "android", k: "qq" }, { t: "手Q-苹果(iOS)", v: "2", sk: "ios", k: "qq" }, { t: "手Q-安卓抢先服(android)", v: "6", sk: "android", k: "qq" }];//
                    //{t: "手Q-苹果抢先服(iOS)", v: "7", sk: "ios", k: "qq" }
                }
            });
        } else {
            // if (ActGlobal.commonUser.loginType == 'wx') { //这种方法只有第一次微信授权才会成功，其他时候返回''
            if (ActGlobal.loginEnv == 5 || (ActGlobal.bindRoleInfo.sAppid && ActGlobal.bindRoleInfo.sAppid.substr(0, 2) == 'wx')) { //加上抢先服
                YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "微信-安卓(android)", v: "3", sk: "android", k: "weixin" }, { t: "微信-苹果(iOS)", v: "4", sk: "ios", k: "weixin" }, { t: "微信-安卓抢先服(android)", v: "7", sk: "android", k: "weixin" }];//
                //{t: "微信-苹果抢先服(iOS)", v: "7", sk: "ios", k: "weixin" }
            } else {
                YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "手Q-安卓(android)", v: "1", sk: "android", k: "qq" }, { t: "手Q-苹果(iOS)", v: "2", sk: "ios", k: "qq" }, { t: "手Q-安卓抢先服(android)", v: "6", sk: "android", k: "qq" }];//
                //{t: "手Q-苹果抢先服(iOS)", v: "7", sk: "ios", k: "qq" }
            }
        }
        window.tempSelector = YXZJServerSelect;
        // 普通的milo就是固定的
        if (ActConfig.bindWindow === 1) {
            confirmButtonId = 'confirmButtonId_yxzj';
            channelContentId = 'channelContentId_yxzj';
            areaContentId = 'areaContentId_yxzj';
            roleContentId = 'roleContentId_yxzj';
        }
        // 取消绑定按钮的事件
        $('#' + cancelButtonId).on('click', function () {
            if (typeof cancelEvent === 'function') {
                cancelEvent();
            } else {
                console.log('bind cancel!')
            }
        });
        if (ActConfig.bgType === 2) { // 管线
            // RoleSelectorMobile
            // RoleSelector // 这里的miloAlert会报错，就是那个授权那个东西
            var RoleSelector = milo.RoleSelector;
            if (ActConfig.bindWindow === 0) {
                RoleSelector = milo.RoleSelectorMobile;
            }
            RoleSelector.init({
                type: ActConfig.bindWindow === 0 ? 'html' : 'float', // 0表示不弹出默认弹窗，1表示弹出默认弹窗
                gameId: ActConfig.appName,
                charset: 'UTF-8',
                filterChannel: (ActGlobal.loginEnv == 5 || (ActGlobal.bindRoleInfo.sAppid && ActGlobal.bindRoleInfo.sAppid.substr(0, 2) == 'wx')) ? 'weixin' : 'qq',
                openToOpen: {
                    ams_targetappid_wx: ActConfig.wxAppid,
                    ams_targetappid_qc: ActConfig.qqAppid,
                    ams_appname: ActConfig.appName,
                    sAMSTrusteeship: 1, //固定，1表示走微信托管，0表示不走托管
                    // oGopenidParams: { // gopenid游戏角色查询需要。如果需要走gopenid相关转换，需要传此对象参数
                    //     needGopenid: 1, // 传1表示需要后端转换成gopenid,如果需要带注册，则还需要传isPreengage=1
                    //     isGopenid: 1, // 传1表示当前前端登录态已经是gopenid，如果需要带注册，则还需要传isPreengage=1
                    //     isPreengage: 1, // 传1表示自动注册gopenid
                    // },
                },
                channelContentId: channelContentId ? channelContentId : "",    // 渠道 手Q，微信
                systemContentId: "",      // 系统android，ios
                area1ContentId: "",        //端游用到的二级大区
                areaContentId: areaContentId ? areaContentId : "",         // 服务器
                roleContentId: roleContentId ? roleContentId : "",      // 角色
                confirmButtonId: confirmButtonId,//确认按钮，会触发submitEvent
                onSubmit: (roleObj) => {
                    ActGlobal.roleInfo = roleObj;
                    if (PIPSubmitId !== '' && PIPCancelId !== '') {
                        return roleselector.init();
                    }
                    milo.RoleSelector.getPIPInfo({
                        gameId: ActConfig.appName
                    }).then((res) => {
                        console.log('getPIPInfo,location.href', res)
                        if (parseInt(res.retCode) === 0) {
                            ActFun.ActCommitBind(
                                function (res) {
                                    if (typeof submitSuccEvent == "function") {
                                        submitSuccEvent(res);
                                    } else {
                                        console.log(res);
                                    }
                                },
                                function (res) {
                                    if (typeof submitFailEvent == "function") {
                                        submitFailEvent(res);
                                    } else {
                                        console.log(res);
                                    }
                                },
                            );
                        } else {
                            if (typeof ShowPIPFunc === 'function') {
                                ShowPIPFunc();
                            } else {
                                console.log('ShowPIPFunc is not a function!')
                            }
                        }
                    })
                },
                onError: (err) => {
                    console.log(err);
                    alert('登录信息失效，请刷新页面后重试');
                },
            }).then(roleselector => {
                $('#' + PIPCancelId).on('click', function () {
                    if (typeof cancelPIPCallBack === 'function') {
                        cancelPIPCallBack();
                    } else {
                        console.log('cancelPIPCallBack is not a function!')
                    }
                });
                $('#' + PIPSubmitId).on('click', function () {
                    milo.RoleSelector.setPIPInfo({
                        gameId: ActConfig.appName,
                    }).then((res) => {
                        ActFun.ActCommitBind(
                            function (res) {
                                if (typeof submitSuccEvent == "function") {
                                    submitSuccEvent(res);
                                } else {
                                    console.log(res);
                                }
                            },
                            function (res) {
                                if (typeof submitFailEvent == "function") {
                                    submitFailEvent(res);
                                } else {
                                    console.log(res);
                                }
                            },
                        );
                    })
                });
                return roleselector.init();
            }).then(rs => {
                ActGlobal.roleSelect = rs;
            });
        } else { // ams和星图
            need("biz.roleselector", function (Roleselector) {
                var roleSelectConfig = {
                    'type': ActConfig.bindWindow === 0 ? 'html' : 'float', // 0表示不弹出默认弹窗，1表示弹出默认弹窗
                    'gameId': ActConfig.appName,
                    'isQueryRole': true,
                    'systemContentId': "",      // 系统android，ios
                    'channelContentId': channelContentId ? channelContentId : "",    // 渠道 手Q，微信
                    'areaContentId': areaContentId ? areaContentId : "",         // 服务器
                    'area1ContentId': "",        //端游用到的二级大区
                    'roleContentId': roleContentId ? roleContentId : "",      // 角色
                    'confirmButtonId': confirmButtonId,//确认按钮，会触发submitEvent
                    'cancelButtonId': cancelButtonId,//取消按钮，会触发cancelEvent
                    'queryRoleEvent': function (roleObj) {
                        console.log(roleObj); // 这里返回有roleName，但是没有head_url
                        var recentRoleId = ActGlobal.recentRoleInfo.sRoleId;
                        if (recentRoleId.length === 0) {
                            console.log('recentRoleId is null');
                            return;
                        }
                        //查询最近登录角色的详细信息
                        for (var ke in roleObj) {
                            if (roleObj[ke].roleId == recentRoleId) {
                                ActGlobal.roleInfo = {
                                    areaid: ActGlobal.recentRoleInfo.sArea,
                                    areaname: ActGlobal.recentRoleInfo.sAreaName,
                                    roleareaid: roleObj[ke].roleAreaId,
                                    sPartition: ActGlobal.recentRoleInfo.sPartition,
                                    roleid: ActGlobal.recentRoleInfo.sRoleId,
                                    rolename: ActGlobal.recentRoleInfo.sRoleName,
                                    checkparam: roleObj[ke].checkparam,
                                    md5str: roleObj[ke].md5str,
                                };
                                break;
                            }
                        }
                    },
                    'submitEvent': function (roleObj) {
                        // console.log(roleObj.submitData); // 这里能获得openid，在checkparam里面
                        ActGlobal.roleInfo = roleObj.submitData;
                        ActFun.ActCommitBind(
                            function (res) {
                                if (typeof submitSuccEvent == "function") {
                                    // res.aBindInfo.user_openid = ActGlobal.commonUser.userOpenid
                                    ActFun.syncBindRoleInfo(res.aBindInfo, res.role_token);
                                    submitSuccEvent(res);
                                } else {
                                    console.log(res);
                                }
                            },
                            function (res) {
                                if (typeof submitFailEvent == "function") {
                                    submitFailEvent(res);
                                } else {
                                    console.log(res);
                                }
                            },
                        );
                    },//提交信息回调
                    'cancelEvent': function () {
                        if (typeof cancelEvent == "function") {
                            cancelEvent();
                        } else {
                            console.log("Roleselector selecting canceled");
                        }
                    },
                    'onLoginError': function (err) {
                        console.log(err);
                        alert('登录信息失效，请刷新页面后重试');
                    },
                    "openToOpen": {
                        // "ams_targetappid":((ActGlobal.commonUser.iUin.indexOf('owan') < 0)?ActConfig.qqAppid:ActConfig.wxAppid),
                        "ams_targetappid_wx": ActConfig.wxAppid,
                        "ams_targetappid_qc": ActConfig.qqAppid,
                        "ams_appname": ActConfig.appName,
                        "sAMSTrusteeship": 1 //固定，1表示走微信托管，0表示不走托管
                    }
                };
                // 需要自定义pip弹窗的场景
                if (PIPSubmitId !== '' && PIPCancelId !== '') {
                    $('#' + PIPCancelId).on('click', function () {
                        if (typeof cancelPIPCallBack === 'function') {
                            cancelPIPCallBack();
                        } else {
                            console.log('cancelPIPCallBack is not a function!')
                        }
                    });
                    $('#' + PIPSubmitId).on('click', function () {
                        RoleSelector.setPIPInfo({
                            gameId: ActGlobal.appName // 替换成当前业务的gameId
                        }, function (res) {
                            // 可在这里执行自定义逻辑
                            // console.log(res)
                            $('#' + confirmButtonId).click();
                        })
                    });
                    roleSelectConfig.customPIPEvent = function () {
                        console.log('用户未授权');
                        ShowPIPFunc();
                    }
                }
                Roleselector.init(roleSelectConfig);
                // Roleselector.show();
                ActGlobal.roleSelect = Roleselector;
            }, function () {
                console.log('load fail. wtf?!')
            });
        }

        //查询是否绑定角色
        ActFun.ActSetFlowCfg(ActConfig.checkBindId,
            false,
            false,
            {},
            function (res) {
                console.log(res);
                ActGlobal.checkRoleFinish = true;
                if (typeof res === 'undefined' || typeof res.isBind === 'undefined') {
                    failCallBack();
                    return;
                }
                if (res.isBind === true) { // 已绑定
                    ActFun.syncBindRoleInfo(res.aBindInfo, res.aBindInfo.role_token); // 记录下绑定信息
                    if (typeof bindedCallBack == "function") {
                        bindedCallBack(res.aBindInfo); // 把查询到的信息返回一下，可能会用到
                    } else {
                        console.log(res.aBindInfo);
                    }
                } else { // 未绑定 -- 这里需要注意，有可能会返回最近登录的角色
                    if (ActGlobal.loginEnv !== null && parseInt(ActGlobal.loginEnv) >= 3) {
                        ActGlobal.roleSelect === null ? console.log('roleSelecter Init fail! please check!') : ActGlobal.roleSelect.show(); // 这里会弹出选择角色框
                        if (ActConfig.bgType === 2 && ActConfig.bindWindow === 1) {
                            channelContentId = ActGlobal.roleSelect.renderData.renderKey + '_channelContentId';
                            areaContentId = ActGlobal.roleSelect.renderData.renderKey + '_areaContentId';
                            roleContentId = ActGlobal.roleSelect.renderData.renderKey + '_roleContentId';
                        }
                    }
                    if (typeof res.aBindInfo !== "undefined" && Object.keys(res.aBindInfo).length > 0) {
                        var sPartition = res.aBindInfo.partition;
                        var roleId = res.aBindInfo.user_openid;
                        var roleName = res.aBindInfo.charac_name;
                        var headUrl = res.aBindInfo.head_url;
                        if (sPartition > 0 && roleId.length > 0 && roleName.length > 0) {
                            var sArea = sPartition.substr(0, 1);
                            var sAreaName = (ActConfig.bgType === 2) ? window.tempSelector.zoneToName(sPartition) : YXZJServerSelect.zoneToName(sPartition);
                            ActGlobal.recentRoleInfo.sArea = sArea;
                            ActGlobal.recentRoleInfo.sAreaName = sAreaName;
                            ActGlobal.recentRoleInfo.sPartition = sPartition;
                            ActGlobal.recentRoleInfo.sRoleId = roleId;
                            ActGlobal.recentRoleInfo.sRoleName = roleName;
                            ActGlobal.recentRoleInfo.sHeadUrl = headUrl;
                            if (sArea == '2' || sArea == '4') {
                                ActGlobal.recentRoleInfo.sPlatId = 0;
                            } else {
                                ActGlobal.recentRoleInfo.sPlatId = 1;
                            }

                            $('#' + channelContentId).val(sArea).trigger('change');
                            $('#' + areaContentId).val(sPartition).trigger('change');
                        }
                    }
                    if (typeof unBindCallBack == "function") {
                        // ActGlobal.commonUser.userOpenid = res.aBindInfo.user_openid
                        unBindCallBack(res.aBindInfo);
                    } else {
                        console.log(res.aBindInfo);
                    }
                }
            },
            function (res) {
                if (typeof failCallBack == "function") {
                    failCallBack(res);
                } else {
                    alert(res.sMsg);
                }
            });
        ActFun.ActSubmitFlow(ActConfig.checkBindId);
    },
    /**
     * 更改绑定
     */
    ActChangeBind: function (callBack) {
        if (ActGlobal.loginEnv == 5 || (ActGlobal.bindRoleInfo.sAppid && ActGlobal.bindRoleInfo.sAppid.substr(0, 2) == 'wx')) { //加上抢先服
            YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "微信-安卓(android)", v: "3", sk: "android", k: "weixin" }, { t: "微信-苹果(iOS)", v: "4", sk: "ios", k: "weixin" }, { t: "微信-安卓抢先服(android)", v: "7", sk: "android", k: "weixin" }];
            //{t: "微信-苹果抢先服(iOS)", v: "7", sk: "ios", k: "weixin" }
        } else {
            YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "手Q-安卓(android)", v: "1", sk: "android", k: "qq" }, { t: "手Q-苹果(iOS)", v: "2", sk: "ios", k: "qq" }, { t: "手Q-安卓抢先服(android)", v: "6", sk: "android", k: "qq" }];
            //{t: "手Q-苹果抢先服(iOS)", v: "7", sk: "ios", k: "qq" }
        }
        ActGlobal.roleSelect.show();
        if (typeof callBack == "function") {
            callBack();
        }
    },
    /**
     * 确认绑定角色
     */
    ActCommitBind: function (succCallBack, failCallBack) {
        ActGlobal.roleInfo.sPartition = ActGlobal.roleInfo.sPartition ? ActGlobal.roleInfo.sPartition : ActGlobal.roleInfo.partition;
        ActGlobal.roleInfo.sOpenid = ActGlobal.roleInfo.roleid ? ActGlobal.roleInfo.roleid : ActGlobal.roleInfo.roleId;
        ActGlobal.roleInfo.sArea = ActGlobal.roleInfo.areaid ? ActGlobal.roleInfo.areaid : ActGlobal.roleInfo.area;
        if (ActGlobal.roleInfo.sArea == '2' || ActGlobal.roleInfo.sArea == '4') {
            ActGlobal.roleInfo.sPlatId = 0;
        } else {
            ActGlobal.roleInfo.sPlatId = 1;
        }
        ActGlobal.roleInfo.sRoleName = ActGlobal.roleInfo.rolename ? ActGlobal.roleInfo.rolename : ActGlobal.roleInfo.roleName;
        ActGlobal.roleInfo.sHeadUrl = ActGlobal.recentRoleInfo.sHeadUrl;
        ActFun.ActSetFlowCfg(ActConfig.roleBindId,
            false,
            false,
            ActGlobal.roleInfo,
            function (res) {
                if (res.result === 0) {
                    ActGlobal.checkRoleFinish = true;
                    ActFun.syncBindRoleInfo(res.aBindInfo, res.role_token); // 记录下绑定信息
                }
                if (typeof succCallBack == "function") {
                    succCallBack(res);
                } else {
                    console.log(res.sMsg);
                }
            },
            function (res) {
                if (typeof failCallBack == "function") {
                    failCallBack(res);
                } else {
                    console.log(res.sMsg);
                }
            });
        ActFun.ActSubmitFlow(ActConfig.roleBindId);
    },
    /**
     * 将绑定角色信息保存为全局变量
     */
    syncBindRoleInfo: function (roleInfo, token) {
        ActGlobal.isBindRole = true;
        ActGlobal.bindRoleInfo.sServiceType = 'yxzj';
        ActGlobal.bindRoleInfo.sOpenid = roleInfo.user_openid;
        ActGlobal.bindRoleInfo.sRoletoken = token;
        ActGlobal.bindRoleInfo.sPartition = roleInfo.partition;
        ActGlobal.bindRoleInfo.sArea = roleInfo.area;
        ActGlobal.bindRoleInfo.sPlatId = roleInfo.platid;
        ActGlobal.bindRoleInfo.sAmsNewRoleId = roleInfo.newrole;
        ActGlobal.bindRoleInfo.sRoleId = decodeURIComponent(roleInfo.newrole);
        try {
            ActGlobal.bindRoleInfo.sRoleName = decodeURIComponent(roleInfo.charac_name);
        } catch (e) {
            ActGlobal.bindRoleInfo.sRoleName = roleInfo.charac_name;
        }
    },
    /**
     * 设置分享
     */
    ActSetShareData: function (textTitle, textDesc, textLink, textImg, textTail, success, canceled, scenes = 0, autolaunch = false) {
        success = typeof success == 'function' ? success : function () { };
        canceled = typeof canceled == 'function' ? canceled : function () { };
        if (ActConfig.bgType === 2 && !ActFun.isMsdk() && ActFun.isWeiXin()) {
            var opts = {
                wx_appid: 'wxfeb5a65212da517c', //微信公众号appid
                title: textTitle,// 分享标题，默认为活动页面标题（可手动调整）
                desc: textDesc, //分享活动简介
                link: textLink, //分享链接
                imgUrl: textImg, //分享后朋友看到的图标
                sourceName: textTail, // 小尾巴
                /*微信分享回调【不需要可不写】*/
                WXtrigger: function (res) { //微信点击事件回调
                    // 点击的事件没什么必要
                    // alert("微信点击回调\n"+JSON.stringify(res));
                },
                WXsuccess: function (res) { //微信分享成功回调
                    success();
                },
                WXcancel: function (res) { //微信分享取消回调
                    // 这里不可达
                    // alert("微信分享取消回调\n"+JSON.stringify(res));
                },
                WXfail: function (res) { //微信分享失败回调
                    // alert("微信分享失败回调\n"+JSON.stringify(res));
                    canceled();
                },
                QQcallback: function (res) {//qq成功、失败、或取消的回调
                    // alert("QQ分享之后回调回调\n"+JSON.stringify(res));
                    success();
                },
                QQtrigger: function (res) {//qq触发事件的回调
                    // alert("QQ分享触发回调\n"+JSON.stringify(res));
                },
                qqBrowserCallback: function (data) {
                    //data.code ==1 表示能分享
                    //data.code ==-1 表示不能分享
                    //data.code == 0 表示未知
                    // alert("QQ浏览器分享触发回调\n"+JSON.stringify(data));
                    success();
                }
            };
            console.log(opts);
            milo.mobileShare.initShareAll(opts);
            return;
        }
        console.log(ActGlobal.loginEnv);
        switch (ActGlobal.loginEnv) {
            case 0: // 内嵌H5 -- 这里一般是分享大图的
                var params = {
                    "type": "websharephoto",
                    "sharePath": textImg,
                };
                if (scenes == 0) { // 分享到手Q好友和微信好友
                    params.shareType = "Session";
                } else { // 分享到Q空间和朋友圈
                    params.shareType = "TimeLine/Qzone";
                }
                var args = encodeURIComponent(JSON.stringify(params));
                var url = "uniwebview://webview?funcname=SetCommonThing&args=" + args;
                console.log(url);
                ActFun.invokeNativeFunctionByIFrame(url);
                break;
            case 1: // 游戏内浏览器
                if (typeof connectWebViewJavascriptBridge === "undefined") {
                    loadScript(ActConfig.msdkJsPath, function () {
                        console.log("load msdkJsAdapter success!");
                        if (ActGlobal.bindRoleInfo.sAppid.match(/wx/i) == 'wx') { //分享到微信
                            var WXStructuredShare = '{"MsdkMethod":"WGSendToWeiXinWithUrl",' +   //分享的方法
                            '"scene":"' + (scenes == 0) ? 0 : 1 + '",' +                      //分享的场景，1：朋友圈;0：微信好友
                                '"title":"' + textTitle + '",' +           //结构化分享的标题
                                '"desc":"' + textDesc + '",' +             //结构化分享的描述
                                '"imgUrl":"' + textImg + '",' +       //结构化分享的icon
                                '"url":"' + textLink + '",' +                  //结构化分享的链接
                                '"mediaTagName":"MSG_INVITE",' +
                                '"messageExt":"' + textTitle + '"}';
                            msdkShare(WXStructuredShare);
                        } else { //分享到手Q
                            var QQStructuredShare = '{"MsdkMethod":"WGSendToQQ",' +     //分享的方法
                            '"scene":"' + (scenes == 0) ? 2 : 1 + '",' +            //分享的场景，1：QQ空间;2：QQ好友
                                '"title":"' + textTitle + '",' +       //结构化分享的标题
                                '"desc":"' + textDesc + '",' +         //结构化分享的描述
                                '"imgUrl":"' + textImg + '",' +   //结构化分享的icon
                                '"url":"' + textLink + '"}';               //结构化分享的链接
                            msdkShare(QQStructuredShare);//进行分享
                        }
                    });
                } else {
                    if (ActGlobal.bindRoleInfo.sAppid.match(/wx/i) == 'wx') { //分享到微信
                        var WXStructuredShare = '{"MsdkMethod":"WGSendToWeiXinWithUrl",' +   //分享的方法
                        '"scene":"' + (scenes == 0) ? 0 : 1 + '",' +                      //分享的场景，1：朋友圈;0：微信好友
                            '"title":"' + textTitle + '",' +           //结构化分享的标题
                            '"desc":"' + textDesc + '",' +             //结构化分享的描述
                            '"imgUrl":"' + textImg + '",' +       //结构化分享的icon
                            '"url":"' + textLink + '",' +                  //结构化分享的链接
                            '"mediaTagName":"MSG_INVITE",' +
                            '"messageExt":"' + textTitle + '"}';
                        msdkShare(WXStructuredShare);
                    } else { //分享到手Q
                        var QQStructuredShare = '{"MsdkMethod":"WGSendToQQ",' +     //分享的方法
                        '"scene":"' + (scenes == 0) ? 2 : 1 + '",' +            //分享的场景，1：QQ空间;2：QQ好友
                            '"title":"' + textTitle + '",' +       //结构化分享的标题
                            '"desc":"' + textDesc + '",' +         //结构化分享的描述
                            '"imgUrl":"' + textImg + '",' +   //结构化分享的icon
                            '"url":"' + textLink + '"}';               //结构化分享的链接
                        msdkShare(QQStructuredShare);//进行分享
                    }
                }
                break;
            case 2: // 王者营地
                if (window.GameHelper && typeof window.GameHelper.shareWebPage === 'function') {
                    window.GameHelper.shareWebPage(
                        textTitle, //结构化分享的标题
                        textDesc, //结构化分享的描述
                        textImg, //结构化分享的icon
                        textLink, //结构化分享的链接
                        '');
                } else {
                    console.error('GameHelper load failed');
                }
                break;
            case 3: // 第三方浏览器
                need("biz.qqbrowserclient", function (qqBrowserClient) {
                    var shareObj = {
                        title: textTitle,
                        desc: textDesc,
                        share_url: textLink,
                        image_url: textImg,
                        qqBrowserCallback: function (data) {
                            success();
                        }
                    };
                    qqBrowserClient.init(shareObj)
                });
                break;
            case 6: // x5浏览器
                var scene = (scenes == 0) ? 2 : 1; // 1：朋友圈and空间；2：好友
                var params = {
                    method: (ActGlobal.bindRoleInfo.sAppid.match(/wx/i) == 'wx') ? "sendToWeixinWithUrl" : "sendToQQ",
                    scene: scene,
                    title: textTitle,
                    desc: textDesc,
                    url: textLink,
                    imgUrl: textImg
                };
                prompt(JSON.stringify(params));
                break;
            default: // 手Q + 微信
                if (ActFun.isWeiXin()) {
                    console.log('asdsa')
                    need("biz.wxclient", function (WXClient) {
                        //微信客户初始化成功后，返回wx对象
                        WXClient.init({
                            sAppId: "wxfeb5a65212da517c" // 不能用王者的appid，不然会分享失败
                        }, function (wx) {
                            //分享用的信息对象
                            var shareObj = {
                                title: textTitle,
                                desc: textDesc,
                                link: textLink,
                                imgUrl: textImg,
                                actName: ActConfig.actName,//点击流命名
                                success: function (sres) {
                                    success();
                                },
                                cancel: function (sres) {
                                    canceled();
                                }
                            }
                            //为发送给好友、分享到朋友圈、分享到QQ、分享到微博同时绑定分享事件
                            WXClient.shareAll(shareObj);
                        });
                    });
                } else {
                    var shareObjTM = {
                        title: textTitle,
                        desc: textDesc,
                        share_url: textLink,
                        image_url: textImg,
                        img_width: "120",
                        img_height: "120",
                        appid: ActConfig.qqAppid,
                        sourceName: textTail,
                    };
                    if (typeof mqq === "undefined") {
                        return;
                        loadScript(ActConfig.qqApiJsPath, function () {
                            console.log("load mqq success!");
                            mqq.ui.setOnShareHandler(function (type) {
                                shareObjTM.share_type = type;
                                if (type == 0) {
                                    QGCSDK.shareArkMessageSafe({
                                        arkConfig: {
                                            appName: 'com.tencent.gamecenter.qqsy',
                                            appView: 'picView2',
                                            appDesc: '游戏分享',
                                            appPrompt: '游戏分享',
                                            appVersion: '1.0.0.1',
                                            appMeta: {
                                                shareData: {
                                                    appid: '1104466820',
                                                    scene: '1247',
                                                    url: ''
                                                }
                                            }
                                        }
                                    }).then((res) => {
                                        if (res.result === 'success') {
                                            console.log('share success');
                                        } else if (res.result === 'fail') {
                                            console.log('error', res.error.message);
                                        }
                                    })
                                    QGCSDK.onDebugLog(function(text) {
                                        console.log(`QGCSDK debug: ${text}`);
                                    })
                                    success();
                                }else{
                                    if (type == 2 && type == 3) {
                                        shareObjTM.share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfeb5a65212da517c&redirect_uri=" + encodeURIComponent(textLink) + "&response_type=code&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                                    }
                                    mqq.ui.shareMessage(
                                        shareObjTM,
                                        function (result) {
                                            success();
                                        });
                                }
                            });
                            if (autolaunch) {
                                try {
                                    mqq.ui.showShareMenu();
                                } catch (e) {
                                    console.error('唤起手机QQ登录组件失败:', e);
                                }
                            }
                        });
                    } else {
                        mqq.ui.setOnShareHandler(function (type) {
                            shareObjTM.share_type = type;
                            if (type == 0) {
                                QGCSDK.shareArkMessageSafe({
                                    arkConfig: {
                                        appName: 'com.tencent.gamecenter.qqsy',
                                        appView: 'picView2',
                                        appDesc: '游戏分享',
                                        appPrompt: '游戏分享',
                                        appVersion: '1.0.0.1',
                                        appMeta: {
                                            shareData: {
                                                appid: '1104466820',
                                                scene: '1247',
                                                url: ''
                                            }
                                        }
                                    }
                                }).then((res) => {
                                    if (res.result === 'success') {
                                        console.log('share success');
                                    } else if (res.result === 'fail') {
                                        console.log('error', res.error.message);
                                    }
                                })
                                QGCSDK.onDebugLog(function(text) {
                                    console.log(`QGCSDK debug: ${text}`);
                                })
                                success();
                            }else{
                                if (type == 2 && type == 3) {
                                    shareObjTM.share_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxfeb5a65212da517c&redirect_uri=" + encodeURIComponent(textLink) + "&response_type=code&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
                                }
                                mqq.ui.shareMessage(
                                    shareObjTM,
                                    function (result) {
                                        success();
                                    });
                            }
                        });
                        if (autolaunch) {
                            try {
                                mqq.ui.showShareMenu();
                            } catch (e) {
                                console.error('唤起手机QQ登录组件失败:', e);
                            }
                        }
                    }
                }
                break;
        }
    },
    /**
     * 设置流程配置文件
     */
    ActSetFlowCfg: function (flowId, withRole, loadingMask, sData, success, failure) {
        try {
            if (withRole === true) {
                sData = $.extend(sData, ActGlobal.bindRoleInfo);
            }
            if (ActConfig.bgType === 0) {
                var flowObj = {
                    '_everyRead': true, //_everyRead参数用于控制缓存，设为true表示每次发请求都会读取amsCfg参数的值，建议加上
                    "iActivityId": ActConfig.iAMSActivityId, //活动id
                    'activityId': flowId, // 模块实例号
                    "iFlowId": flowId, //流程id
                    "sNeedSubmitPopDiv": loadingMask, // 是否开启loading层，默认打开
                    "sData": sData,
                    "fFlowSubmitEnd": function (res) {
                        if (typeof success == "function") {
                            success(res.jData);
                        } else {
                            alert(res.sMsg);
                        }
                    },
                    "fFlowSubmitFailed": function (res) {
                        //失败会走到这个函数
                        //条件不满足，ame返回大于0是后走到这里
                        if (typeof failure == "function") {
                            failure(res);
                        } else {
                            alert(res.sMsg);
                        }
                    },
                    'onBeginGetGiftEvent': function () {
                        return 0; // 抽奖前事件，返回0表示成功
                    },
                    'onGetGiftFailureEvent': function (res) {// 抽奖失败事件
                        if (typeof failure == "function") {
                            failure(res);
                        } else {
                            alert(res.sMsg);
                        }
                    },
                    'onGetGiftSuccessEvent': function (res) {// 抽奖成功事件
                        if (typeof success == "function") {
                            success(res);
                        } else {
                            alert(res.sMsg);
                        }
                    }
                }
                window["amsCfg_" + flowId] = flowObj;
            } else if (ActConfig.bgType === 1) {
                var flow = {
                    actId: ActConfig.iAMSActivityId,
                    chartId: flowId,
                    sData: sData,
                    loading: loadingMask,
                    success: function (res) {
                        console.log("IDE succ");
                        if (typeof success == "function") {
                            success(res.data);
                        } else {
                            alert(res.sMsg);
                        }
                    },
                    fail: function (res) {
                        console.log("IDE fail");
                        // if(res.iRet === 101 || res.iRet === '101'){
                        //     //todo 登录态失效，需要重新调登录方法 （开发自行实现）
                        // } else if (res.iRet === 99998 || res.iRet === '99998') {
                        //     // todo 调用提交绑定大区方法
                        // }
                        if (typeof failure == "function") {
                            failure(res);
                        } else {
                            alert(res.sMsg);
                        }
                    }
                }
                window["flow_" + flowId] = flow;
            } else {
                var pipe = {
                    iActivityId: ActConfig.iAMSActivityId,
                    iFlowId: flowId,
                    sData: sData,
                    forbidLoading: !loadingMask, // true的时候显示loading层
                    onSuccess: function (res) {
                        console.log("PIPE succ");
                        if (typeof success == "function") {
                            success(res.jData);
                        } else {
                            alert(res.sMsg);
                        }
                    },
                    onFail: function (res) {
                        console.log("PIPE fail");
                        // if(res.iRet === 101 || res.iRet === '101'){
                        //     //todo 登录态失效，需要重新调登录方法 （开发自行实现）
                        // } else if (res.iRet === 99998 || res.iRet === '99998') {
                        //     // todo 调用提交绑定大区方法
                        // }
                        if (typeof failure == "function") {
                            failure(res);
                        } else {
                            alert(res.sMsg);
                        }
                    }
                }
                window["pipe_" + flowId] = pipe;
            }
        } catch (e) {
            console.log(e);
        }
    },
    /**
     * 执行流程
     */
    ActSubmitFlow: function (flowId, sData) {
        try {
            if (ActConfig.bgType === 0 && typeof window["amsCfg_" + flowId] !== "undefined" && typeof sData !== "undefined" && Object.keys(sData).length > 0) {
                window["amsCfg_" + flowId].sData = $.extend(window["amsCfg_" + flowId].sData, sData);
            } else if (ActConfig.bgType === 1 && typeof window["flow_" + flowId] !== "undefined" && typeof sData !== "undefined" && Object.keys(sData).length > 0) {
                window["flow_" + flowId].sData = $.extend(window["flow_" + flowId].sData, sData);
            }
            if (ActConfig.bgType === 0) {
                amsSubmit(ActConfig.iAMSActivityId, flowId);
            } else if (ActConfig.bgType === 1) {
                if (typeof IDE === "undefined") {
                    var jsPath = "//game.gtimg.cn/images/js/ide/latest/ide." + ((ActGlobal.pageChar === 'gbk') ? 'gbk' : 'min') + ".js"
                    loadScript(jsPath, function () {
                        console.log("load IDE success!");
                        IDE.emit(window["flow_" + flowId]);
                    });
                } else {
                    IDE.emit(window["flow_" + flowId]);
                }
            } else {
                milo.Customize.submit(window["pipe_" + flowId])
            }
        } catch (e) {
            console.log(e)
        }
    },
    /**
     * 仅初始化角色选择器，不用提供真实的绑定功能
     */
    initRoleSelector: function (confirmButtonId, cancelButtonId, channelContentId, areaContentId, roleContentId, initSuccEvent, submitSuccEvent, submitFailEvent, cancelEvent) {
        // 普通的milo就是固定的
        if (ActConfig.bindWindow === 1) {
            confirmButtonId = 'confirmButtonId_yxzj';
            channelContentId = 'channelContentId_yxzj';
            areaContentId = 'areaContentId_yxzj';
            roleContentId = 'roleContentId_yxzj';
        }
        if (ActConfig.bgType === 2) { // 管线
            // RoleSelectorMobile
            // RoleSelector // 这里的miloAlert会报错，就是那个授权那个东西
            var RoleSelector = milo.RoleSelector;
            if (ActConfig.bindWindow === 0) {
                RoleSelector = milo.RoleSelectorMobile;
            }
            RoleSelector.init({
                type: ActConfig.bindWindow === 0 ? 'html' : 'float', // 0表示不弹出默认弹窗，1表示弹出默认弹窗
                gameId: ActConfig.appName,
                charset: 'UTF-8',
                filterChannel: (ActGlobal.loginEnv == 5 || (ActGlobal.bindRoleInfo.sAppid && ActGlobal.bindRoleInfo.sAppid.substr(0, 2) == 'wx')) ? 'weixin' : 'qq', // 是否过滤渠道，可选值:no weixin qq auto(根据登录态自动，这个我试过，不行的)
                openToOpen: {
                    ams_targetappid_wx: ActConfig.wxAppid,
                    ams_targetappid_qc: ActConfig.qqAppid,
                    ams_appname: ActConfig.appName,
                    sAMSTrusteeship: 1, //固定，1表示走微信托管，0表示不走托管
                },
                channelContentId: channelContentId ? channelContentId : "",    // 渠道 手Q，微信
                systemContentId: "",      // 系统android，ios
                area1ContentId: "",        //端游用到的二级大区
                areaContentId: areaContentId ? areaContentId : "",         // 服务器
                roleContentId: roleContentId ? roleContentId : "",      // 角色
                confirmButtonId: confirmButtonId,//确认按钮，会触发submitEvent
                onSubmit: (roleObj) => {
                    // console.log('当前角色：', roleObj);
                    ActGlobal.roleInfo = roleObj;
                    ActGlobal.bindRoleInfo.sPartition = roleObj.partition;
                    ActGlobal.bindRoleInfo.sArea = roleObj.area;
                    if (typeof submitSuccEvent == "function") {
                        submitSuccEvent(roleObj);
                    } else {
                        console.log(roleObj);
                    }
                },
                onError: (err) => {
                    console.log(err);
                    console.log(err);
                    if (typeof submitFailEvent == "function") {
                        submitFailEvent(res);
                    } else {
                        console.log(res);
                    }
                },
            }).then(roleselector => {
                return roleselector.init();
            }).then(rs => {
                ActGlobal.roleSelect = rs;
                if (ActGlobal.loginEnv !== null && parseInt(ActGlobal.loginEnv) >= 3) {
                    ActGlobal.roleSelect === null ? console.log('roleSelecter Init fail! please check!') : ActGlobal.roleSelect.show(); // 这里会弹出选择角色框
                    channelContentId = rs.renderData.renderKey + '_channelContentId';
                    areaContentId = rs.renderData.renderKey + '_areaContentId';
                    roleContentId = rs.renderData.renderKey + '_roleContentId';
                }
                $('#' + channelContentId).trigger('change');
                $('#' + areaContentId).trigger('change');
                if (typeof initSuccEvent == "function") {
                    initSuccEvent();
                } else {
                    console.log('role selector init success!');
                }
            });
        } else { // ams和星图
            if (ActGlobal.loginEnv == 5 || (ActGlobal.bindRoleInfo.sAppid && ActGlobal.bindRoleInfo.sAppid.substr(0, 2) == 'wx')) { //加上抢先服
                YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "微信-安卓(android)", v: "3", sk: "android", k: "weixin" }, { t: "微信-苹果(iOS)", v: "4", sk: "ios", k: "weixin" }, { t: "微信-安卓抢先服(android)", v: "7", sk: "android", k: "weixin" }];
                //{t: "微信-苹果抢先服(iOS)", v: "7", sk: "ios", k: "weixin" }
            } else {
                YXZJServerSelect.STD_CHANNEL_DATA = [{ t: "手Q-安卓(android)", v: "1", sk: "android", k: "qq" }, { t: "手Q-苹果(iOS)", v: "2", sk: "ios", k: "qq" }, { t: "手Q-安卓抢先服(android)", v: "6", sk: "android", k: "qq" }];
                //{t: "手Q-苹果抢先服(iOS)", v: "7", sk: "ios", k: "qq" }
            }
            need("biz.roleselector", function (Roleselector) {
                var roleSelectConfig = {
                    'type': ActConfig.bindWindow === 0 ? 'html' : 'float', // 0表示不弹出默认弹窗，1表示弹出默认弹窗
                    'gameId': ActConfig.appName,
                    'isQueryRole': true,
                    'systemContentId': "",      // 系统android，ios
                    'channelContentId': channelContentId ? channelContentId : "",    // 渠道 手Q，微信
                    'areaContentId': areaContentId ? areaContentId : "",         // 服务器
                    'area1ContentId': "",        //端游用到的二级大区
                    'roleContentId': roleContentId ? roleContentId : "",      // 角色
                    'confirmButtonId': confirmButtonId,//确认按钮，会触发submitEvent
                    'cancelButtonId': cancelButtonId,//取消按钮，会触发cancelEvent
                    'queryRoleEvent': function (roleObj) {
                        console.log(roleObj); // 这里返回有roleName，但是没有head_url
                        var recentRoleId = ActGlobal.recentRoleInfo.sRoleId;
                        if (recentRoleId.length === 0) {
                            console.log('recentRoleId is null');
                            return;
                        }
                        //查询最近登录角色的详细信息
                        for (var ke in roleObj) {
                            if (roleObj[ke].roleId == recentRoleId) {
                                ActGlobal.roleInfo = {
                                    areaid: ActGlobal.recentRoleInfo.sArea,
                                    areaname: ActGlobal.recentRoleInfo.sAreaName,
                                    roleareaid: roleObj[ke].roleAreaId,
                                    sPartition: ActGlobal.recentRoleInfo.sPartition,
                                    roleid: ActGlobal.recentRoleInfo.sRoleId,
                                    rolename: ActGlobal.recentRoleInfo.sRoleName,
                                    checkparam: roleObj[ke].checkparam,
                                    md5str: roleObj[ke].md5str,
                                };
                                break;
                            }
                        }
                    },
                    'submitEvent': function (roleObj) {
                        // console.log(roleObj.submitData); // 这里能获得openid，在checkparam里面
                        ActGlobal.roleInfo = roleObj.submitData;
                        if (typeof submitSuccEvent == "function") {
                            submitSuccEvent(roleObj.submitData);
                        } else {
                            console.log(roleObj.submitData);
                        }
                    },//提交信息回调
                    'cancelEvent': function () {
                        if (typeof cancelEvent == "function") {
                            cancelEvent();
                        } else {
                            console.log("Roleselector selecting canceled");
                        }
                    },
                    'onLoginError': function (err) {
                        console.log(err);
                        alert('登录信息失效，请刷新页面后重试');
                    },
                    "openToOpen": {
                        // "ams_targetappid":((ActGlobal.commonUser.iUin.indexOf('owan') < 0)?ActConfig.qqAppid:ActConfig.wxAppid),
                        "ams_targetappid_wx": ActConfig.wxAppid,
                        "ams_targetappid_qc": ActConfig.qqAppid,
                        "ams_appname": ActConfig.appName,
                        "sAMSTrusteeship": 1 //固定，1表示走微信托管，0表示不走托管
                    }
                };
                Roleselector.init(roleSelectConfig);
                ActGlobal.roleSelect = Roleselector;
            }, function () {
                console.log('load fail. wtf?!')
            });
            // 上面是初始化完了
            if (ActGlobal.loginEnv !== null && parseInt(ActGlobal.loginEnv) >= 3) {
                ActGlobal.roleSelect === null ? console.log('roleSelecter Init fail! please check!') : ActGlobal.roleSelect.show(); // 这里会弹出选择角色框
            }
            $('#' + channelContentId).trigger('change');
            $('#' + areaContentId).trigger('change');
            if (typeof initSuccEvent == "function") {
                initSuccEvent();
            } else {
                console.log('role selector init success!');
            }
        }
    },
    /**
     * 初始化所有上报，建议在查询绑定获取到openid的时候初始化，已废弃
     */
    initReport: function (openid) { // 初始化tam上报，入参为openid
        // console.log("Logined openid: " + openid);
        try {
            if (/^owan+/.test(openid)) {
                window.xomReporter.setWxOpenId(openid);
            } else {
                window.xomReporter.setQqOpenId(openid);
            }
        } catch (e) {
            console.log(e)
            console.log("xomReporter is not initailed yet....")
        }
    },
    /**
     * 打开游戏
     * @param autoLaunch  自动拉起游戏，没有下载则自动下载；
     * @param noTrace  无痕打开，拉起游戏但是不跳转
     */
    openGame: function (autoLaunch = false, noTrace = false) {
        if (ActFun.isMsdk() && !ActFun.isYingDi()) { // 游戏内或者游戏内浏览器，不用拉起游戏
            return;
        }
        var iosFlag = ActFun.isIos();
        if (ActFun.isQQ()) { // 手Q
            if (typeof mqq === "undefined") {
                loadScript(ActConfig.qqApiJsPath, function () {
                    console.log("load mqq success!");
                    var myurl = 'https://speed.gamecenter.qq.com/pushgame/v1/detail?appid=1104466820&_wv=2164260896&_wwv=448&autosubscribe=1'
                    var paraStr = '?platform=qq_m&launchform=sq_gamecenter&gamedata=' + milo.request('data') + '&platformdata=&atoken=$AT$&ptoken=$PT$&openid=$OPID$&user_openid=$OPID$';
                    if (autoLaunch) {
                        myurl += '&autodownload=1&autolaunch=1';
                    }
                    if (noTrace) {
                        if (iosFlag) {
                            if (/ipad/i.test(navigator.userAgent)) {//ipad判断
                                window.location.href = "smoba1104466820://?" + milo.request('data');
                            } else {
                                mqq.app.launchAppWithTokens(
                                    ActConfig.qqAppid,
                                    paraStr
                                );
                            }
                        } else { // 安卓
                            if (ActFun.checkYXZJInstalled()) { // 已安装
                                mqq.app.launchAppWithTokens({
                                    appID: ActConfig.qqAppid,
                                    packageName: 'com.tencent.tmgp.sgame',
                                    paramsStr: paraStr,
                                    flag: '67108864', //android 必须
                                });
                            } else {
                                mqq.ui.openUrl({	//使用此方法可以在新窗口中打开手Q游戏专区，可以从专区返回活动
                                    url: myurl,
                                    target: 1,
                                    style: 3
                                });
                            }
                        }
                    } else {
                        mqq.ui.openUrl({	//使用此方法可以在新窗口中打开手Q游戏专区，可以从专区返回活动
                            url: myurl,
                            target: 1,
                            style: 3
                        });
                    }
                });
            } else {
                var myurl = 'https://speed.gamecenter.qq.com/pushgame/v1/detail?appid=1104466820&_wv=2164260896&_wwv=448&autosubscribe=1'
                var paraStr = '?platform=qq_m&launchform=sq_gamecenter&gamedata=' + milo.request('data') + '&platformdata=&atoken=$AT$&ptoken=$PT$&openid=$OPID$&user_openid=$OPID$';
                if (autoLaunch) {
                    myurl += '&autodownload=1&autolaunch=1';
                }
                if (noTrace) {
                    if (iosFlag) {
                        if (/ipad/i.test(navigator.userAgent)) {//ipad判断
                            window.location.href = "smoba1104466820://?" + milo.request('data');
                        } else {
                            mqq.app.launchAppWithTokens(
                                ActConfig.qqAppid,
                                paraStr
                            );
                        }
                    } else { // 安卓
                        if (ActFun.checkYXZJInstalled()) { // 已安装
                            mqq.app.launchAppWithTokens({
                                appID: ActConfig.qqAppid,
                                packageName: 'com.tencent.tmgp.sgame',
                                paramsStr: paraStr,
                                flag: '67108864', //android 必须
                            });
                        } else {
                            mqq.ui.openUrl({	//使用此方法可以在新窗口中打开手Q游戏专区，可以从专区返回活动
                                url: myurl,
                                target: 1,
                                style: 3
                            });
                        }
                    }
                } else {
                    mqq.ui.openUrl({	//使用此方法可以在新窗口中打开手Q游戏专区，可以从专区返回活动
                        url: myurl,
                        target: 1,
                        style: 3
                    });
                }
            }
        } else if (ActFun.isWeiXin()) { // 微信
            // 无痕拉起的方法微信已经失效了，所以就不管了，只有微信游戏中心拉起
            if (noTrace) {
                WeixinJSBridge.invoke(
                    "launchApplication",
                    {
                        schemeUrl: 'tencentmsdk1104466820://',
                    },
                    function (sRes) {
                        if (sRes && sRes.err_msg.indexOf("launchApplication:ok") != -1) {
                            console.log('ok')
                        } else {
                            console.log('weixin invoke failure!')
                        }
                    }
                );
            } else {
                // window.open('https://game.weixin.qq.com/cgi-bin/h5/static/circlecenter/mixed_circle.html?appid=wx95a3a4d7c627e07d')
                window.open('https://pvp.qq.com/d/a20210827mch/play.html')
                // window.open('https://pvp.qq.com/act/a20180628code/index.htm')
            }
        } else { // 营地之类的第三方
            if (noTrace) {
                window.location.href = "tencentmsdk1104466820://";
            } else {
                console.log('https://pvp.qq.com/d/a20210827mch/play.html?browser=start&noDownloadAlert=true')
                window.open('https://pvp.qq.com/d/a20210827mch/play.html?browser=start&noDownloadAlert=true');
            }
        }
    },
    /**
     * 打开eruda进行debug
     */
    openDebug: function () {
        loadScript("//cdn.jsdelivr.net/npm/eruda", function () {
            eruda.init();
        });
        // if(typeof IDE !== 'undefined'){
        //     IDE. showVConsole();
        // } else {
        //     loadScript("//cdn.jsdelivr.net/npm/eruda", function () {
        //         eruda.init();
        //     });
        // }
    },
    /**
     * 防止暴力点击，时间可以在ActConfig设置
     */
    antiClickBrush: function () {//点击频率限制函数
        var now = (new Date()).getTime();
        console.log('ActGlobal.lastClickTime', ActGlobal.lastClickTime)
        console.log('ActConfig.timeInterval', ActConfig.timeInterval)
        console.log('now', now)
        if (ActGlobal.lastClickTime != null && now - ActGlobal.lastClickTime < ActConfig.timeInterval) {//当两次点击时间小于指定时间时，返回false
            return false;
        } else {
            ActGlobal.lastClickTime = now;//更新判断点击间隔的变量
            return true;
        }
    },
    /**
     * 检查是否已安装王者，仅支持安卓
     */
    checkYXZJInstalled: function () {
        if (ActFun.isAndroid()) {
            if (typeof mqq === "undefined") {
                loadScript(ActConfig.qqApiJsPath, function () {
                    console.log("load mqq success!");
                    mqq.app.isAppInstalled('com.tencent.tmgp.sgame', function (result) {
                        return result.result;
                    });
                });
            } else {
                mqq.app.isAppInstalled('com.tencent.tmgp.sgame', function (result) {
                    return result.result;
                });
            }
        } else {
            console.log("can't check YXZJ is installed in IOS.");
        }
    },
    loginByQQ: function () {
        need("biz.login", function (LoginManager) {
            LoginManager.login({
                iUseQQConnect:(typeof window.iUseQQConnect != 'undefined') ? window.iUseQQConnect : 0,//是否使用QQ互联
            });
        });
    },
    loginByWx: function () {
        if (!ActFun.isWeiXin()) {
            if (ActConfig.wxOpenLink.length > 0) {
                ActFun.loginByOpenLink();
            } else {
                console.log("非微信环境请配置openlink~");
                alert('请在【王卡助手】微信公众号回复“王者荣耀”参与活动');
            }
            return;
        }
        need("biz.login", function (LoginManager) {//测试
            var redirectUrl = window.location.href;
            var params = "acctype=wx&appid=" + ActConfig.commonAppid;
            if (redirectUrl.indexOf('?') == -1) {
                redirectUrl += "?" + params;
            } else {
                redirectUrl += "&" + params;
            }
            var redirectWxUrl = "https://iu.qq.com/wxauth/redirect.html?url=" + encodeURIComponent(redirectUrl);
            LoginManager.loginByWX({
                redirect_wx_url: redirectWxUrl,
                appConfig: ActConfig.appConfig
            });
        });
    },
    loginByOpenLink: function () {
        window.location.href = ActConfig.wxOpenLink;
    },
    logout: function () {
        need("biz.login", function (LoginManager) {
            LoginManager.logout(
                {
                    logoutCallback: function () {
                        console.log("force to reload cookie");
                        window.location.reload();
                    }
                }
            );
        });
    },
    /**
     * 如果跳转手Q有问题，尝试在需要打开的链接后加上?_wwv=128
     * http://mqq.oa.com/webview.html
     * @param {*} url
     */
    jumpToQQAPP: function (url) {
        var jumpUrl = "mqqapi://forward/url?url_prefix=" + window.btoa(url) + "&version=1&src_type=web";
        if (typeof (mqq) != "object") {
            ActFun.asyncLoadJs(ActFun.qqApiJsPath, function () {
                window.location.href = jumpUrl;
            });
        } else {
            window.location.href = jumpUrl;
        }
    },
    //获取通用的请求参数
    sDataWithRole: function (flag) {
        if (flag) {
            return $.extend(ActGlobal.sData, ActGlobal.bindRoleInfo);
        } else {
            return ActGlobal.sData;
        }
    },
    /*是否是微信环境*/
    isWeiXin: function () {
        return /MicroMessenger/gi.test(navigator.userAgent);
    },
    /*是否是QQ环境*/
    isQQ: function () {
        var sUserAgent = window.navigator.userAgent;
        var REGEXP_IOS_QQ = new RegExp("(iPad|iPhone|iPod).*? (IPad)?QQ\\/([\\d\\.]+)");
        var REGEXP_ANDROID_QQ = new RegExp("\\bV1_AND_SQI?_([\\d\\.]+)(.*? QQ\\/([\\d\\.]+))?", "ig");
        //判断是否是IOSQQ 或者 AndroidQQ打开
        var isIphoneOs_QQ = REGEXP_IOS_QQ.test(sUserAgent);
        var isAndroid_QQ = REGEXP_ANDROID_QQ.test(sUserAgent);

        if (isIphoneOs_QQ || isAndroid_QQ) {
            return true;
        } else {
            return false;
        }
    },
    /*是否是安卓系统*/
    isAndroid: function () {
        var ua = window.navigator.userAgent.toLowerCase();
        if (/android/i.test(ua)) {
            return true;
        } else {
            return false;
        }
    },
    /*是否是IOS系统*/
    isIos: function () {
        var ua = window.navigator.userAgent.toLowerCase();
        if (/iphone|ipod|ipad/i.test(ua)) {
            return true;
        } else {
            return false;
        }
    },
    isQQByAppid: function () {
        var currentAppid = milo.request("appid");
        return /^\d+$/.test(currentAppid);
    },
    isMsdk: function () {
        if (milo.request("msdkEncodeParam")) {
            return true;
        }
        return false;
    },
    isYingDi: function () {
        var judge = milo.request("source");
        return /^smoba_zhushou$/.test(judge);
    },
    asyncLoadJs: function (srcUrl, callback) {
        var script = document.createElement('script');
        script.async = "async";
        script.src = srcUrl;
        if (callback) {
            script.onload = callback;
        }
        document.getElementsByTagName("head")[0].appendChild(script);
    },
    invokeNativeFunctionByIFrame: function (url) {
        var WVJBIframe = document.createElement("iframe");
        WVJBIframe.style.display = "none";
        WVJBIframe.src = url;
        document.documentElement.appendChild(WVJBIframe);
        setTimeout(function () {
            document.documentElement.removeChild(WVJBIframe)
        }, 500);
    },
    /**
     * 游戏内设置活动朝向
     * @param orientation 0：横竖屏；1：竖屏；2：横屏
     */
    setWebviewOrientation: function (orientation) {
        msdkSetWebviewOrientaton(orientation);
    },
    /**
     * 返回游戏
     */
    returnGame: function () {
        var addrUrl = location.href;
        var params = "";
        var index = addrUrl.indexOf("?");
        if (index != -1) {
            params = addrUrl.substr(index);
        }
        var msdkSchemeUrl = "wxcde873f99466f74a://" + params;
        var doLaunch = function () {
            setTimeout(function () {
                WeixinJSBridge.invoke('launchApplication', {
                    "schemeUrl": msdkSchemeUrl,
                }, function (res) { })
            }, 500);
        }

        //if (isNewWeixin()) {
        if (true) {
            //大于等于6.5.6
            if (window.WeixinJSBridge) {
                doLaunch();
            } else {
                document.addEventListener('WeixinJSBridgeReady', function () {
                    doLaunch(); //此时立即调用权限可能还未准备好，所以doLaunch里需要延迟调用
                });
            }
        } else {
            location.href = msdkSchemeUrl;
        }
    },
    /**
     * 关闭msdk浏览器
     */
    msdkCloseWebview: function () {
        if (ActFun.isIos()) {
            msdkiOSHandler('CloseMSDKWebview', data, null);
        } else {
            var data = '{"MsdkMethod":"CloseMSDKWebview"}'
            prompt(data)
        }
    },
    /**
     * 浏览器全屏
     */
    setFullScreen: function () {
        var SetFullScreen = '{"MsdkMethod":"WGSetFullScreen","isFullScreen":"true"}';
        msdkCall('WGSetFullScreen', SetFullScreen);
    },
    /**
     * 还原浏览器全屏
     */
    resetFullScreen: function () {
        var SetFullScreen = '{"MsdkMethod":"WGSetFullScreen","isFullScreen":"false"}';
        msdkCall('WGSetFullScreen', SetFullScreen);
    },
    /**
     * 内置逻辑，不要直接调用
     */
    invokeNativeFunctionByIFrame: function (url) {
        var hiddenArea = $("#hiddenArea");
        var hiddenIframe;
        hiddenIframe = document.createElement('iframe');
        hiddenIframe.style.display = 'none';
        hiddenArea.append(hiddenIframe);
        hiddenIframe.src = url;

        setTimeout(function () {
            hiddenIframe.remove();
        }, 5000);
    },
    /**
     * 客户端红点，0消除红点，1展示红点
     * env表示环境，0测试环境，1正式环境
     */
    notifyRedNum: function (num, env) {
        console.log('redNum:' + num);
        if (num <= 0) {
            num = 0;
        } else {
            num = 6;
        }
        var params = {
            "amsActId": (env === 0) ? (ActConfig.iAMSActivityId + '00') : ActConfig.iAMSActivityId, // 测试环境需要加00
            "redNum": num.toString()
        };
        var args = encodeURIComponent(JSON.stringify(params));
        var url = "uniwebview://webview?funcname=SetRedPoint&args=" + args;
        console.log(url);
        ActFun.invokeNativeFunctionByIFrame(url);
    },
    /**
     * 内嵌H5跳转到指定场景
     */
    jumpGameSence: function (id, param1, param2) {
        var params = {
            "type": "JumpForm",
            "EntryId": id.toString(),
            "param1": param1.toString(),
            "param2": param2.toString(),
        };
        var args = encodeURIComponent(JSON.stringify(params));
        var url = "uniwebview://webview?funcname=SetCommonThing&args=" + args;
        console.log(url);
        ActFun.invokeNativeFunctionByIFrame(url);
    },
    /**
     * 内嵌H5分享大图到朋友圈or空间
     */
    quanShare: function (picUrl) {
        picUrl = picUrl.replace("pvp.sparta.html5.qq.com/", '');
        picUrl = picUrl.replaceAll('_tde_/', '');
        picUrl = picUrl.replaceAll('_', '.');
        const params = {
            type: "websharephoto",
            sharePath: picUrl,
            shareType: "TimeLine/Qzone"
        };
        const args = encodeURIComponent(JSON.stringify(params));
        const url = "uniwebview://webview?funcname=SetCommonThing&args=" + args;
        console.log("朋友圈/空间大图分享", url, params);
        ActFun.invokeNativeFunctionByIFrame(url);
    },
    /**
     * 内嵌H5分享大图到好友
     */
    friendShare: function (picUrl) {
        picUrl = picUrl.replace("pvp.sparta.html5.qq.com/", '');
        picUrl = picUrl.replaceAll('_tde_/', '');
        picUrl = picUrl.replaceAll('_', '.');
        const params = {
            type: "websharephoto",
            sharePath: picUrl,
            shareType: "Session"
        };
        const args = encodeURIComponent(JSON.stringify(params));
        const url = "uniwebview://webview?funcname=SetCommonThing&args=" + args;
        console.log("好友大图分享", url, params);
        ActFun.invokeNativeFunctionByIFrame(url);
    },
}
if (typeof $('html meta').forEach !== 'undefined') {
    $('html meta').forEach(function (element) {
        if (ActGlobal.pageChar !== null && ActGlobal.pageChar !== '') {
            return;
        }
        ActGlobal.pageChar = $(element).attr('charset');
    });
}
if (typeof loadScript === 'undefined') {
    // throw Error("Sent to blackhole"); // Send to blackhole
    if (typeof milo.loader.loadScript === 'undefined') {
        window.loadScript = milo.loader.loadScript;
    } else {
        window.loadScript = function (url, callback) {
            var head = document.getElementsByTagName("head")[0];
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = url;
            var timeout = setTimeout(function () {
                head.removeChild(script);
                (typeof callback === 'function') && callback.call(this, false)
            }, 5000);
            head.appendChild(script);
            return true;
        }
    }
}
if (ActFun.isMsdk() && typeof connectWebViewJavascriptBridge === "undefined") {
    loadScript(ActConfig.msdkJsPath, function () {
        console.log("load msdkJsAdapter success!");
    });
}