import { Vec2, _decorator } from 'cc';
import { constants } from '../data/constants';
import { eventEmitter } from '../manager/eventEmitter';

const TT_CONFIG = {
    AD_ID: {
        /** banner广告 */
        banner: '30a3ll993k15aakgla',
        /** 视频广告 */
        video: 'o1h5n7r8fnp31df3g1',
        /** 插屏广告 */
        interstitial: '4687fak66i8aklc5hd'
    }
}

var globalTT:any;
const delayTime: number = 1900;
class PlatformTT {
    private _onHideTime: number = Infinity;
    private _shareTimes: number = 0;

    private _rewardVideo: wx.RewardedVideoAd;
    private _bannerAd: wx.BannerAd;
    private _interstitialAd: any;

    private _shareSuccessHandler: Function = null;
    private _videoSuccessHandler: Function = null;

    private _showInterstitialAdTime: number = null;
    private _shareModalIsActive: boolean = false;
    private _shareStr: string = "东北F4来到美国西部拓荒时代，保卫城镇，完成自我救赎。";

    public initialize(): void {
        //@ts-ignore
        globalTT = tt;
        console.log("初始化抖音框架");
        //监听游戏生命周期回调
        globalTT.onShow(function (res) {
            //判断是否是从侧边栏复访
            if (res.scene == 1104) {
                console.log('从侧边栏复访');
            }
        });

        globalTT.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
            success: () => { },
            fail: () => { },
            complete: () => { }
        });

        //发送给朋友
        globalTT.onShareAppMessage(function(){
            globalTT.shareAppMessage({
                title: this._shareStr,
                query: 'shareMsg='+'a=1',
            });
        }.bind(this));
        
        globalTT.onShow((res: {
            scene: string;
            query: any;
            shareTicket: string;
            referrerInfo: wx.ReferrerInfo;
        }) => {
            if (this._shareSuccessHandler == null) return;
            if (this._shareModalIsActive) return;
            if (Date.now() - this._onHideTime >= delayTime) {
                if (this._shareSuccessHandler) this._shareSuccessHandler(true);
            } else {
                globalTT.showModal({
                    title: '分享提示',
                    content: '成功分享到群即可获得奖励',
                    success: (res) => {
                        if (res.confirm) {
                            this.shareShowReward(this._shareSuccessHandler(false));
                        } else if (res.cancel) {
                            this._shareSuccessHandler = null;
                        }
                        this._shareModalIsActive = false;
                    }
                });
                this._shareModalIsActive = true;
            }
            this._onHideTime = Infinity;
        });

        //this.__createBannerAd();
        this.__createVideoAd();
        //this.__createInterstitialAd();
    }

    //检查当前宿主是否支持跳转到侧边栏
    public isCheckScene(handler: Function = null){
        globalTT.checkScene({
            scene: 'sidebar',
            success(res) {
                if(handler){
                    if(res.isExist) {//支持
                        if(true){
                            handler(false);
                        }else{
                            handler(true);
                        }
                    }else{//不支持
                        handler(false)
                    }
                }
            },
            fail(err) {
                console.error('检查侧边栏支持失败', err);
                // 可以选择默认操作，例如不展示奖励入口
                if(handler){handler(false)}
            }
        });
    }

    //添加测边栏功能
    public openSideBar(handler: Function = null): void {
        globalTT.navigateToScene({
            scene: 'sidebar',
            success() {
                handler?.('成功打开侧边栏',true);
            },
            fail(err) {
                handler?.('打开侧边栏失败',false);
            }
        });
    }

    /**
     * 是否支持添加桌面
     * @returns 
     */
    public isSupportDesk(){
        return true;
    }

    //添加到桌面
    public addDesk(handler: Function = null): void {
        // 调用创建桌面快捷方式 API
        globalTT.addShortcut({
            success() {
                globalTT.showToast({title: '创建桌面快捷方式成功'});
            },
            fail(err) {
                globalTT.showToast({title: '创建桌面快捷方式失败', err});
            }
        });
    }

    public showToast(param: { title: string, icon?: 'success' | 'loading' | 'none', image?: string, duration?: number, mask?: boolean, success?: (res?: any) => void, fail?: (res?: any) => void, complete?: (res?: any) => void }): void {
        let finalParam = {
            title: '',
            icon: 'none',
            duration: 2000,
        } as any;
        Object.assign(finalParam, param);
        globalTT.showToast(finalParam);
    }

    public shareAppMessage(param: { title?: string, imageUrl?: string, query?: string, imageUrlId?: string } = {}): void {
        globalTT.shareAppMessage(param);
    }

    public vibrateShort(param: any = {}): void {
        globalTT.vibrateShort(param);
    }

    public vibrateLong(param: any = {}): void {
        globalTT.vibrateLong(param);
    }

    public showCustomAd(close: Function): void {
        
    }

    public hideCustomAd(): void {

    }

    public showSigleCustomAd(): void {
    }

    public hideSigleCustomAd(): void {
    }
    
    //分享
    public shareShowReward(handler: Function = null): void {
        if(handler){
            this._shareSuccessHandler = handler;
        }
        this._onHideTime = Date.now();
        this.shareAppMessage({
            title: this._shareStr, 
            query: 'shareMsg='+'a=1',
        });
    }

    public showRewardVideo(handler: Function = null): void {
        //console.log('当日视频次数： ', ArchiveSystem.localData.videoRewardTimesToday);
        /*if (ArchiveSystem.localData.videoRewardTimesToday % 2 === 1) {
            cc.log(ArchiveSystem.localData.videoRewardTimesToday, '转为分享');
            this.__turnVideoToShare(handler);
            return;
        }*/
        if (!this._rewardVideo) {
            this.__turnVideoToShare(handler);
            return;
        }
        this._videoSuccessHandler = handler;
        this._rewardVideo
            .show()
            .then(() => {
                console.log("视频播放成功");
            })
            .catch(err => {
                this._rewardVideo.load()
                    .then(() => {
                        this._rewardVideo
                            .show()
                            .then(() => {
                                console.log("视频重新加载，播放成功");
                            });
                    })
                    .catch(err2 => {
                        this._videoSuccessHandler?.(false);
                        this.shareShowReward(handler);
                        this._videoSuccessHandler = null;
                    });
            });
    }

   
    public showBannerAd(): void {
        if (!this._bannerAd) return;
        const { screenWidth, screenHeight } = globalTT.getSystemInfoSync();
        this._bannerAd.show()
            .then(() => {
               this._bannerAd.style.left = (screenWidth - this._bannerAd.style.realWidth) / 2;
                this._bannerAd.style.top = screenHeight - this._bannerAd.style.realHeight;
            }).catch((e: any) => {
                console.log('banner广告显示出错', e);
            });
    }

    public hideBannerAd(recreate: boolean = false): void {
        if (!this._bannerAd) return;
        this._bannerAd.hide();
        if (recreate) {
            this.refreshBannerAd();
        }
    }

    public refreshBannerAd(): void {
        if (!this._bannerAd) return;
        this._bannerAd.destroy();
        this.__createBannerAd();
    }

    public showInterstitialAd(force: boolean = false): void {
        if(force){
            if (!this._interstitialAd) return;
            this._interstitialAd.show();
        }else{
            if (!this._interstitialAd) return;
            let timeNow = Date.now();
            if (this._showInterstitialAdTime == null) {
                this._showInterstitialAdTime = timeNow;
                return;
            }
            if (timeNow - this._showInterstitialAdTime > 120 * 1000) {
                this._interstitialAd.show();
                this._showInterstitialAdTime = timeNow;
            }
        }
    }

    public exitGame(): void {
        wx.exitMiniProgram({});
    }

    private __createVideoAd(): void {
        if (!TT_CONFIG.AD_ID.video) return;
        this._rewardVideo = globalTT.createRewardedVideoAd({ adUnitId: TT_CONFIG.AD_ID.video });
        // 注册视频的onClose事件
        this._rewardVideo.onClose(res => {
            if (res && res.isEnded || res === undefined) {
                this._videoSuccessHandler?.(true);
            } else {
                this.showToast({
                    title: "完整观看视频才有奖励哦"
                });
                this._videoSuccessHandler?.(false);
            }
            this._videoSuccessHandler = null;
        });
        // 注册视频的onError事件
        this._rewardVideo.onError(res => {
            this._videoSuccessHandler?.(false);
            this.showToast({
                title: "暂时没有可观看的视频"
            });
            this.shareShowReward(this._videoSuccessHandler);
            this._videoSuccessHandler = null;
        });
    }

    private __createBannerAd(): void {
        if (!TT_CONFIG.AD_ID.banner) return;
        const { screenWidth, screenHeight } = globalTT.getSystemInfoSync();
        let w = screenWidth * 0.85;
        let left = (screenWidth-w)/2.0;
        this._bannerAd = globalTT.createBannerAd({
            adUnitId: TT_CONFIG.AD_ID.banner,
            adIntervals: 48,
            style: {
                left: left,
                top: screenHeight - 70, 
                width: w,
                height: 70 
            }
        });
        this._bannerAd.onError(err => {
            switch (err.errCode) {
                case 1001: {
                    break;
                }
                case 1004: {
                    break;
                }
            }
        });
        this._bannerAd.onResize(() => {});
    }

    private __createInterstitialAd(): void {
        if (!TT_CONFIG.AD_ID.interstitial) return;
        this._interstitialAd = globalTT.createInterstitialAd({ adUnitId: TT_CONFIG.AD_ID.interstitial });
    }

    private __turnVideoToShare(handler: Function): void {
        this.shareShowReward(handler);
        this._videoSuccessHandler = null;
    }
}

export default new PlatformTT();