import AppPlatform from "../../FrameWork/Util/AppPlatform";
import AppConfig from "../../FrameWork/Config/AppConfig";
import HttpUnit from "../../FrameWork/NetWork/HttpUnit";
import AppSwitchConfig from "../../FrameWork/Config/AppSwitchConfig";
import { LogUtils } from "../../FrameWork/Util/LogUtils";


export default class OPPOAPI {
    public static readonly adUnitId_custom = "";
    public static readonly bannerAdUnitId_custom = "";
    public static readonly InsAdUnitId_custom = "";
    public static readonly OpenScreenAdUnitId_custom = "";
    public static readonly NativeAdId_custom = ""

    public static get BannerInstance_custom() {
        return OPPOAPI._banner_custom;
    }
    protected static _banner_custom: any = null;

    public static Login_custom(onSuccess: Function, onFail: Function) {
        if (AppPlatform.is_OPPO_GAME_custom()) {
            window["qg"].login(
                {
                    success: (res) => {
                        let token = res.data.token;
                        onSuccess(token);
                        console.log("OPPO 登陆成功,获取到 token : " + token);
                        for (var key in res) {
                            console.log(key, res[key]);
                        }
                    },
                    fail: (res) => {
                        console.log("OPPO 登陆失败", res);
                        for (var key in res) {
                            console.log(key, res[key]);
                        }
                    }
                })
        }
    }

    public static initAdService_custom(onSuccess: Function, onFail: Function, onComplete: Function) {
        window["qg"].initAdService(
            {
                appId: AppConfig.AppID_custom,
                isDebug: false,
                success: function (res) {
                    console.log("oppo initAdService success");
                    if (onSuccess) {
                        onSuccess(res)
                    }
                },
                fail: function (res) {
                    console.log("oppo initAdService fail: ", res.code, res.msg);
                    if (onFail) {
                        onFail(res)
                    }
                },
                complete: function (res) {
                    console.log("oppo initAdService complete");
                    if (onComplete) {
                        onComplete(res)
                    }
                }
            })
    }

    public static showRewardedVideoAd_custom(onAdClose: Function, onFailed: Function, id?: string) {
        if (AppPlatform.is_OPPO_GAME_custom()) {
            let videoId = AppConfig.tt_adUnitId_custom
            if (id) {
                videoId = id;
            }
            let videoAd = window["qg"].createRewardedVideoAd({
                posId: videoId
            })
            videoAd.onLoad(() => {
                console.log("oppo 视频广告加载完成");
                videoAd.show();
            })
            videoAd.onVideoStart(() => {
                console.log("oppo 视频广告开始播放");
            })
            videoAd.onClose((res) => {
                if (res.isEnded) {
                    console.log("oppo 视频广告观看 完成");
                    onAdClose(true);
                } else {
                    console.log("oppo 视频广告观看 未完成");
                    onAdClose(false);
                }
                videoAd.destroy();
            })
            videoAd.onError((err) => {
                console.log("oppo 视频广告获取失败", err);
                videoAd.destroy();
                onFailed();
            })
            videoAd.load();
        }
        else {
            onAdClose(true);
        }
    }

    public static navigateToMiniProgram_custom(pkgName: string, gameName: string, path: string, onSuccess: Function, onFail: Function, onComplate: Function) {

        if (AppPlatform.is_OPPO_GAME_custom()) {
            console.log("OPPO 跳转游戏: " + pkgName);
            HttpUnit.reportExport_custom(pkgName, gameName, (result) => {
                if (1 == result.code) {
                    console.log("OPPO 导出上报成功");
                }
                else {
                    console.log("OPPO 导出上报失败", result.msg);
                }
            }, (result) => {
                console.log("OPPO 导出上报失败");
                for (var key in result) {
                    console.log(key, result[key]);
                }
            });
            let time = Date.now();
            while (Date.now() - time <= 500) {

            }
            window["qg"].navigateToMiniGame(
                {
                    pkgName: pkgName,
                    path: path,
                    extraData: {
                        from: AppConfig.AppID_custom
                    },
                    envVersion: 'release',
                    success(res) {
                        if (onSuccess) {
                            onSuccess(res)
                        }
                    },
                    fail(res) {
                        if (onFail) {
                            onFail(res)
                        }
                    },
                    // complete(res) {
                    //     if (onComplate) {
                    //         onComplate(res)
                    //     }
                    // }
                })


        }
    }

    public static showInterstitialAd_custom(onAdClose: Function, onFailed: Function) {

        if (AppPlatform.is_OPPO_GAME_custom()) {
            var insertAd = window["qg"].createInsertAd({
                posId: OPPOAPI.InsAdUnitId_custom
            })
            insertAd.load();
            insertAd.onLoad(() => {
                console.log("插屏广告加载完成");
                insertAd.show();
            })
            insertAd.onShow(() => {
                console.log("插屏广告显示成功");
            })
            insertAd.onError((err) => {
                console.log("插屏广告拉取失败", err);
                insertAd.destroy();
                if (onFailed) {
                    onFailed();
                }
            })
        }
        else {
            onAdClose();
        }
    }

    public static showBannaer_custom(): any {
        if (OPPOAPI._banner_custom) {
            OPPOAPI._banner_custom.show();
            return;
        }
        var bannerAd = window["qg"].createBannerAd({
            posId: OPPOAPI.bannerAdUnitId_custom
        })
        bannerAd.show();
        OPPOAPI._banner_custom = bannerAd;
    }

    public static hideBanner_custom() {
        if (OPPOAPI._banner_custom) {
            OPPOAPI._banner_custom.hide();
        }
    }

    public static destroyBanner_custom() {
        if (OPPOAPI._banner_custom) {
            OPPOAPI._banner_custom.destroy();
        }
        OPPOAPI._banner_custom = null;
    }

    public static getLaunchOptionsSync_custom() {
        let obj: any = { query: "", referrerInfo: { package: "", extraData: { appid: "" } } }

        if (AppPlatform.is_OPPO_GAME_custom()) {
            var options = window["qg"].getLaunchOptionsSync();
            if (null != options && options != "") {
                obj = options;
            }
            else {
                console.log("没有启动设置!!!")
            }
            return obj;
        }
        return obj;
    }

    public static share_custom(complate: Function, titel: string, imageUrl: string) {
        complate(false);
    }

    public static createDesktopIcon_custom(onSuccess: Function, onFail: Function) {

        if (AppPlatform.is_OPPO_GAME_custom()) {
            window["qg"].hasShortcutInstalled({
                success: function (res) {
                    if (res == false) {
                        window["qg"].installShortcut(
                            {
                                success: function () {
                                    if (onSuccess) {
                                        onSuccess();
                                    }
                                },
                                fail: function (err) {
                                    if (onFail) {
                                        onFail();
                                    }
                                    console.log("创建桌面图标失败!!!!", err);
                                    for (var key in err) {
                                        console.log(key, err);
                                    }
                                },
                                complete: function () {

                                }
                            })
                    }
                    else {
                        console.log("桌面图标已存在!!!!");
                        if (onFail) {
                            onFail();
                        }
                    }
                },
                fail: function (err) {
                    if (onFail) {
                        onFail();
                    }
                    console.log("判断桌面图标是否存在失败!!!", err);
                    for (var key in err) {
                        console.log(key, err);
                    }
                },
                complete: function () {

                }
            })
        }
        else {
            if (onFail) {
                onFail();
            }
        }
    }

    //根据配置的概率自动弹出创建图标确认框
    public static autoPopCreateDestopIcon_custom(onSuccess: Function, onFail: Function) {

        if (!AppPlatform.is_OPPO_GAME_custom()) {
            if (null != onFail) {
                onFail();
            }
            return;
        }
        let rate = Math.floor(Math.random() * 100);
        if (rate <= AppSwitchConfig.getInstance_custom().getAppSwitchData_custom().oppocfg_custom.addToDesktop_custom) {
            OPPOAPI.createDesktopIcon_custom(onSuccess, onFail);
        }
        else {
            if (null != onFail) {
                onFail();
            }
        }
    }

    //显示OPPO原生界面
    public static showNativeAd_custom(onSuccess: Function, onFail: Function) {
        LogUtils.warn_custom("111111111111111111111111")
        // if (!AppPlatform.is_OPPO_GAME()) {
        //     if (null != onFail) {
        //         onFail();
        //     }
        //     return;
        // }
        // if (1 == AppSwitchConfig.getInstance().getAppSwitchData().oppocfg.yuanshengSwitch) {
        //     ViewMgr.instance.openView(ViewDef.OPPONativeView, null, (v: OPPONativeAdViewTemplate) => {
        //         if (null != onSuccess) {
        //             onSuccess(v);
        //         }
        //     });
        // }
        // else {
        //     if (null != onFail) {
        //         onFail();
        //     }
        // }
    }



    public static _cachedNativeAd_custom: any = null;
    public static _cachedAdItem_custom: any = null;
    public static _cachedimgUrl_custom: string = null;
    public static _tryLoadCount_custom: number = 5;



    public static LoadCahcedNativeAd_custom(): void {
        if (OPPOAPI._cachedNativeAd_custom) {
            OPPOAPI._cachedNativeAd_custom.destroy();
            OPPOAPI._cachedNativeAd_custom = null;
        }
        OPPOAPI._cachedAdItem_custom = null;
        OPPOAPI._cachedNativeAd_custom = window["qg"].createNativeAd({
            posId: OPPOAPI.NativeAdId_custom
        })
        OPPOAPI._cachedNativeAd_custom.load();
        ++OPPOAPI._tryLoadCount_custom;
        console.log("缓存 原生广告 开始加载");

        let self = this;

        OPPOAPI._cachedNativeAd_custom.onLoad((res) => {
            console.log("缓存 原生广告 加载成功:", res);
            var adlist = res.adList;
            for (var i = 0; i < adlist.length; ++i) {
                var ad = adlist[i];
                console.log("缓存 原生广告 数据:", i);
                for (var key in ad) {
                    console.log(key, ad[key]);
                }
            }
            OPPOAPI._cachedAdItem_custom = adlist[Math.floor(Math.random() * adlist.length)];
            if (null != OPPOAPI._cachedAdItem_custom) {
                for (var i = 0; i < OPPOAPI._cachedAdItem_custom.imgUrlList.length; ++i) {
                    console.log("缓存 原生广告 imgUrlList : ", i + " ", OPPOAPI._cachedAdItem_custom.imgUrlList[i])
                }
                let imgUrlList = OPPOAPI._cachedAdItem_custom.imgUrlList;
                for (let i = 0; i < imgUrlList.length; ++i) {
                    let imgUrl = imgUrlList[i];
                    OPPOAPI._cachedimgUrl_custom = imgUrl;
                    if (null != OPPOAPI._cachedimgUrl_custom && "" != OPPOAPI._cachedimgUrl_custom) {
                        break;
                    }
                }
                if (null != OPPOAPI._cachedimgUrl_custom && "" != OPPOAPI._cachedimgUrl_custom) {
                    console.log("缓存 原生广告  加载图片", OPPOAPI._cachedimgUrl_custom);
                }
                else {
                    console.log("缓存 原生广告 加载失败 imgulr is : ", OPPOAPI._cachedimgUrl_custom);
                    OPPOAPI._cachedNativeAd_custom.destroy();
                    OPPOAPI._cachedNativeAd_custom = null;
                    setTimeout(() => {
                        OPPOAPI.LoadCahcedNativeAd_custom();
                    }, 2500);
                }
            }
        })
        OPPOAPI._cachedNativeAd_custom.onError((res) => {
            console.log("缓存 原生广告 加载失败:", res);
            for (var key in res) {
                console.log(key, res[key]);
            }
            OPPOAPI._cachedNativeAd_custom.destroy();
            OPPOAPI._cachedNativeAd_custom = null;
            setTimeout(() => {
                OPPOAPI.LoadCahcedNativeAd_custom();
            }, 5000);
        })
    }

    /**
     * 判断是否创建桌面图标
     * @param onSuccess 
     * @param onFail 
     */
    public static hasShortcutInstalled(onSuccess: Function, onFail: Function) {
        window["qg"].hasShortcutInstalled({
            success: function (res) {
                if (res == false) {
                    console.log("桌面图标不存在!!!!");
                    if (onSuccess) {
                        onSuccess(false);
                    }
                }
                else {
                    console.log("桌面图标已存在!!!!");
                    if (onSuccess) {
                        onSuccess(true);
                    }
                }
            },
            fail: function (err) {
                if (onFail) {
                    onFail();
                }
                console.log("判断桌面图标是否存在失败!!!", err);
                for (var key in err) {
                    console.log(key, err);
                }
            },
            complete: function () {

            }
        })
    }

}