
import { _decorator, tween, v3, EditBox, Node, Vec3, Tween, Quat } from 'cc';
import BasePanel from '../core/component/BasePanel';
import { audioMgr } from '../core/manager/AudioManager';
import Data from '../core/manager/Data';
import WindowManager from '../core/manager/WindowManager';
import MsgHints from '../core/utils/MsgHints';
import Utils from '../core/utils/Utils';
import { BoxLayer } from '../gameui/BoxLayer';
import { GameConst, BOX_TYPE, ITEM_TYPE } from '../core/common/GameConst';
import i18n from '../core/i18n/runtime-scripts/LanguageData';
import { autoBind } from '../core/extend/AutoBind';
import platformSystem from '../platform/platformSystem';

const { ccclass, property } = _decorator;

@ccclass('HallUI')
export class HallUI extends BasePanel {
    @autoBind(EditBox)
    public editBox: EditBox = null!;
    @autoBind
    public chestLevel0: Node = null!;
    @autoBind
    public chestLevel1: Node = null!;

    onLoad(): void {
        super.onLoad();
        this.shake(this.chestLevel0);
        this.shake(this.chestLevel1);
    }

    /**
     * 小幅度旋转晃动节点（轻微摇摆效果）
     * @param n 要晃动的节点
     * @param intensity 晃动强度（默认1，范围0.1-3）
     */
    public shake(n: Node, intensity: number = 1) {
        Tween.stopAllByTarget(n); // 停止所有之前的动画
        const originalAngle = n.angle; // 保存初始角度
        const shakeAngle = 3 * Math.min(Math.max(intensity, 0.1), 3);
        tween(n)
            .delay(1.2)
            .repeat(20,
                tween()
                    .to(0.15, { angle: originalAngle + shakeAngle }, { easing: 'sineInOut' }) // 向右微倾
                    .to(0.15, { angle: originalAngle - shakeAngle }, { easing: 'sineInOut' }) // 向左微倾
                    .to(0.15, { angle: originalAngle }, { easing: 'sineInOut' }) // 回正
            )
            .call(() => {
                n.angle = originalAngle; // 确保最终回到初始角度
            })
            .start();
    }

    onBtnClicked(event: any, customEventData: any) {
       audioMgr.playOneShot(GameConst.audios.btnclick);
        var btnName = event.target.name;
        switch (btnName) {
            case "btn_setting":
                // WindowManager.ins.open("NewPackOpenedLayer");
                WindowManager.ins.open("SettingLayer")
                break;
            case "btn_play":
                //获取输入的内容
                if(GameConst.isDebug){
                    let str: string = this.editBox.string;
                    if(!Utils.isNull(str)){
                        const level: number = parseInt(str);
                        Data.user.lv = level;
                    }
                }
                platformSystem.platform.showInterstitialAd();
                WindowManager.ins.open("LevelLayer");
                /*platformSystem.platform.showRewardVideo((b) => {
                    WindowManager.ins.open("LevelLayer");
                })*/
                break;
            case "btn_buy_life":
                if (Data.user.life >= GameConst.MAX_LIFE) {
                    MsgHints.show(i18n("main.体力已满"))
                    return;
                }
                WindowManager.ins.open("BuyLifeLayer")
                break;
            case "btn_buy_coin":
                WindowManager.ins.open("BuyCoinLayer");
                break;
            case "reward0":
            case "full0":
                let info0 = Data.user.hasLvBox();
                if(!info0){
                    MsgHints.show(i18n(`main.条件不足`));
                    return;
                }
                WindowManager.ins.open("BoxLayer").then((com: BoxLayer) => {
                    com?.setInfo(BOX_TYPE.LEVEL, GameConst.getLvBoxReward(Math.floor(Data.user.lv / GameConst.LvBox_Reward)))
                });
                break;
            case "reward1":
            case "full1":
                let info1 = Data.user.hasStarBox();
                if(!info1){
                    MsgHints.show(i18n(`main.条件不足`));
                    return;
                }
                WindowManager.ins.open("BoxLayer").then((com: BoxLayer) => {
                    com?.setInfo(BOX_TYPE.STAR, GameConst.getStarBoxReward(Math.floor(Data.user.lv / GameConst.Start_Progress)))
                });
                break;
        }
    }

    start() {
        if(!GameConst.isDebug){
           this.editBox.node.active = false;
        }
        this.SetText("level_lable", i18n("main.LV:%{value}", { value: Data.user.lv}));
        this.SetProgressBar("probar_lv", 0.1);
        let btn_play = this.GetNode("btn_play")
        tween(btn_play).sequence(tween(btn_play).to(1, { scale: v3(1.05, 1.05, 1.05) }), tween(btn_play).to(1, { scale: v3(1, 1, 1) })).repeatForever().start()
    }

    update() {
        if (Data.user.life >= GameConst.MAX_LIFE) {
            this.SetText("lbl_life_time", i18n("main.已满"))
        }else {
            if (Data.user.life_cost_time == 0) {
                Data.user.life_cost_time = Date.now();
            }

            let nLeft = (Date.now() - Data.user.life_cost_time) / 1000;
            let addLife = Math.floor(nLeft / 60 / GameConst.MAX_LIFE_RECOVERY_TIME);
            if (addLife > 0)
                Data.user.life += addLife;
            nLeft -= addLife * GameConst.MAX_LIFE_RECOVERY_TIME * 60;
            this.SetText("lbl_life_time", Utils.getTimeStrByS(GameConst.MAX_LIFE_RECOVERY_TIME * 60 - nLeft))
        }
        this.SetText("lbl_life", Data.user.life + "")
        this.SetText("lbl_coin", Data.user.coin + "")
        this.SetText("lbl_lv", Data.user.lv + "")
        this.SetText("lbl_lv_center", Data.user.lv + "")

        let info = Data.user.hasLvBox();
        this.GetGameObject("full0").active = info
        let lvmin = Data.user.lv % 10;
        this.SetText("lbl_pro_lv", lvmin + "/10");
        this.SetProgressBar("lbl_pro_star", lvmin / 10);
        this.SetProgressBar("probar_lv_center", lvmin / 10);
        this.SetProgressBar("probar_lv", lvmin / 10);

        info = Data.user.hasStarBox();
        if (info) {
            this.SetText("probar_star", "满");
            this.SetProgressBar("probar_star", 1);
            this.GetGameObject("full1").active = true;
        }else {
            let starmin = Data.user.star % GameConst.Start_Progress;
            this.GetGameObject("full1").active = false;
            this.SetText("lbl_pro_star", starmin + `/${GameConst.Start_Progress}`);
            this.SetProgressBar("probar_star", starmin / GameConst.Start_Progress);
        }
    }
}
