import AppPlatform from "../../FrameWork/Util/AppPlatform";
import AppConfig from "../../FrameWork/Config/AppConfig";
import AppSwitchConfig from "../../FrameWork/Config/AppSwitchConfig";
import wudianMgr from "../../FrameWork/Mgr/WudianMgr";


export class GameRecorder {
    protected get recorder_custom() {
        // if(null == this._recorder)
        // {
        //     if(Laya.Browser.onMiniGame)
        //     {
        //         if (null != Laya.Browser.window["wx"].getGameRecorder
        //             && "function" == typeof (Laya.Browser.window["wx"].getGameRecorder))  
        //         {
        //             this._recorder = Laya.Browser.window["wx"].getGameRecorder();
        //             if(null != this._recorder)
        //             {
        //                 this._recorder.on('start', () => { console.log("开始录屏") });
        //                 this._recorder.on('stop', (res) => { console.log("停止录屏 录屏长度:", res.duration) });
        //                 this._recorder.on('pause', () => { console.log("暂停录屏") });
        //                 this._recorder.on('resume', () => { console.log("继续录屏") });
        //                 this._recorder.on('abort', () => { console.log("丢弃录屏") });
        //             }
        //         }
        //         else
        //         {
        //             console.log("不支持微信录屏!");
        //         }
        //     }
        // }
        return this._recorder_custom;
    }
    protected _recorder_custom: any = null;

    /**
    * 开始录屏
    */
    public start_custom() {
        if (null != this.recorder_custom) {
            this.recorder_custom.start();
        }
    }
    /**
    * 停止录屏
    */
    public stop_custom() {
        if (null != this.recorder_custom) {
            this.recorder_custom.stop();
        }
    }
    /**
    * 暂停录屏
    */
    public pause_custom() {
        if (null != this.recorder_custom) {
            this.recorder_custom.pause();
        }
    }
    /**
    * 从暂停状态恢复到录制状态
    */
    public resume_custom() {
        if (null != this.recorder_custom) {
            this.recorder_custom.resume();
        }
    }
    /**
    * 舍弃录屏
    */
    public abort_custom() {
        if (null != this.recorder_custom) {
            this.recorder_custom.abort();
        }
    }
    /**
    * 显示分享按钮
    */
    public showShareBtn_custom() {
        if (null != this.recorder_custom) {
            let button = window["wx"].createGameRecorderShareButton({
                // 样式参数
                style: {
                    left: 10,
                    top: 150,
                    height: 50,
                    color: '#ffffff',
                    textAlign: 'center',
                    fontSize: 16,
                    borderRadius: 4,
                    iconMarginRight: 16,
                    paddingLeft: 1,
                    paddingRight: 30,
                },
                // 按钮的背景图片
                image: 'button.jpg',
                text: '自定义文案',
                icon: 'icon.jpg',
                // 分享参数
                share: {
                    query: 'a=1&b=2',
                    // 背景音乐的路径
                    bgm: 'walkin.mp3',
                    timeRange: [[0, 1000], [2000, 3000]],
                    title: {
                        template: 'default.score',
                        data: {
                            score: 6500
                        }
                    },
                    button: {
                        template: 'default.enter',
                    }
                }
            })
        }
    }
}

export default class WXAPI {


    public static readonly GameRecorder_custom = new GameRecorder();

    public static wxLogin_custom(onSuccess: Function, onFail: Function) {
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            window["wx"].login(
                {
                    success: (res) => {
                        if (res.code) {
                            let code = res.code;
                            console.log("登陆成功,获取到code : " + code)
                            onSuccess(code);
                        }
                    }
                })
        }
    }


    //-------------------------激励视频---------------------------------
    protected static _isRegRewardedVideoAdEvent_custom = false;
    protected static _onRewardedVideoAdFailed_custom: Function = null;
    protected static _onRewardedVideoAdClose_custom: Function = null;
    protected static onRewardedVideoAdLoad_custom() {
        console.log('激励视频 广告加载完成')
    }
    protected static onRewardedVideoAdError_custom(err) {
        console.log('激励视频 广告加载失败' + err)
        if (WXAPI._onRewardedVideoAdFailed_custom) {
            WXAPI._onRewardedVideoAdFailed_custom();
        }
    }
    protected static onRewardedVideoAdClose_custom(res) {
        if ((res && res.isEnded) || res == null) {
            console.log('激励视频 已完整观看')
            if (WXAPI._onRewardedVideoAdClose_custom) {
                WXAPI._onRewardedVideoAdClose_custom(true)
            }
        }
        else {
            console.log('激励视频 未完整观看')
            if (WXAPI._onRewardedVideoAdClose_custom) {
                WXAPI._onRewardedVideoAdClose_custom(false)
            }
        }
    }
    protected static regRewardedVideoAdEvent_custom(rewardedVideoAd) {

        rewardedVideoAd.onLoad(WXAPI.onRewardedVideoAdLoad_custom)
        rewardedVideoAd.onError(WXAPI.onRewardedVideoAdError_custom)
        rewardedVideoAd.onClose(WXAPI.onRewardedVideoAdClose_custom)

        WXAPI._isRegRewardedVideoAdEvent_custom = true;
    }
    public static showRewardedVideoAd_custom(onAdClose: Function, onFailed: Function, id?: string) {
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            WXAPI._onRewardedVideoAdClose_custom = onAdClose;
            WXAPI._onRewardedVideoAdFailed_custom = onFailed;

            // 中昱版本
            // let videoids = [
            //     'adunit-c7bd96dcbbb64965',
            //     'adunit-6e934a1930991975',
            //     'adunit-d68053701196d5ec'
            // ]
            // let index = Math.floor(Math.random() * videoids.length); 
            // if(index >= 3){
            //     index = 2;
            // }
            let videoId = 'adunit-5f7b05e86460186f';//videoids[index];//AppConfig.adUnitId_custom
            id = 'adunit-5f7b05e86460186f'; 
            // if (id) {
            //     videoId = id;
            // }

            // 嗨鹿版本
            // let videoId = 'adunit-fbe06f21d4c53ec4'

            console.log('videoId================0',videoId)
            console.log('videoId================1',videoId)
            let rewardedVideoAd = window["wx"].createRewardedVideoAd(
                {
                    adUnitId: videoId,
                }
            );

            if (!WXAPI._isRegRewardedVideoAdEvent_custom) {
                WXAPI.regRewardedVideoAdEvent_custom(rewardedVideoAd);
            }

            rewardedVideoAd.load().then(() => {
                let promise = rewardedVideoAd.show();
                promise.then(() => console.log('激励视频 广告显示成功'));
                promise.catch((err) => {
                    rewardedVideoAd.load()
                        .then(() => rewardedVideoAd.show())
                        .catch(err => {
                            console.log('激励视频 广告显示失败')
                            // if (onFailed) {
                            //     onFailed();
                            // }
                        })
                });
            }).catch(err => {
                console.log('激励视频 广告加载失败')
                // if (onFailed) {
                //     onFailed();
                // }
            })
        }
        else {
            onAdClose(true);
        }
    }
    //----------------------------------------------------------------


    //-------------------------小游戏跳转---------------------------
    public static navigateToMiniProgram_custom(appId: string, path: string, onSuccess: Function, onFail: Function, onComplate: Function) {
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            console.log("跳转游戏: " + appId);
            window["wx"].navigateToMiniProgram(
                {
                    appId: appId,
                    path: path,
                    extraData: {
                        foo: 'bar'
                    },
                    envVersion: 'release',
                    success(res) {
                        if (onSuccess) {
                            onSuccess(res)
                        }
                    },
                    fail(res) {
                        if (onFail) {
                            onFail(res)
                        }
                    },
                    complete(res) {
                        if (onComplate) {
                            onComplate(res)
                        }
                    }
                })

        }
    }
    //----------------------------------------------------------------------

    //---------------------分享----------------------------------------
    protected static _onShow_custom: Function = null;
    protected static _lastShareTime_custom: number = 0;
    public static share_custom(complate: Function, titel: string, imageUrl: string) {

        if (AppPlatform.is_WECHAT_GAME_custom()) {
            WXAPI._onShow_custom = () => {
                window["wx"].offShow(WXAPI._onShow_custom)
                WXAPI._onShow_custom = null;
                var c = Date.now() - this._lastShareTime_custom;
                if (complate) {
                    if (Date.now() - this._lastShareTime_custom > 2000) {
                        complate(true)
                    }
                    else {
                        complate(false)
                    }
                }
            }
            window["wx"].onShow(WXAPI._onShow_custom)
            this._lastShareTime_custom = Date.now();
            window["wx"].shareAppMessage(
                {
                    title: titel,
                    imageUrl: imageUrl
                }
            );
        }
    }
    //----------------------------------------------------------------------


    //--------------------插屏幕广告---------------------------------------
    public static showInterstitialAd_custom(onAdClose: Function, onFailed: Function) {

        return;
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            var interstitialAd = window["wx"].createInterstitialAd({
                adUnitId: 'adunit-ceaa3ecd2361b779'//AppConfig.InsAdUnitId_custom,
            })

            interstitialAd.onLoad(() => {
                console.log('插屏广告 加载完成');
                interstitialAd.show().catch((err) => {
                    console.log('插屏广告 显示失败 :' + err)
                    if (onFailed) {
                        onFailed();
                    }
                })
            })

            interstitialAd.onError((err) => {
                console.log('插屏广告 加载失败' + err);
                if (onFailed) {
                    onFailed();
                }
            })

            interstitialAd.onClose(() => {
                console.log('插屏广告 关闭');
                if (onAdClose) {
                    onAdClose();
                }
            })
        }
        else {
            onAdClose();
        }
    }
    /**
     * 得到小程序启动参数的同步方法,可得到一个Object返回值,返回值具体的数据结构在下面的列表中
     * scene	number	启动小游戏的场景值
     * query	Object	启动小游戏的 query 参数
     * shareTicket	string	shareTicket,详见获取更多转发信息
     * referrerInfo	object	来源信息。从另一个小程序、公众号或 App 进入小程序时返回。否则返回 {}
     * https://developers.weixin.qq.com/minigame/dev/api/base/app/life-cycle/wx.getLaunchOptionsSync.html
     * @static
     * @returns {LaunchOptions} 
     * @memberof WXAPI
     */
    public static getLaunchOptionsSync_custom() {
        // let result = { scene: 0, query: null, shareTicket: "", referrerInfo: null };

        if (AppPlatform.is_WECHAT_GAME_custom()) {
            let obj = window["wx"].getLaunchOptionsSync()
            console.log("场景值 " + obj.scene);
            let str = JSON.stringify(obj.query);
            console.log("Query参数 " + str);
            let key = obj.query["key"];
            console.log("Query参数:key " + key);
            console.log("ShareTicket " + obj.shareTicket);
            console.log("ReferrerInfo.appId " + obj.referrerInfo.appId);
            console.log("ReferrerInfo.extraData " + obj.referrerInfo.extraData);
            return obj;
        }
        let obj = { scene: 1001, query: "", shareTicket: "", appId: "", extraData: "" }
        return obj;
    }

    public static async wxOnShow_custom(){
        /* 这里上报from */
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            window['wx'].onShow((args)=>{
                let query = args.query;
                let gdt_vid = query.gdt_vid;
                let weixinadinfo = query.weixinadinfo
            });
        }
        return null;
    }

    //----------------------------------------------------------------------
    /**
     * 打开微信左上角分享转发点击事件,在游戏逻辑中调用一次即可
     * 注意此方法只会在真机上执行,在微信模拟器环境下点击转发按钮什么都不会发生
     * 
     * @static
     * @param {string} titel 分享标题
     * @param {string} imageUrl 分享图片地址
     * @param {Function} [success] 成功回调函数(可不填)
     * @param {Function} [fail] 失败回调函数(可不填)
     * @param {Function} [complate] 完成回调函数,成功失败都会执行(可不填)
     * @memberof WXAPI
     */
    public static SetShareMenu_custom(titel: string, imageUrl: string, success?: Function, fail?: Function, complate?: Function) {

        if (AppPlatform.is_WECHAT_GAME_custom()) {
            console.log("小游戏设置转发按钮");
            window["wx"].showShareMenu({
                withShareTicket: false,
                success: success,
                fail: fail,
                complete: complate
            });
            window["wx"].onShareAppMessage(function () {
                return {
                    title: titel,
                    imageUrl: imageUrl
                }
            });
        }
    }

    //检测更新
    public static checkUpdate_custom() {
        console.log('微信进入新版本更新shaoyang11111')
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            //cc.assetManager.cacheManager.clearLRU();
            var updateManager = window["wx"].getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                console.log("是否需要更新 : ", res.hasUpdate)
            })
            updateManager.onUpdateReady(function () {
                window["wx"].showModal({
                    title: '更新提示',
                    content: '新版本已经准备好,是否重启小游戏?',
                    success: function (res) {
                        if (res.confirm) {
                            console.log('微信进入新版本更新shaoyang22222')
                            cc.assetManager.cacheManager.clearLRU();
                            updateManager.applyUpdate()
                        }
                    }
                })
            })
            updateManager.onUpdateFailed(function () {
                console.log("新版本下载失败!!!")
            })
        }
    }

    protected static _crazyClickShowCounter_custom: number = 0;

    //尝试打开微信狂点界面
    public static tryShowWXCrazyClick_custom(): boolean {
        if (!wudianMgr.wudianFlag_custom || 1 != AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().wxcfg_custom.kuangdianBanner_custom) {
            return false;
        }
        let kuangdianLevelSpcacing = AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().wxcfg_custom.kuangdianLevelSpcacing_custom;
        if (kuangdianLevelSpcacing == 0) {
            return true;
        }
        console.log(' WXAPI._crazyClickShowCounter_custom = ' + WXAPI._crazyClickShowCounter_custom + ' (kuangdianLevelSpcacing - 1) = ' + (kuangdianLevelSpcacing - 1));
        if (WXAPI._crazyClickShowCounter_custom == (kuangdianLevelSpcacing - 1)) {
            WXAPI._crazyClickShowCounter_custom = 0;
            return true;
        }
        WXAPI._crazyClickShowCounter_custom++;
        return false;
    }

    //检查是否已添加到我的小程序
    public static checkIsAddedToMyMiniProgram(onSuccess: Function){
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            window["wx"].checkIsAddedToMyMiniProgram({
                success: res => {
                    console.log(res);
                    if(onSuccess){
                        onSuccess(res.added)
                    }
                }
            });
        }
        
    }


    //订阅消息
    public static requestSubscribeMessageNewBanben(onSuccess: Function){
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            if(window["wx"].requestSubscribeMessage){
                window["wx"].requestSubscribeMessage({
                    tmplIds: ['rqtbYwBPIAVwc1KJnAAvIGnIetWDlRjNO0rR5BmGqI4'],
                    success (res) {
                        console.log('订阅消息', res)
               
                        if(onSuccess){
                            onSuccess(res)
                        }
                    }
                  })
            }
        
        }
        
    } 

    public static requestSubscribeMessageNewGuanka(onSuccess: Function){
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            if(window["wx"].requestSubscribeMessage){
                window["wx"].requestSubscribeMessage({
                    tmplIds: ['qJLO08nqnmdKEVF-AIEez7EvZl_yfY6GQgwx5b6gmFA'],
                    success (res) {
                        console.log('订阅消息', res)
                
                        if(onSuccess){
                            onSuccess(res)
                        }
                    }
                  })
            }
        
        }
        
    } 

}