import { Widget, _decorator, Node, Label, Vec3, tween, isValid, math, sys } from 'cc';
import { UIBase } from '../scriptBase/UIBase';
import { UI } from '../enum/UI';
import { GameMgr } from '../manager/GameMgr';
import { CoinItem } from '../uiItem/CoinItem';
import { CoinMgr } from '../manager/CoinMgr';
import { EventType } from '../enum/EventType';
import { EventMgr } from '../manager/EventMgr';
import { AudioMgr } from '../manager/AudioMgr';
import { SkillMgr } from '../manager/SkillMgr';
import { AdMgr } from '../manager/AdMgr';

import ATRewardedVideoSDK from "../AnyThinkAds/ATRewardedVideoTSSDK"
import AAJS2 from "../utils/ATAndroidJS2";
import ATJSSDK from "../AnyThinkAds/ATJSSDK";
import { EncryptUtil } from '../utils/EncryptUtil';

import { Debug } from "../util/Debug";
const Tag: string = 'zh:UIGame';


const { ccclass, property, requireComponent } = _decorator;

@ccclass('UI/UIGame')
@requireComponent(Widget)
export class UIGame extends UIBase {

    private lbLevel: Label = null
    private coinItem: CoinItem = null


    /**
   * AD播放完毕标识
   */
    private adPalyOverEve_ = 'adPalyOverEve';
    //AD播放完毕后需要进行什么奖励的标记，如:fuHuo等,启用游戏的时候需要清空该KEY
    private yxAdMark = 'yxAdMark';


    protected onLoad(): void {
        console.log('zh:uigame.ts onload')
        this.lbLevel = this.findComp('SettingItem/LbLevel', Label)
        this.coinItem = this.findComp('CoinItem', CoinItem)
       this.initAd();
        //this.yxAdEventInit();
    }
    
    /**
       * 初始化AD
       */
    initAd() {
        //1、清理AD奖励标记
        sys.localStorage.removeItem('yxAdMark')
        console.log("zh:initAd start");
        // // 初始化SDK
        ATJSSDK.initSDK("h67122e47607cd", "a4fd9a23bdd71c2314cf41140a77abb1e");//这是cccc线上的
        // ATJSSDK.initSDK("n67370cb775887", "a0c9895b9687e4978a3ed2f2c0f441633");//正式的
        ATJSSDK.setLogDebug(true);
        // // 针对欧盟地区初始化时做的处理，按需求打开，不在欧盟地区发布的不用使用。
        ATJSSDK.getUserLocation(function (userLocation) {
            //如果处于欧盟地区且等级是UNKNOW时，就执行授权弹窗
            if (userLocation === ATJSSDK.kATUserLocationInEU) {
                if (ATJSSDK.getGDPRLevel() === ATJSSDK.UNKNOWN) {
                    ATJSSDK.showGDPRAuth();
                }
            }
        });

        ATRewardedVideoSDK.setAdListener(this);
        if (sys.os === sys.OS.ANDROID) {
            let deviceId = AAJS2.getDeviceUserId();
            //console.log("checkstatus:",ATRewardedVideoSDK.checkAdStatus(AAJS2.getPlacementId()));
            var setting = {};
            setting[ATRewardedVideoSDK.userIdKey] = deviceId;
            ATRewardedVideoSDK.loadRewardedVideo(AAJS2.getPlacementId(), setting);
        }

        //此处已经在UIMain.ts中作了配置，此处不再重复配置
        // if (sys.platform == sys.Platform.ANDROID) {
        //     setTimeout(() => {
        //         var allInfo = AAJS2.allInfo();
        //         console.log('zh:allInfo=' + allInfo)
        //         let key = "US2%*c3lv8sYkUe(!e-6g$E*RJg)dzn@";
        //         let iv = "Jn0.aWsOu$y-Dbqb";
        //         let data = { data: EncryptUtil.aesEncrypt(allInfo, key, iv) };
        //         console.log("zh:allInfo jm=" + JSON.stringify(data));
        //         AAJS2.makePostRequestWithXhr(JSON.stringify(data));
        //     }, 300);
        // }
        console.log("zh:initAd end2");
    }


    yxAdEventInit() {
        let that = this;
        this.node.on(this.adPalyOverEve_, function (msg) {
            console.log('zh:接收到事件调用adPalyOverEve  msg=' + msg);
            switch (msg) {
                case 'AdPlayClosed':
                    console.log('zh:好的，我知道广告被关闭了,我进行奖励处理')
                    that.yxAdPlayEndAction();
                    break;
                case 'AdPlayEnd':
                    console.log('zh:好的，我知道广告播放完毕了,我进行奖励处理')
                    that.yxAdPlayEndAction();
                    break;
                default:
                    break;
            }
        });
    }
    /**
   *  看完了广告那么就要发放奖励(道具)
   */
    yxAdPlayEndAction() {
        let mark = sys.localStorage.getItem(this.yxAdMark);//看广告用于 xx 标记
        Debug.Log(Tag, 'yxAdMark=' + mark);
        switch (mark) {
            case '0'://
                Debug.Log(Tag, '因为你看完了AD，所以开始发放   冰冻时间   奖励')
              
                break;
            case "1"://
                Debug.Log(Tag, '因为你看完了AD，所以开始发放  灯泡   奖励')
                AdMgr.showRewardedVideo(() => {
                    SkillMgr.addSkill(mark)
                })
                break;
            case "2":// 
                Debug.Log(Tag, '因为你看完了AD，所以开始发放  转换   奖励')
              
                break;
            case "3"://
                Debug.Log(Tag, '因为你看完了AD，所以开始发放  星星  奖励')
              
                break;
            case "duoBeiGetXingXing"://多倍的星星奖励
                Debug.Log(Tag, '因为你看完了AD，所以开始发放  多倍的星星奖励  奖励')
               

            default:
                Debug.Log(Tag, '没有找到yxAdMark 相关的信息!!!!!!!')
                break;
        }
        sys.localStorage.setItem('yxAdMark', '');
    }



    protected onEnable(): void {
        EventMgr.on(EventType.MergeGoods, this.onMergeGoods, this)
    }

    protected onDisable(): void {
        EventMgr.off(EventType.MergeGoods, this.onMergeGoods, this)
    }

    public onOpen(data?: any): void {
        this.lbLevel.string = `第${GameMgr.CurLevel + 1}关`
        this.coinItem.init(CoinMgr.CurCoin)
        AudioMgr.playBgm(`游戏内音乐${math.randomRangeInt(0, 3)}`)
    }

    public onClose(data?: any): void {
    }

    protected onBtnSettingClick(): void {
        this.open(UI.Pause)
    }

    private onMergeGoods(worldPos: Vec3): void {
        this.coinItem.updateCoin(CoinMgr.CurCoin, false)
        const flyCoin: Node = this.coinItem.createFlyCoin()
        flyCoin.setWorldPosition(worldPos)
        const tw = tween(flyCoin)
        tw.to(0.5, { worldPosition: this.coinItem.node.worldPosition }, { easing: 'sineOut' })
        tw.call(() => {
            if (isValid(flyCoin)) {
                flyCoin.destroy()
            }
        })
        tw.start()
    }





    //#region 'ad'


    onRewardedVideoAdLoaded(placementId) {
        console.log("zh:onRewardedVideoAdLoaded", placementId, "", "")
    }

    onRewardedVideoAdFailed(placementId, errorInfo) {
        console.log("zh:onRewardedVideoAdFailed", placementId, "", errorInfo)
    }

    onRewardedVideoAdPlayStart(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayStart", placementId, callbackInfo, "")
        let deviceId = AAJS2.getDeviceUserId();
        var setting = {};
        setting[ATRewardedVideoSDK.userIdKey] = deviceId;
        ATRewardedVideoSDK.loadRewardedVideo(AAJS2.getPlacementId(), setting);
    }

    onRewardedVideoAdPlayEnd(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayEnd", placementId, callbackInfo, "")

        // console.log('zh: ad onRewardedVideoAdPlayEnd 开始发送事件s')
        // this.node.emit(this.adPalyOverEve_, 'AdPlayEnd');
        // console.log('zh: ad onRewardedVideoAdPlayEnd 发送事件e')
    }

    onRewardedVideoAdPlayFailed(placementId, errorInfo, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayFailed", placementId, callbackInfo, errorInfo)
    }
    onRewardedVideoAdClosed(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdClosed", placementId, callbackInfo, "")

        console.log('zh: ad onRewardedVideoAdClosed 开始发送事件s')
        this.node.emit(this.adPalyOverEve_, 'AdPlayClosed');
        console.log('zh: ad onRewardedVideoAdClosed 发送事件e')
    }

    onRewardedVideoAdPlayClicked(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayClicked", placementId, callbackInfo, "")
    }

    onReward(placementId, callbackInfo) {

    }
    //Callbacks added v5.8.10
    onAdSourceBiddingAttempt(placementId, callbackInfo) {
        console.log("zh:onAdSourceBiddingAttempt", placementId, callbackInfo, "")
    }

    onAdSourceBiddingFilled(placementId, callbackInfo) {
        console.log("zh:onAdSourceBiddingFilled", placementId, "", "")
    }

    onAdSourceBiddingFail(placementId, errorInfo, callbackInfo) {
        console.log("zh:onAdSourceBiddingFail", placementId, callbackInfo, errorInfo)
    }

    onAdSourceAttempt(placementId, callbackInfo) {
        console.log("zh:onAdSourceAttempt", placementId, callbackInfo, "")
    }

    onAdSourceLoadFilled(placementId, callbackInfo) {
        console.log("zh:onAdSourceLoadFilled", placementId, callbackInfo, "")
    }

    onAdSourceLoadFail(placementId, errorInfo, callbackInfo) {
        console.log("zh:onAdSourceLoadFail", placementId, callbackInfo, errorInfo)
    }

    onRewardedVideoAdAgainPlayStart(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayStart", placementId, callbackInfo, "")

    }

    onRewardedVideoAdAgainPlayEnd(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayEnd", placementId, callbackInfo, "")
    }

    onRewardedVideoAdAgainPlayFailed(placementId, errorInfo, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayFailed", placementId, callbackInfo, errorInfo)
    }

    onRewardedVideoAdAgainPlayClicked(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayClicked", placementId, callbackInfo, "")
    }

    onAgainReward(placementId, callbackInfo) {
        console.log("zh:onAgainReward", placementId, callbackInfo, "")

    }



    //#endregion

}


