import { LogUtils } from "./LogUtils"
import AppConfig from "../Config/AppConfig"
import EventMgr from "../Event/EventMgr"
import { ryw_Event } from "../Event/EventEnum"
import TTAPI from "../../Platform/tt/TTAPI"
import OPPOAPI from "../../Platform/oppo/OPPOAPI"
import VIVOAPI from "../../Platform/vivo/VIVOAPI"
import QQMiniGameAPI from "../../Platform/qq/QQMiniGameAPI"
import WXAPI from "../../Platform/weixin/WXAPI"
import BagManager from "../../Scripts/Manager/BagManager"
import PrefabManage from "../../Scripts/PrefabManager/PrefabManage"

/**
 * 平台相关
 */

export default class AppPlatform {
    private static readonly PlatformResSubName_custom: string = "PlatformRes";
    public static isBackGameWX: boolean = false; //是否从后台回到前台 微信

    //平台登录
    public static loginPlatform_custom(successListener: Function, failListener: Function, pcListener?: Function) {
        if (AppPlatform.is_TT_GAME_custom()) {//抖音,字节跳动
            TTAPI.ttLogin_custom(function (code) {
                successListener(code)
            }, () => {
                failListener();
            })
        } else if (AppPlatform.is_WECHAT_GAME_custom()) {
            WXAPI.wxLogin_custom(function (code) {
                successListener(code)
            }, null)

        }
        else if (AppPlatform.is_OPPO_GAME_custom()) { //oppo小游戏
            OPPOAPI.initAdService_custom(() => { }, () => { }, () => { });
            OPPOAPI.Login_custom(function (code) {
                successListener(code)
            }, null)
        }
        else if (AppPlatform.is_QQ_PLAY_custom()) {  //qq小游戏
            QQMiniGameAPI.Login_custom(function (code) {
                successListener(code)
            }, null)
        }
        else if (AppPlatform.is_VIVO_GAME_custom()) {//VIVO 小游戏
            let failCounter = 0;
            let _successListener = (code: any) => {
                successListener(code)
            }
            let fail = () => {
                if (failCounter >= 1) {
                    console.log("vivo 登陆失败!!!重试次数已达上限");
                    failListener();
                    return;
                }
                VIVOAPI.showDialog_custom("提示", "登录失败,点击确定按钮重试", [{ text: '确定', color: '#33dd44' }], () => {
                    VIVOAPI.Login_custom(function (token, type) { _successListener(token); }, function () { fail(); });
                    ++failCounter;
                }, () => { }, () => { });
            }
            VIVOAPI.Login_custom(function (token, type) { _successListener(token); }, function () { fail(); });
        }

        // else if (AppPlatform.is_BD_GAME_custom()) {//百度小游戏
        //     BDAPI.bdLogin_custom((code) => {
        //         successListener(code)
        //     }, null);
        // }
        else if (AppPlatform.is_Android_custom() || AppPlatform.is_Iphone_custom()) {//android  ios
            LogUtils.log_custom("playVideo android ios 未实现")
        } else {
            pcListener ? pcListener() : failListener();
        }
    }

    /**
     * 加载一个分包完毕 做一些处理
     * @param subName 
     */
    public static loadSubpackageFinish_custom(subName: string) {
        //加载广告模块

    }

    /**
     * 播放视频
     * @param tab 
     * @see name        播放的视频的名字,一般情况下不需要传,用AppConfig中配置好的,如果ios,android name=="full"则为全屏视频,不填为激励视频
     * @see onClose   视频播放完成的回调  true 完整观看,false为完整观看
     * @see onFailed  视频播放失败的回调
     */
    public static playVideo_custom(tab: { name?: string, onClose?: Function, onFailed?: Function }): void {
        //内部人员无广
        // let guangJuanNum = BagManager.getBagGoodNums(8888)
        // guangJuanNum = 10000
        // if(guangJuanNum>0){
        //     PrefabManage.showTextTips('免广劵减1')
        //     BagManager.subBagList(8888)
        //     if (tab.onClose) {
        //         tab.onClose(true);
        //         EventMgr.emitEvent_custom(ryw_Event.ryw_Video_Finish_custom) 
        //     }
        //     return
        // }
        let guangJuanNum = BagManager.getBagGoodNums(3700)
        if (guangJuanNum > 0) {
            PrefabManage.showTextTips('无广卷减1')
            BagManager.subBagList(3700)
            if (tab.onClose) {
                tab.onClose(true);
            }
            return
        }

        if (AppPlatform.is_WECHAT_GAME_custom()) {
            WXAPI.showRewardedVideoAd_custom(tab.onClose, tab.onFailed, tab.name);
        } else if (AppPlatform.is_TT_GAME_custom()) {
            cc.audioEngine.pauseAll();
            TTAPI.showRewardedVideoAd_custom(tab.onClose, tab.onFailed);
        } else if (AppPlatform.is_VIVO_GAME_custom()) {
            VIVOAPI.showRewardedVideoAd_custom(tab.onClose, tab.onFailed);
        } else if (AppPlatform.is_OPPO_GAME_custom()) {
            OPPOAPI.showRewardedVideoAd_custom(tab.onClose, tab.onFailed);
        } else if (AppPlatform.is_QQ_PLAY_custom()) {
            QQMiniGameAPI.showRewardedVideoAd_custom(tab.onClose, tab.onFailed);
        } else if (AppPlatform.is_Android_custom() || AppPlatform.is_Iphone_custom()) {
            LogUtils.log_custom("playVideo android ios 未实现")
        }
        else {//其他平台
            LogUtils.log_custom("playVideo 其他平台 未实现")
            if (tab.onClose) {
                tab.onClose(true);
            }
        }
    }

    /**
     * 提示系统 toast
     * @param title 提示文字
     */
    public static showToast_custom(title: string): void {
        if (AppPlatform.is_WECHAT_GAME_custom()) {

        } else if (AppPlatform.is_TT_GAME_custom()) {
            window["tt"].showToast({
                title: title,
                icon: "none"
            })
        } else if (AppPlatform.is_VIVO_GAME_custom()) {
            window["qg"].showToast({
                message: title
            })
        } else if (AppPlatform.is_OPPO_GAME_custom()) {
            window["qg"].showToast({
                title: title,
                icon: "none"
            })
        } else if (AppPlatform.is_QQ_PLAY_custom()) {
            window["qq"].showToast({
                title: title,
                icon: "none"
            })
        } else if (AppPlatform.is_Android_custom()) {


        } else if (AppPlatform.is_Iphone_custom()) {

        }
        else {//其他平台
            LogUtils.log_custom("showToast 其他平台 未实现")
        }
    }


    //检测更新
    public static checkUpdate_custom() {
        let platform = "";
        if (AppPlatform.is_WECHAT_GAME_custom()) {
            platform = "wx";
        } else if (AppPlatform.is_TT_GAME_custom()) {
            platform = "tt";
        }
        //支持 wx 与 头条
        if (platform != "") {
            console.log("启动了版本更新机制。。。。")
            let updateManager = window[platform].getUpdateManager()
            updateManager.onCheckForUpdate(function (res) {
                console.log("是否需要更新 : ", res.hasUpdate)
            })
            updateManager.onUpdateReady(function () {
                window[platform].showModal({
                    title: '更新提示',
                    content: '新版本已经准备好,是否重启小游戏?',
                    success: function (res) {
                        if (res.confirm) {
                            cc.assetManager.cacheManager.clearLRU()
                            updateManager.applyUpdate()
                        }
                    }
                })
            })
            updateManager.onUpdateFailed(function () {
                console.log("新版本下载失败!!!")
            })
        }
    }


    /**
     * 跳转其他小游戏
     * @param data 
     * @param ad_tag 标签
     */
    public static navigateToMiniProgram_custom(data: any, ad_tag?: any) {
        if (data) {
            LogUtils.log_custom("跳转游戏: " + data.title);
            if (AppPlatform.is_TT_GAME_custom()) {//抖音
                TTAPI.showMoreGamesModal_custom(() => {
                    LogUtils.log_custom("跳转成功")
                }, () => {
                    LogUtils.log_custom("跳转失败")
                    EventMgr.emitEvent_custom(ryw_Event.ryw_ADKRQ_ClickQuit_custom);
                });
            } else if (AppPlatform.is_WECHAT_GAME_custom()) {//微信
                // RYPlatformMgr.sendClickAd_custom(data.id);
                //点击广告 
                WXAPI.navigateToMiniProgram_custom(data.appid, data.url, (res) => {
                    LogUtils.log_custom("跳转成功")

                    // RYPlatformMgr.sendClickAdAllow_custom(data.id);
                }, (res: any) => {
                    LogUtils.log_custom("跳转失败")
                    EventMgr.emitEvent_custom(ryw_Event.ryw_ADKRQ_ClickQuit_custom);
                    if (res.errMsg == "navigateToMiniProgram:fail cancel") {
                        LogUtils.log_custom("用户取消跳转");

                        EventMgr.emitEvent_custom(ryw_Event.ryw_ADKRQ_ClickQuit_custom, ad_tag)
                    }
                }, (res: any) => {
                    LogUtils.log_custom("跳转完成")
                });
            }
            else if (AppPlatform.is_OPPO_GAME_custom()) {
                OPPOAPI.navigateToMiniProgram_custom(data.appid, data.title, data.url, (res) => {
                    LogUtils.log_custom("跳转成功")
                }, (res) => {
                    LogUtils.log_custom("跳转失败")
                    EventMgr.emitEvent_custom(ryw_Event.ryw_ADKRQ_ClickQuit_custom);
                }, (res: any) => {
                    LogUtils.log_custom("跳转完成")
                });


            }
            else if (AppPlatform.is_QQ_PLAY_custom()) {  //qq小游戏
                QQMiniGameAPI.navigateToMiniProgram_custom(data.appid, data.url, (res) => {
                    LogUtils.log_custom("跳转成功")
                }, (res: any) => {
                    LogUtils.log_custom("跳转失败")
                    EventMgr.emitEvent_custom(ryw_Event.ryw_ADKRQ_ClickQuit_custom);
                }, (res: any) => {
                    LogUtils.log_custom("跳转完成")
                });
            }
            else if (AppPlatform.is_VIVO_GAME_custom()) {
                VIVOAPI.navigateToMiniProgram_custom(data.appid, data.url, (res) => {
                    LogUtils.log_custom("跳转成功")
                }, (res: any) => {
                    LogUtils.log_custom("跳转失败")
                    EventMgr.emitEvent_custom(ryw_Event.ryw_ADKRQ_ClickQuit_custom);
                }, (res: any) => {
                    LogUtils.log_custom("跳转完成")
                });
            }
        }
    }

    //初始游戏
    public static initGame_custom() {
        if (AppPlatform.is_WECHAT_GAME_custom()) {

        }
        else if (AppPlatform.is_QQ_PLAY_custom()) {
            // CachedQQBannerAd.preloadBanner_custom();
            QQMiniGameAPI.LoadAppBoxAd_custom(() => { }, () => { });
        }
        else if (AppPlatform.is_OPPO_GAME_custom()) {
            if (null != window["qg"].reportMonitor && typeof (window["qg"].reportMonitor) == 'function') {
                window["qg"].reportMonitor('game_scene', 0);
            }
            OPPOAPI.LoadCahcedNativeAd_custom();
        }
        else if (AppPlatform.is_VIVO_GAME_custom()) {
            VIVOAPI.LoadCahcedNativeAd_custom();
        }
        else if (AppPlatform.is_TT_GAME_custom()) {

        }
    }

    /**
     * 是否是微信小游戏
     */
    public static is_WECHAT_GAME_custom(): boolean {
        if (AppConfig.isWX_TT_QQ_MiniGame_custom == 0 && cc.sys.platform == cc.sys.WECHAT_GAME) {
            return true;
        }
        return false;
    }

    /**
     * 是否是QQ 玩一玩
     */
    public static is_QQ_PLAY_custom(): boolean {
        if (cc.sys.platform == cc.sys.WECHAT_GAME && AppConfig.isWX_TT_QQ_MiniGame_custom == 2) {
            return true;
        }
        return false;
        // if (cc.sys.platform == cc.sys.QQ_PLAY && cc.sys.browserType == cc.sys.BROWSER_TYPE_QQ_PLAY) {
        //     return true;
        // }
        // return false;
    }

    /**
     * 是否是OPPO小游戏
     */
    public static is_OPPO_GAME_custom(): boolean {
        if (cc.sys.platform == cc.sys.OPPO_GAME) {
            return true;
        }
        return false;
    }

    /**
     * 是否是VIVO小游戏
     */
    public static is_VIVO_GAME_custom(): boolean {
        if (cc.sys.platform == cc.sys.VIVO_GAME) {
            return true;
        }
        return false;
    }

    /**
     * 是否是抖音
     */
    public static is_TT_GAME_custom(): boolean {
        if (cc.sys.platform == cc.sys.BYTEDANCE_GAME) {
            return true;
        }
        return false;
    }


    /**
     * 是否是小米快游戏
     */
    public static is_Xiaomi_GAME_custom(): boolean {
        if (cc.sys.platform == cc.sys.XIAOMI_GAME) {
            return true;
        }
        return false;
    }


    /**
     * 是否原生Android
     */
    public static is_Android_custom(): boolean {
        if (cc.sys.platform == cc.sys.ANDROID) {
            return true;
        }
        return false;
    }

    /**
     * 是否是 iphonex iphonexs  iphonexr
     */
    public static isIphoneX_custom() {
        if (this.is_Iphone_custom()) {
            //显示整个游戏窗口的真实像素分辨率
            let size = cc.sys.windowPixelResolution;
            if ((size.width == 2436 && size.height == 1125) || (size.height == 2436 && size.width == 1125)) {//iphone x
                return true;
            } else if ((size.width == 2688 && size.height == 1242) || (size.height == 2688 && size.width == 1242)) {//iphone xs
                return true;
            } else if ((size.width == 1792 && size.height == 828) || (size.height == 1792 && size.width == 828)) {//iphone xr
                return true;
            }
        }
        return false;
    }

    //是否是 iPhone ios
    public static is_Iphone_custom() {
        if (cc.sys.platform == cc.sys.IPHONE || cc.sys.platform == cc.sys.IPAD) {
            return true;
        }
        return false;
    }

    //获取场景值
    public static getLaunchOptionsSync_custom() {
        let obj = null;
        if (AppPlatform.is_TT_GAME_custom()) {//抖音
            obj = window["tt"].getLaunchOptionsSync();
            let str = JSON.stringify(obj);
            LogUtils.log_custom("场景值: " + str)
            return obj;
        } else if (AppPlatform.is_WECHAT_GAME_custom()) {//微信
            obj = window["wx"].getLaunchOptionsSync()
            let str = JSON.stringify(obj);
            LogUtils.log_custom("场景值: " + str)
            return obj;
        } else if (AppPlatform.is_OPPO_GAME_custom()) {//oppo
            var options = window["qg"].getLaunchOptionsSync();
            if (null != options && options != "") {
                obj = options;
            }
            else {
                obj = { query: "", referrerInfo: { package: "", extraData: { appid: "" } } }
                console.log("没有启动设置!!!")
            }
            let str = JSON.stringify(obj);
            LogUtils.log_custom("场景值: " + str)
            return obj;
        } else if (AppPlatform.is_QQ_PLAY_custom()) {   //qq小游戏
            obj = window["qq"].getLaunchOptionsSync()

            let str = JSON.stringify(obj);
            LogUtils.log_custom("场景值: " + str)
            return obj;
        } else if (AppPlatform.is_VIVO_GAME_custom()) {
            obj = {};
            return obj;
        }
        obj = {};
        return obj;
    }

    public static isOtherGame() {
        if (!AppPlatform.is_TT_GAME_custom()
            && !AppPlatform.is_VIVO_GAME_custom()
            && !AppPlatform.is_OPPO_GAME_custom()
            && !AppPlatform.is_QQ_PLAY_custom()
            && !AppPlatform.is_WECHAT_GAME_custom()) {
            return true;
        }
        return false;
    }


    public static PlatformOnShow(callback) {
        if (AppPlatform.is_TT_GAME_custom()) {//抖音
            window["tt"].onShow((res) => {
                if (callback) {
                    callback(res)
                }
                console.log("启动参数:", res.query);
                console.log("来源信息:", res.refererInfo);
                console.log("场景值:", res.scene);
                console.log("启动场景字段:", res.launch_from, ", ", res.location);
            });
        } else if (AppPlatform.is_WECHAT_GAME_custom()) {
            window["wx"].onShow(function () {
                if (callback) {
                    callback()
                }
                console.log('微信 显示在前台');
                AppPlatform.isBackGameWX = true;
            });
        }
    }


    public static PlatformOnHide(callback) {
        if (AppPlatform.is_TT_GAME_custom()) {//抖音
            window["tt"].onHide(() => {
                if (callback) {
                    callback()
                }
                console.log("小游戏隐藏");
            });
        } else if (AppPlatform.is_WECHAT_GAME_custom()) {
            window["wx"].onHide(function () {
                if (callback) {
                    callback()
                }
                console.log('微信onhide');

            });
        }
    }


    public static PlatformShare(complate: Function, titel: string, imageUrl: string) {
        if (AppPlatform.is_TT_GAME_custom()) {//抖音
            TTAPI.share_custom(complate)
        }
        else if (AppPlatform.is_WECHAT_GAME_custom()) {
            WXAPI.share_custom((finish) => {
                complate && complate();
            }, titel, imageUrl);
        }
        else {
            complate && complate();
        }
    }

}