import Userdata from "../Userdata";
import DataTool from "./DataTool";

export class SdkToutiao {
    public static lastRecordPath = null;
    private static interAd = null;
    private static isInterAdLoaded = false;
    private static videoAd = null;
    private static videoSuccessFunc: Function = null;
    private static videoFailedFunc: Function = null;
    private static lastShowAdsTime = 0;
    private static AdsCDTime = 32;//秒数
    private static titles = ["快来消灭各种动物, 球球无敌?!", "上千个球球乱弹, 超解压的!!!", "只要瞄得准, 不怕过不了的关卡!"];
    private static picUrl = "https://common-1257117844.cos.ap-shanghai.myqcloud.com/toutiao/bricksbreaker/banner.jpg";

    private static recordStartTime = 0;
    private static stoppedRecord = false;
    /**
     * @returns 是否支持显示更多游戏按钮
     */
    static isSupportMoreGames(): boolean {
        const systemInfo = window.tt.getSystemInfoSync();
        // iOS 不支持，建议先检测再使用
        if (systemInfo.platform !== "ios" && window.tt.showMoreGamesModal) {
            return true;
        } else {
            return false;
        }
    }

    static listenToutiaoEvent() {
        tt.onHide(() => {
            cc.log("小游戏隐藏");
            if (Userdata.anonymous_openid && Userdata.Stars > 0) {//同步数据到服务器
                DataTool.setAsync(Userdata.anonymous_openid, Userdata.getAllToutiaoData(), (res)=>{
                    if (res){
                        tt.showToast({
                            title: "进度保存成功!",
                            duration: 2000
                          });
                    }
                });
            }
        });
    }

    static login(cb: Function) {
        tt.login({
            force: false,
            success(res) {
                cc.log(`login 调用成功 code = ${res.code} , anonymousCode =  ${res.anonymousCode}`);
                cb && cb(res);
            },
            fail(res) {
                cc.log(`login 调用失败`);
                cb && cb();
            },
            complete() {
                cc.log(`login 调用完成`);
                // cb && cb();
            }
        });
    }

    static checkLogin(cb) {
        tt.checkSession({
            success() {
                cc.log(`session 未过期`);
                cb && cb();
            },
            fail() {
                cc.log(`session 已过期，需要重新登录`);
                SdkToutiao.login(cb);
            },
            complete() {
                cc.log(`session 调用完成`);
                // cb && cb();
            }
        });
    }

    static addShortcut() {
        tt.addShortcut({
            success: function (res) {

            },
            fail: function (res) {

            }
        })
    }

    static showFavoriteGuide() {
        tt.showFavoriteGuide({
            type: "bar",
            content: "一键添加到我的小程序",
            position: "bottom",
            success(res) {
                //   cc.log("引导组件展示成功");
            },
            fail(res) {
                //   cc.log("引导组件展示失败");
            },
        });
    }

    /**
     * 跳转更多游戏
     */
    static showMoreGames() {
        if (!SdkToutiao.isSupportMoreGames()) {
            return;
        }

        /**
         * "ttf520839d6a1b0eae",
        "ttb8b1ce0c278ae8cc",
        "tt8b15fda8143f6af7",
        "tt89cdff7016f6dae7",
        "tt99e1ef5c06dacafa02",
        "tt898fff3216b4da85",
        "tt38a64e1ba79d6b23",
        "ttc6c7b07a59fc9462",
         */
        // 打开小游戏盒子
        window.tt.showMoreGamesModal({
            appLaunchOptions: [
                {
                    appId: "ttf520839d6a1b0eae",//蛇与方块
                    query: "",
                    extraData: {},
                },
                {
                    appId: "tt8b15fda8143f6af7",//舞动球球
                    query: "",
                    extraData: {},
                },
                {
                    appId: "ttb8b1ce0c278ae8cc",
                    query: "",
                    extraData: {},
                },
                {
                    appId: "tt89cdff7016f6dae7",
                    query: "",
                    extraData: {},
                },
                {
                    appId: "tt99e1ef5c06dacafa02",
                    query: "",
                    extraData: {},
                },
                {
                    appId: "tt898fff3216b4da85",
                    query: "",
                    extraData: {},
                },
                {
                    appId: "tt38a64e1ba79d6b23",
                    query: "",
                    extraData: {},
                },
                {
                    appId: "ttc6c7b07a59fc9462",
                    query: "",
                    extraData: {},
                }
            ],
            success(res) {
                cc.log("success", res.errMsg);
            },
            fail(res) {
                cc.log("fail", res.errMsg);
            },
        });
    }

    /**
     * 开始发起录屏
     * @param cb (isStart, msg)
     * @returns 
     */
    static startRecord(cb?: Function) {
        if (typeof window.tt.getGameRecorderManager === 'undefined') {
            cb && cb(false);
            cc.log('record startRecord false 2', window.tt.getGameRecorderManager);
            return;
        }
        const recorder = window.tt.getGameRecorderManager();

        SdkToutiao.stoppedRecord = false;
        SdkToutiao.recordStartTime = Date.now();
        recorder.onStart(res => {
            cc.log('录屏开始');
            // do somethine;
            cb && cb(true, res);
        });

        SdkToutiao.lastRecordPath = null;
        recorder.onStop(res => {
            cc.log('record start onstop', res.videoPath);
            if (Date.now() - SdkToutiao.recordStartTime > 1000 * 15) {
                SdkToutiao.lastRecordPath = res.videoPath;
            }
            SdkToutiao.stoppedRecord = true;
            cb && cb(false, res.videoPath);
        })

        recorder.onError(res => {
            SdkToutiao.lastRecordPath = null;
        })

        recorder.start({
            duration: 300,
        });
        cc.log('record startRecord true');
    }

    static stopRecord(cb?: Function) {
        let called = false;
        SdkToutiao.stopRecord1(() => {
            if (!called) {
                called = true;
                cb && cb();
            }
        })
    }

    /**
     * 停止录屏
     * @param cb 
     * @returns 返回录屏地址
     */
    static stopRecord1(cb?: Function) {
        if (typeof window.tt.getGameRecorderManager === 'undefined') {
            cb && cb(false);
            cc.log('record stopRecord false 2', window.tt.getGameRecorderManager);
            return;
        }

        if (SdkToutiao.lastRecordPath) {
            cb && cb(SdkToutiao.lastRecordPath);
            return;
        }

        if (SdkToutiao.stoppedRecord) {
            cb && cb(false);
            return;
        }

        const recorder = window.tt.getGameRecorderManager();
        recorder.onStop(res => {
            if (Date.now() - SdkToutiao.recordStartTime > 1000 * 15) {
                SdkToutiao.lastRecordPath = res.videoPath;
            }
            SdkToutiao.stoppedRecord = true;
            cb && cb(res.videoPath);
        })

        recorder.stop();
        SdkToutiao.stoppedRecord = true;
        cc.log('record stopRecord true');

        setTimeout(() => {//保证会回调
            cb && cb(false);
        }, 5000);
    }

    /**
     * 分享录屏
     * @param videoPath 
     * @param cb 返回分享是否成功
     * @returns 
     */
    private static _shareRecord(videoPath, desc, cb?: Function) {
        if (typeof window.tt.getGameRecorderManager === 'undefined') {
            cc.log('record shareRecord false 2', window.tt.getGameRecorderManager);
            return;
        }

        if (!videoPath) {
            return;
        }

        cc.log('record shareRecord => ', videoPath);
        window.tt.shareAppMessage({
            channel: 'video',
            title: '小球乱弹',
            desc: desc,
            imageUrl: '',
            templateId: '', // 替换成通过审核的分享ID
            query: '',
            extra: {
                videoPath: videoPath, // 可替换成录屏得到的视频地址
                videoTopics: ['小球乱弹'],
                createChallenge: true,
            },
            success() {
                cc.log('分享视频成功');
                cb && cb(true);
            },
            fail(e) {
                cc.log('分享视频失败');
                cb && cb(false);
            }
        })
    }

    /**
     * 暂停录屏
     * @param cb 
     * @returns 
     */
    static pauseRecord(cb?: Function) {
        if (typeof window.tt.getGameRecorderManager === 'undefined') {
            cb && cb(false);
            cc.log('record pauseRecord false 2', window.tt.getGameRecorderManager);
            return;
        }

        const recorder = window.tt.getGameRecorderManager();
        recorder.onPause(res => {
            cc.log('record onPause', res);
            // do somethine;
            cb && cb(res);
        })

        recorder.pause();
        cc.log('record pauseRecord true');
    }

    /**
     * 恢复录屏
     * @param cb 
     * @returns 
     */
    static resumeRecord(cb?: Function) {
        if (typeof window.tt.getGameRecorderManager === 'undefined') {
            cb && cb(false);
            cc.log('record resumeRecord false 2', window.tt.getGameRecorderManager);
            return;
        }

        const recorder = window.tt.getGameRecorderManager();
        recorder.onResume(res => {
            cc.log('record onResume', res);
            // do somethine;
            cb && cb(res);
        })

        recorder.resume();
        cc.log('record resumeRecord true');
    }

    static getTitle(_title?: string): string {
        let title = _title;
        if (!title) {
            title = this.titles[Math.floor(Math.random() * this.titles.length)];
        }
        return title;
    }

    /**
     * 主界面分享
     * @param _title 
     */
    static share(_title?: string) {
        window.tt.shareAppMessage({
            title: this.getTitle(_title),
            imageUrl: this.picUrl
        });
    }

    static showFollow() {
        window.tt.getSystemInfo({
            success(res) {
                if (res.appName == 'Douyin') {
                    if (window.tt.openAwemeUserProfile) {
                        window.tt.openAwemeUserProfile();
                    } else {
                        window.tt.showModal({
                            title: "提示",
                            content:
                                "当前客户端版本过低，无法使用该功能，请升级客户端或关闭后重启更新。",
                        });
                    }
                } else {
                    window.tt.showModal({
                        title: "提示",
                        content:
                            "需要在抖音中才能关注, 请使用抖音搜索游戏并关注, 谢谢支持!",
                    });
                }
            },
            fail(res) {
                cc.log(`getSystemInfo 调用失败`);
            },
        });

    }

    static openShareMenu() {
        window.tt.showShareMenu({ withShareTicket: true });//设置分享按钮，方便获取群id展示群排行榜
        window.tt.onShareAppMessage(() => {
            return {
                title: this.getTitle(),
                imageUrl: this.picUrl
            }
        });
    }

    static shareRecord(desc?: string, cb?: Function) {
        if (this.lastRecordPath) {
            this._shareRecord(this.lastRecordPath, this.getTitle(desc), cb);
        } else {
            this.share(desc);
        }
    }

    /**
     * 加载新的插页广告
     */
    static loadNewInterAd() {
        this.createInterAd();
        return;
        if (typeof window.tt.createInterstitialAd != 'undefined') {
            if (this.interAd) {
                this.interAd.destroy();
                this.interAd = null;
            }

            // 插屏广告支持今日头条和抖音客户端
            this.interAd = window.tt.createInterstitialAd({
                adUnitId: "7srb516442h3hgbee3",
            });

            this.interAd.onLoad(() => {
                this.isInterAdLoaded = true;
            });

            this.interAd.onClose(() => {
                this.isInterAdLoaded = false;
                this.loadNewInterAd();
            });

            this.interAd.load();
        }
    }

    static createInterAd() {
        if (this.interAd == null) {
            this.interAd = window.tt.createInterstitialAd({
                adUnitId: "7srb516442h3hgbee3",
            });

            this.interAd.onLoad(() => {
                cc.log("interAd loaded ");

                this.interAd.show().then(() => {
                    cc.log('on inter showed');

                }).catch((err) => {
                    cc.log("on inter show error ", err);
                });
                this.lastShowAdsTime = cc.sys.now() / 1000;
            });


            this.interAd.onError((obj) => {
                cc.log("interAd onError ", obj);

            });
        }
    }
    /**
     * 显示插页广告
     */
    static showInterAd() {
        if (cc.sys.now() / 1000 - this.lastShowAdsTime <= this.AdsCDTime) {
            cc.log('on inter cd', cc.sys.now() / 1000 - this.lastShowAdsTime);
            return;//cd
        }

        // return;//去掉banner 抖音不能兼容banner
        if (typeof window.tt.createInterstitialAd != 'undefined') {
            this.createInterAd();

            this.interAd.load();
        }
    }

    /**
     * 加载视频广告
     */
    static loadRewardVideoAd(loadSuccessFunc?: Function, loadFailedFunc?: Function) {
        if (this.videoAd == null) {
            this.videoAd = tt.createRewardedVideoAd({
                adUnitId: "31alcll8m1n3157bc2"
            });
        }

        this.videoAd.load()
            .then(() => {
                if (loadSuccessFunc) {
                    loadSuccessFunc();
                }
            })
            .catch(err => {
                if (loadFailedFunc) {
                    loadFailedFunc();
                }
            })

        this.videoAd.onClose(res => {
            // 用户点击了【关闭广告】按钮
            // 小于 2.1.0 的基础库版本，res 是一个 undefined
            if (res && res.isEnded || res === undefined) {
                // 正常播放结束，可以下发游戏奖励
                if (this.videoSuccessFunc) {
                    this.videoSuccessFunc();
                }
            }
            else {
                // 播放中途退出，不下发游戏奖励
                cc.log("视频中途退出");
                if (this.videoFailedFunc) {
                    this.videoFailedFunc();
                }
            }
        });
    }

    /**
     * 展示视频广告
     */
    static showRewardVideoAd(videoSuccessShowFunc: Function, videoFailedShowFunc: Function) {
        this.videoSuccessFunc = videoSuccessShowFunc;
        this.videoFailedFunc = videoFailedShowFunc;

        if (this.videoAd) {
            this.videoAd.show()
                .then(() => {
                    cc.log('广告显示成功')
                })
                .catch(err => {
                    cc.log('show video try 1');
                    //再试一次
                    this.loadRewardVideoAd(() => {
                        this.videoAd.show();
                    }, () => {
                        videoFailedShowFunc && videoFailedShowFunc();
                    })
                });
        } else {
            this.loadRewardVideoAd(() => {
                this.videoAd.show();
            }, () => {
                videoFailedShowFunc && videoFailedShowFunc();
            })
        }

    }
}