import { _decorator, Component, Label, Node, tween, Vec2, Vec3,sys } from 'cc';

import { Global } from './Global';
import { PropsAction } from './PropsAction';
import { Clips, DJ, DJ_TYPE } from './Enums';
import { AudioMgr } from './AudioMgr';
import { Tools } from './Tools';
import { AdManger } from './ad/AdManger';
import { DjManger } from './DjManger';


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


const { ccclass, property } = _decorator;

@ccclass('Props3Action')
export class Props3Action extends Component {

    @property([Node])
    pin_img_arr:Node[] = [];

    @property(Node)
    bucket:Node = null;

    pos_pin  = [];

    @property({ type: Label })
    conis_label: Label;  

    start() {
        this.conis_label.string = Global.get_need_coins() + "";
        if(this.pin_img_arr){
            this.pin_img_arr.forEach((ele)=>{
              if(ele){
                this.pos_pin.push({pos:ele.getPosition().clone(),pin:ele});
              }
            });
        }
        this.initAdForPage();
    }

    /**
     * 初始化广告
     */
    initAdForPage(){
        console.log('zh:initAdForPage foir props3Action.ts')
        if(sys.os===sys.OS.ANDROID){
            let deviceId = AAJS2.getDeviceUserId();
            console.log("zh:checkstatus:",ATRewardedVideoSDK.checkAdStatus(AAJS2.getPlacementId()));
            var setting = {};
            setting[ATRewardedVideoSDK.userIdKey] = deviceId;
            ATRewardedVideoSDK.loadRewardedVideo(AAJS2.getPlacementId(), setting);
        }
    }

    dt:number = 0;
    times:number = 0;
    update(deltaTime: number) {
        if(!this.node.active){
            return;
        }
        if(this.times==0){
            this.times++;
            this.show_tween();
        }else{
            this.dt+=deltaTime;
            if(this.dt>=1.5){
                this.dt = 0;
                this.show_tween();
            }
        }
    }

    private show_tween(){
        this.pos_pin.forEach((ele)=>{
            this.play_tween(ele.pos,ele.pin);
          });
    }

    private play_tween(pos:Vec3,pin:Node){
        {
            //set pos default
            pin.setPosition(pos.x,pos.y,pos.z);
        }
        let target_pos = this.bucket.position.clone();
        target_pos.x = target_pos.x+ Tools.random_between(-20,20);
        target_pos.y = target_pos.y+ Tools.random_between(-20,20);
        tween(pin)
            .to(0.75, { position: target_pos },Global.our_easing)
            .call(() => {
            }).delay(0.3)
            .start();
    }


    /**
     * 清理钉子孔
     * @returns 
     */
    clear_pins_coins(){
        console.log('zh:clear_pins_coins 11')
        AudioMgr.ins.playSound(Clips.btn_1);
        if (Global.cur_coins < Global.get_need_coins()) {
            Global.tips_action.show("Gold Quantity Insufficient");//钻石数量不够
            return;
        }
        let pin_arr = Global.layer_empty_action.get_pin_arr();
        if (pin_arr.length == 0) {
            Global.tips_action.show("No Screws to Clear");//没有可清理的钉子
            return;
        }
    
        //如果不是开发调试就限制
        if(!Global.devMark){ 
            if (!DjManger.use_dj(DJ.Btn_3,DJ_TYPE.Type_coin)) {
                Global.tips_action.show("Current Level: Props Exhausted");//当前关卡次数已经用完   
                return;
            }
        }

        console.log('zh:clear_pins_coins 222')
        //消耗
        Global.use_coins(Global.get_need_coins());
        Global.bucket_action.put_pins(pin_arr);
        Global.coins_action.refrush_coins();
        this.node.parent.getComponent(PropsAction)?.close();
        console.log('zh:clear_pins_coins 333')
    }

    /**
     * 消耗钻石  ad 播放完毕  消耗钻石
     */
    useCoinsForAdPlayEnd(){
        console.log("zh:clear_pins_videos 开始清理钉子 奖励start");
        let pin_arr = Global.layer_empty_action.get_pin_arr();
        this.node.parent.getComponent(PropsAction)?.close();
        //解锁
        console.log("zh:clear_pins_videos 开始清理  "+ pin_arr.length +" 个钉子 ");
        if (pin_arr.length >0) {
            Global.bucket_action.put_pins(pin_arr);
        }
        console.log("zh:clear_pins_videos 开始清理钉子 奖励end");
        //清理AD奖励标记
        sys.localStorage.removeItem('yxAdMark')
    }



    /**
     * 清理钉子孔
     * @returns 
     */
    clear_pins_videos(){
        console.log('zh:clear_pins_videos  111')

        AudioMgr.ins.playSound(Clips.btn_1);
        let pin_arr = Global.layer_empty_action.get_pin_arr();
        if (pin_arr.length == 0) {
            Global.tips_action.show("No Screws to Clear");//没有可清理的钉子
            return;
        }
     
        if (!DjManger.use_dj(DJ.Btn_3,DJ_TYPE.Type_video)) {
            Global.tips_action.show("Current Level: Props Exhausted");//当前关卡次数已经用完   
            return;
        }
       
        console.log('zh:clear_pins_videos  222')
        if(sys.os == sys.OS.ANDROID){
            if(ATRewardedVideoSDK.hasAdReady(AAJS2.getPlacementId())){
                console.log('zh:clear_pins_videos ad  ok')
                sys.localStorage.setItem('yxAdMark', 'clearPins');//看广告用于 清理钉子 标记
                ATRewardedVideoSDK.showAd(AAJS2.getPlacementId());
            }else{
                console.log('zh:clear_pins_videos ad  no ok')
                Global.tips_action.show("No reward video for now");//没有奖励视频
               // this.useCoinsForAdPlayEnd();
            }
        }

        console.log('zh:clear_pins_videos  333')

        //zh 下面是原先的代码
        // AdManger.show_video((data) => {
        //     console.log('zh:clear_pins_videos data:',data)
        //     if (data == 1) {
        //         console.log("clear_pins_videos 获取奖励成功");
        //         this.node.parent.getComponent(PropsAction)?.close();
        //         //解锁
        //         Global.bucket_action.put_pins(pin_arr);
        //     } else {
        //         Global.tips_action.show("Gain reward failure");//获取奖励失败
        //         //退款
        //         DjManger.return_used_dj(DJ.Btn_3,DJ_TYPE.Type_video);
        //     } 
        // })
    }

    open(){
        this.conis_label.string = Global.get_need_coins() + "";
    }

}

