import { _decorator, log, SpriteFrame, sys } from "cc";
import { PlayerData } from "./playerData";
import { StorageManager } from './storageManager';
import { gameManager } from "../gameManager";
import { config } from "../config";
//管理广告、分享、SDK相关内容的组件
export class SdkUtil {
    public static platform: string = 'cocos'; //平台
    public static imgAd: SpriteFrame = null!;
    public static imgShare: SpriteFrame = null!;
    public static isDebugMode: boolean = false;
    public static onlineInterval: number = -1;
    public static isEnableVibrate: boolean = true;
    public static isCheckOffline: boolean = false; //登录后会检查是否展示登录界面，而且只检查一次
    public static isWatchVideoAd: boolean = false;//是否正在播放广告
    public static isEnableMoving: boolean = false;//是否允许屏幕上下移动
    public static isEnableZoom: boolean = false;//是否允许屏幕缩放
    public static arrLockDiary = [];//未解锁日记
    public static vibrateInterval: number = 100;//两次震动之间的间隔,AppActivity里面的震动间隔也是100
    public static vibratePreTime: number = 0;//上次震动时间


    public static videoAd:any =null;

    public static tt_isSupportSidebar:boolean = false;   //抖音_是否支持侧边栏
    public static tt_isToEnterFromSidebar:boolean = false; //抖音_是否从侧边栏进入

    /**
       * 自定义事件统计
       *
       * @param {string} eventType
       * @param {object} objParams
       */
    public static customEventStatistics(eventType: string, objParams?: any) {
        eventType = eventType.toString();
        if (!objParams) {
            objParams = {};
        }

        // console.log({'eventType': eventType},{'objParams': objParams});

        if (this.platform === 'wx') {
            //@ts-ignore
            if (window['wx'] && window['wx']['aldSendEvent']) {
                //@ts-ignore
                window.wx['aldSendEvent'](eventType, objParams);
            }
        }

        //@ts-ignore
        if (this.platform === 'cocos' && window.cocosAnalytics && window.cocosAnalytics.isInited()) {
            console.log("###统计", eventType, objParams);
            //@ts-ignore
            window.cocosAnalytics.CACustomEvent.onStarted(eventType, objParams);
        }
    }

    /**
     * 调用震动
     */
    public static vibrateShort() {
        let isEnableVibrate = StorageManager.instance.getGlobalData("vibration") ?? true;

        if (isEnableVibrate) {
            let now = Date.now();

            if (now - this.vibratePreTime >= this.vibrateInterval) {
                if (sys.isNative) {
                    // jsb.reflection.callStaticMethod("com/cocos/game/AppActivity", "vibrator", "()V");
                //@ts-ignore
                } else if (window.wx) {
                //@ts-ignore
                    wx.vibrateShort({
                        success: (result: any) => {

                        },
                        fail: () => { },
                        complete: () => { }
                    });
                }

                this.vibratePreTime = now;
            }
        }
    }

    /**
     * 微信分享
     * 
     * @static
     * @param {string} title
     * @param {string} imageUrl
     * @returns
     * @memberof SdkUtil
     */
    public static shareGame(title: string, imageUrl: string) {
        //@ts-ignore
        if (!window.wx) {
            return;
        }

        //@ts-ignore
        wx.showShareMenu({
            withShareTicket: true,
            complete: () => {

            }
        });

        //@ts-ignore
        if (wx.aldOnShareAppMessage) {
            //@ts-ignore
            wx.aldOnShareAppMessage(function () {
                // 用户点击了“转发”按钮
                return {
                    title: title,
                    imageUrl: imageUrl,

                };
            });
        } else {
            //@ts-ignore
            wx.onShareAppMessage(function () {
                // 用户点击了“转发”按钮
                return {
                    title: title,
                    imageUrl: imageUrl,

                };
            });
        }
    }

    
    /**
     * 抖音激励视频
     * 
     * @static
     * @param {string} _adUnitId
     * @param {Function} call_back
     * @returns
     * @memberof SdkUtil
     */

    public static showVideoAd(_adUnitId: string, call_back) {
        if(sys.platform != sys.Platform.BYTEDANCE_MINI_GAME) {
            call_back({isEnded:true})
            return
        }
        if(gameManager.havNoAllAd) {
            call_back({isEnded:true})
            return
        }
        
        gameManager.showWaitView(100,"正在加载...");
        SdkUtil.videoAd = tt.createRewardedVideoAd({adUnitId: _adUnitId});
        SdkUtil.videoAd.onLoad(() => {
            SdkUtil.videoAd.show();
            console.log("广告加载完成");
        });
        SdkUtil.videoAd.onClose((res) => {
            call_back(res)
            SdkUtil.videoAd.destroy()
            gameManager.hideWaitView();
        });
        SdkUtil.videoAd.onError((res) => {
            let errorString = res.errCode + '-' + res.errMsg
            call_back({isEnded:false,errorString:errorString})
            SdkUtil.videoAd.destroy()
            gameManager.hideWaitView();
        });
        SdkUtil.videoAd.load()
    }

    /**
     * 抖音注册侧边栏
     * 
     * @static
     * @memberof SdkUtil
     */
    public static ttRegisterSidebar() {
        if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            tt.onShow((res) => {
                console.log('tt.onShow =', res)
                // console.log('res=',res)
                if(res.scene == '021036' || res.scene == '101036') {
                    SdkUtil.tt_isToEnterFromSidebar = true
                }
                if(res.scene.launch_from == 'homepage' && res.scene.location == 'sidebar_card') {
                    SdkUtil.tt_isToEnterFromSidebar = true
                }
            });
            
            tt.checkScene({
                scene: "sidebar",
                success: (res) => {
                    console.log("check scene success: ", res.isExist);
                    if(res.isExist != undefined || res.isExist != null) {
                        SdkUtil.tt_isSupportSidebar = res.isExist
                    }
                },
                fail: (res) => {
                    console.log("check scene fail:", res);
                }
            });

            let options = tt.getLaunchOptionsSync()
            console.log('getLaunchOptionsSync=', options)
            if(options.scene == '021036' || options.scene == '101036') {
                SdkUtil.tt_isToEnterFromSidebar = true
            }
        }
    }

    // 抖音检测是否显示奖励
    public static ttCheckSceneShowRewards():boolean {
        return SdkUtil.tt_isSupportSidebar
    }

    // 抖音检测是否从侧边栏进入
    public static ttCheckToEnterFromSidebar():boolean {
        return SdkUtil.tt_isToEnterFromSidebar
    }

    // 抖音导航到侧边栏场景
    public static ttNavToSidebarScene() {
        if(sys.platform == sys.Platform.BYTEDANCE_MINI_GAME) {
            tt.navigateToScene({
                scene: "sidebar",
                success: (res) => {
                    // console.log("navigate to scene success");
                },
                fail: (res) => {
                    // console.log("navigate to scene fail: ", res);
                },
            });
        }
    }
}
