import AppPlatform from "../../FrameWork/Util/AppPlatform";
import AppConfig from "../../FrameWork/Config/AppConfig";
import Common5 from "../th/Common5";
import Common from "../../FrameWork/Util/Common";
import EventMgr from "../../FrameWork/Event/EventMgr";
import { ryw_Event } from "../../FrameWork/Event/EventEnum";

import User from "../../FrameWork/User/User";
import UserManager from "../../Scripts/Manager/UserManager";
/**
 * 抖音
 */
export default class TTAPI {

    //移到 AppConfig

    // public static readonly adUnitId = ""   
    // public static readonly bannerAdUnitId = ""   
    // public static readonly InsAdUnitId = ""
    // public static readonly _templateId = ""       //分享素材id


    private static recordRes_custom: string = ""
    private static record_custom: any;

    protected static _banner_custom: any = null;


    public static loginCode  = "";
    protected static _onShow_custom: Function = null;
    protected static startDate:number = 0;
    protected static stopDate:number = 0;
    
    protected static fourGridGamePanel: any = null;

    public static ttLogin_custom(onSuccess: Function, onFail: Function) {
        if (AppPlatform.is_TT_GAME_custom()) {
            window["tt"].login(
                {
                    force: false,
                    success: (res) => {
                        console.log(res)
                        console.log("登陆成功1");
                        let code = res.code;
                        if (code) {
                            onSuccess(code);
                        } else {
                            console.log("用户没有登陆,采用临时code")
                            onFail();
                        }

                        // window["tt"].getUserInfo({ 
                        //     success(res) {
                        //         User.setUserName(res.userInfo.nickName)
                        //         User.setUserLinkHead(res.userInfo.avatarUrl)
                        //         // EventMgr.emitEvent_custom(ryw_Event.refreshHead)
                        //         // RankData.getInstance().getRankDataLink()
                        //         console.error(`getUserInfo 调用成功`+res.userInfo.avatarUrl​);
                        //         console.error(`getUserInfo 调用成功`+res.userInfo.nickName​);

                        //     },
                        //     fail(res) {
                        //         console.error(`getUserInfo 调用失败`);
                        //     },
                        // });
                    },
                    fail: () => {
                        console.log("登陆失败1");
                        onFail();
                    },
                })
            TTAPI.initRecord_custom();
        }
    }

    public static ttLogin_getUserProfile() {
        if(AppPlatform.is_TT_GAME_custom()){
            window["tt"].openSetting({
                success(res) {
                    console.log(res);

                },
                fail(res) {
                    console.log(`openSetting 调用失败`);
                },
            });
        }
  
  
    }

    //-------------------------激励视频---------------------------------
    protected static _isRegRewardedVideoAdEvent_custom = false;
    protected static _onRewardedVideoAdFailed_custom: Function = null;
    protected static _onRewardedVideoAdClose_custom: Function = null;

    protected static TTAPI_ID_number = 0;

    protected static onRewardedVideoAdLoad_custom() {
        console.log('激励视频 广告加载完成')
    }
    protected static onRewardedVideoAdError_custom(err) {
        Common5.isVideoAdStopTime = false
        console.log('激励视频 广告加载失败' + err)
        if (TTAPI._onRewardedVideoAdFailed_custom) {
            TTAPI._onRewardedVideoAdFailed_custom();

        }
    }
    protected static onRewardedVideoAdClose_custom(res) {

        Common5.isVideoAdStopTime = false
        if ((res && res.isEnded) || res == null) {
            console.log('激励视频 已完整观看')
           
            if (TTAPI._onRewardedVideoAdClose_custom) {
                TTAPI._onRewardedVideoAdClose_custom(true)
                UserManager.lastTime = UserManager.onlineTime //重置为最新的时间
            }
            cc.audioEngine.resumeAll();
            ZYSDK.ZYSDK.reportVideo(true)
        }
        else {
            console.log('激励视频 未完整观看')

            if (TTAPI._onRewardedVideoAdClose_custom) {
                TTAPI._onRewardedVideoAdClose_custom(false)
       
            }
            cc.audioEngine.resumeAll();
            ZYSDK.ZYSDK.reportVideo(false)
        }
    }
    protected static regRewardedVideoAdEvent_custom(rewardedVideoAd) {

        rewardedVideoAd.onLoad(TTAPI.onRewardedVideoAdLoad_custom)
        rewardedVideoAd.onError(TTAPI.onRewardedVideoAdError_custom)
        rewardedVideoAd.onClose(TTAPI.onRewardedVideoAdClose_custom)
        TTAPI._isRegRewardedVideoAdEvent_custom = true;
    }
    public static showRewardedVideoAd_custom(onAdClose: Function, onFailed: Function) {
        Common5.isVideoAdStopTime = true
        if (AppPlatform.is_TT_GAME_custom()) {
            
            if (window["tt"].createRewardedVideoAd) {
                
                TTAPI._onRewardedVideoAdClose_custom = onAdClose;
                TTAPI._onRewardedVideoAdFailed_custom = onFailed;
                if (this.TTAPI_ID_number == AppConfig.tt_adUnitIdArr_custom.length) {
                    this.TTAPI_ID_number = 0;
                }
                let videoid = AppConfig.tt_adUnitIdArr_custom[this.TTAPI_ID_number]; //AppConfig.tt_adUnitIdArr_custom[Math.floor(Math.random() * AppConfig.tt_adUnitIdArr_custom.length)];
                this.TTAPI_ID_number++;
                var rewardedVideoAd = window["tt"].createRewardedVideoAd(
                    {
                        adUnitId: videoid,
                    }
                );

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

                rewardedVideoAd.load().then(() => {
                    var promise = rewardedVideoAd.show();
                    promise.then(() => console.log('激励视频 广告显示成功'));
                    promise.catch((err) => {
                            rewardedVideoAd.load()
                            .then(() => rewardedVideoAd.show())
                            .catch(err => {
                                Common5.isVideoAdStopTime = false
                                if (AppPlatform.is_TT_GAME_custom()) {
                                    let errStr = "激励视频 广告显示失败" + err.errCode
                                    console.log('errStr', errStr);
                                    window["tt"].reportAnalytics('getVideoFail', {
                                        failReason: errStr,
                                    });
                                }
                                if (onFailed) {
    
                                    if (this.TTAPI_ID_number == AppConfig.tt_adUnitIdArr_custom.length) {
                                        this.TTAPI_ID_number = 0;
                                        onFailed();
                                    }else{
                                      
                                        this.showRewardedVideoAd_custom(onAdClose,onFailed);
                                    }
                                }

                            })
                    });
                }).catch(err => {
                    Common5.isVideoAdStopTime = false
                    let errStr = "激励视频 广告加载失败" + err.errCode
                    console.log('errStr', errStr);
                    if (AppPlatform.is_TT_GAME_custom()) {
                        window["tt"].reportAnalytics('getVideoFail', {
                            failReason: errStr,
                        });
                    }
                    if (onFailed) {
                        // onFailed();
                        if (this.TTAPI_ID_number == AppConfig.tt_adUnitIdArr_custom.length) {
                            this.TTAPI_ID_number = 0;
                            onFailed();
                        }else{
                            
                            this.showRewardedVideoAd_custom(onAdClose,onFailed);
                        }
                    }
                })
            } else {
                Common5.isVideoAdStopTime = false
                window["tt"].showModal({
                    title: "提示",
                    content:
                        "当前客户端版本过低,无法使用该功能,请升级客户端或关闭后重启更新。",
                });
            }


        }
        else {
            Common5.isVideoAdStopTime = false
            onAdClose(true);
         
        }
    }
    //-------------------录屏-------------------------------------------
    /**
     * 配置录屏
     */

    public static initRecord_custom() {
        let tt = window["tt"];
        if(tt){
            TTAPI.recordRes_custom = tt.getGameRecorderManager();
        }
        TTAPI.record_custom = window["tt"].getGameRecorderManager();
        if (TTAPI.record_custom != null) {
            TTAPI.record_custom.onStart(res => {
                console.log("录屏开始");
                TTAPI.recordRes_custom = "";
            })

            TTAPI.record_custom.onStop(res => {
                console.log("录屏结束");
                EventMgr.emitEvent_custom(ryw_Event.recordFinish);
                TTAPI.recordRes_custom = res.videoPath;
            })
        }
    }

    public static getOpenID(){
        let onFail = ()=>{

        }

        let onSuccess = (response)=>{
            console.log(response, '数据+++=====')
            if(response.msg == 'OK'){
                User.setOtherplatformUserid(response.openid)
            }
        }
        
        if(this.loginCode != ""){
            let url = "https://report1.ioe-times.com/api/getopenid"
            let headersTab = {}; //头数据
            let xhr: XMLHttpRequest = new XMLHttpRequest();
            xhr.timeout = 15000;

            //请求过程发生意外的回调
            xhr.onerror = function (error) {
            
                onFail();
            }
            //超时
            xhr.ontimeout = function (error) {
        
                onFail();
            }

            xhr.onreadystatechange = function () {
        
                let readyState = xhr.readyState;
                let status = xhr.status;

                if (readyState === 4) {
                    let tab = { code: 1 }
                    if (status >= 200 && status < 300) {
                        let responseText = xhr.responseText;
                        const response = JSON.parse(responseText);
                        console.log(response, 'getLoginInfo data+++++')
                        onSuccess(response);
                    } else {
                        let statusText = xhr.statusText;
                        console.log("接收内容:" + statusText)
                        onSuccess(null);
                    }
                }
            }

            xhr.open("POST", url, true);

            if (!headersTab["Content-Type"]) {
                headersTab["Content-Type"] = "application/json";
            }
            if (headersTab) {
                for (let key in headersTab) {
                    xhr.setRequestHeader(key, headersTab[key]);
                }
            }

            let params = {GameName:"wdztbj",Anonymous_code:"", "Code":this.loginCode};
            let sendMsg = JSON.stringify(params);
            xhr.send(sendMsg); 
        }
    }
    /**
     * 开始录屏
     */
    public static startRecord_custom(durationInput = 300) {
        if (!AppPlatform.is_TT_GAME_custom()) {
            return;
        }
        this.startDate = new Date().getTime();
        console.log("startRecord_custom"+this.startDate);
        TTAPI.record_custom.start({
            duration:durationInput
        })
    }

    /**
    * 停止录屏
    */
    public static stopRecord_custom() {
        if (!AppPlatform.is_TT_GAME_custom()) {
            return;
        }
        this.stopDate = new Date().getTime();
        console.log("stopRecord_custom"+this.stopDate);
        TTAPI.record_custom.stop();
    }

    //----------------------------------------------------------------------

    //---------------------分享录屏----------------------------------------
    public static shareRecord_custom(callback: Function = null, Failcallback: Function = null) {

        if (!AppPlatform.is_TT_GAME_custom()) {
            return;
        }
        if ((this.stopDate - this.startDate) < 5000){
            Common5.showTips_custom("录屏时间小于5秒分享失败,请稍后再试!");
            return;
        }
        if (TTAPI.recordRes_custom != "") {
            window["tt"].shareAppMessage({
                channel: "video",
                extra: {
                    videoPath: TTAPI.recordRes_custom, // 可替换成录屏得到的视频地址
                    videoTopics: [AppConfig.GameName_custom]
                },
                success() {
                    if (callback != null) {
                        callback();
                    }
                    console.log("分享视频成功");
                },
                fail(e) {
                    console.log("分享视频失败", e);
                    if (Failcallback != null) {
                        Failcallback();
                    }
                }
            });
        } else {
            if (Failcallback != null) {
                Failcallback();
            }
            console.log("分享视频为空");
        }
    }
    //----------------------------------------------------------------------


    //----------------------------------------------------------------------

    //---------------------分享好友----------------------------------------
    public static share_custom(complate: Function = null) {

        if (!AppPlatform.is_TT_GAME_custom()) {
            return;
        }
        window["tt"].shareAppMessage({
            templateId: AppConfig.tt_templateId_custom,
            success() {
                if (complate != null) {
                    complate();
                }
            },
            fail() {
                console.log("分享失败");
            }
        });

    }

    //------------------------------------------------------------------

    //-------------------------banner-------------------------------------------

    public static showBanner_custom(): any {
        if (!AppPlatform.is_TT_GAME_custom() || AppConfig.tt_bannerAdUnitId_custom.length <= 0) {
            return;
        }
        if (!TTAPI._banner_custom) {
            const { windowWidth, windowHeight } = window["tt"].getSystemInfoSync();
            var targetBannerAdWidth = 150;
            // 创建一个居于屏幕底部正中的广告
            TTAPI._banner_custom = window["tt"].createBannerAd({
                adUnitId: AppConfig.tt_bannerAdUnitId_custom,
                adIntervals: 30,
                style: {
                    width: targetBannerAdWidth,
                    top: windowHeight - (targetBannerAdWidth / 16) * 9, // 根据系统约定尺寸计算出广告高度
                }
            });
            // 也可以手动修改属性以调整广告尺寸
            TTAPI._banner_custom.style.left = (windowWidth - targetBannerAdWidth) / 2;
            TTAPI._banner_custom.onResize(size => {
                console.log(size.width, size.height);
                TTAPI._banner_custom.style.top = windowHeight - size.height;
                TTAPI._banner_custom.style.left = (windowWidth - size.width) / 2;
            });
        }
        TTAPI._banner_custom.show();
    }

    public static hideBanner_custom() {
        if (null != TTAPI._banner_custom) {
            TTAPI._banner_custom.hide();
        }
    }

    public static showMoreGamesModal_custom(onSuccess: Function, onFail: Function) {
        const systemInfo = window["tt"].getSystemInfoSync();
        // iOS 不支持,建议先检测再使用
        if (systemInfo.platform !== "ios") {
            // 打开互跳弹窗
            window["tt"].showMoreGamesModal({
                appLaunchOptions: [
                    {
                        appId: AppConfig.AppID_custom,
                        query: "foo=bar&baz=qux",
                        extraData: {}
                    }
                    // {...}
                ],
                success(res) {
                    console.log("success", res.errMsg);
                    if (onSuccess) {
                        onSuccess();
                    }
                },
                fail(res) {
                    console.log("fail", res.errMsg);
                    if (onFail) {
                        onFail();
                    }
                }
            });
        }
        else {
            if (onFail) {
                onFail();
            }
        }
    }

    // ------------------------------------- 插屏广告 -------------------------------------
    public static showInterstitialAd(onAdClose?: Function, onFail?: Function) {
        if (!AppPlatform.is_TT_GAME_custom()) {
            return;
        }
        console.log("插屏插屏create....................")
        let interstitialAd: any = window["tt"].createInterstitialAd({
            adUnitId: AppConfig.tt_InsAdUnitId_custom,
        });

        interstitialAd.load().then(() => {
            console.log("插屏广告加载成功!");
            interstitialAd.show().then(() => {
                console.log("插屏广告展示成功!");
            }).catch((err) => {
                console.log("插屏广告显示失败:", JSON.stringify(err));
            });
        }).catch((err) => {
            console.log("插屏广告加载失败:", JSON.stringify(err));
        });

        interstitialAd.onClose(() => {
            console.log('插屏广告 关闭');
            interstitialAd.destroy();
            if (onAdClose) {
                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 TTAPI
     */
    public static getLaunchOptionsSync_custom() {
        // let result = { scene: 0, query: null, shareTicket: "", referrerInfo: null };
        if (AppPlatform.is_TT_GAME_custom()) {
            let obj = window["tt"].getLaunchOptionsSync();
            console.log("obj ", obj);
            console.log("场景值 " + obj.scene);
            let str = JSON.stringify(obj.query);
            console.log("Query参数 " + str);
            let key = obj.query["key"];
            console.log("Query参数:key " + key);
            return obj;
        }
        let obj = { scene: 1001, query: "" }
        return obj;
    }


    //关注抖音号
    public static followTTCount() {
        if (AppPlatform.is_TT_GAME_custom()) {
            window["tt"].openAwemeUserProfile({
                success: (res) => {
                    console.log(res);
                },
            });
        }
    }


    //添加到桌面
    public static addToZM(successCall) {
        if (AppPlatform.is_TT_GAME_custom()) {
            window["tt"].addShortcut({
                success: function (res) {
                    console.log("添加成功");
                    successCall()
                },
                fail: function (res) {
                    console.log("添加失败");
                }
            })
        }

    }

    public static onShow(fu){
        // window["tt"].onShow((res)=>{
        //     fu();
        // })
    }

    


    //创建游戏推荐组件实例。
    public static createGridGamePanel(){
        if (AppPlatform.is_TT_GAME_custom()) {
       
            console.log('createGridGamePanel222226')



            try {
                // 四宫格可设置大小 设置位置无实际作用
                const fourGridGamePanel = window["tt"].createGridGamePanel({
                    gridCount: "four",
                    size: "large",
                    query: {
                        "tte26594d87d569da002": "age=1&name=快乐洗刷刷",
                        "tt0a637cde955f697002": "age=2&name=我的侦探笔记",
                        "tt32d2446faded9fb302": "age=3&name=收纳梦之岛",
                        "ttaf9cd92130a0ced102": "age=4&name=我的修仙日记",
                    },
                  });

                  this.fourGridGamePanel = fourGridGamePanel
            } catch (error) {
                console.error("创建游戏推荐组件失败", error);
            }
        }
    
    }


    public static showFourGridGamePanel(){
        if ( this.fourGridGamePanel) {
            
            this.fourGridGamePanel.show()
              .then(() => {
                console.error("展示游戏推荐组件成功");
              })
              .catch((err) => {
                console.error("展示游戏推荐组件失败", err);
              });

            //   setTimeout(() => {
            //     this.fourGridGamePanel.hide();
            //     console.log("隐藏游戏推荐组件");
            //   }, 5000);

          }
    }



    //检测是否有侧边栏
    public static checkScene(onSuccess: Function, onFail: Function){
        if (AppPlatform.is_TT_GAME_custom()) {
            if(window["tt"].checkScene){
                window["tt"].checkScene({
                    scene: "sidebar",
                    success: (res) => {
                        console.log("check scene success: ", res.isExist);
                        //成功回调逻辑
                        onSuccess && onSuccess()
                    },
                    fail: (res) => {
                        console.log("check scene fail:", res);
                        //失败回调逻辑
                        onFail && onFail()
                    }
                })
            }
          
        }
    }
    //加入侧边栏
    public static navigateToScene(onSuccess: Function, onFail: Function){
        if (AppPlatform.is_TT_GAME_custom()) {
            window["tt"].navigateToScene({
                scene: "sidebar",
                success: (res) => {
                    console.log("navigate to scene success");
                    // 跳转成功回调逻辑
                    onSuccess && onSuccess()
                },
                fail: (res) => {
                    console.log("navigate to scene fail: ", res);
                    // 跳转失败回调逻辑
                    onFail && onFail()
                },
            });
        }
    }

    public static dingyueXiaoxi(){
        const tmplIds = ["MSG1826255137157390297642598729999"];
        if(window['tt'] && window['tt'].requestSubscribeMessage){
            window['tt'].requestSubscribeMessage({
                tmplIds: tmplIds,
                complete: (res) => {
                    console.log('订阅接口完成')
                },
                success: (res) => {
                    console.log(res)
                    console.log("订阅接口完成成功1");
                    ZYSDK.ZYSDK.reportUserAction('订阅消息-成功');
                },
                fail: () => {
                    console.log("订阅接口完成失败1");
                  
                },

                });
        }
 
    }
    
}