import { _decorator, Node, Sprite, Asset, ImageAsset, SpriteFrame, Texture2D, Label, tween, UIOpacity, Animation, math, RichText } from 'cc';
import BaseView from '../../../../../../extensions/app/assets/base/BaseView';
import { PageTips } from '../../tips/native/PageTips';
import { app } from 'db://assets/app/app';
import { PageRewardhistory } from '../../rewardhistory/native/PageRewardhistory';
import { Tools } from 'db://assets/res-native/tools/Tools';
import { USERDATA } from 'db://assets/res-native/data/UserData';
const { ccclass, property } = _decorator;
@ccclass('PageMain')
export class PageMain extends BaseView {
    /** 音乐按钮 */
    @property(Node)
    btn_music: Node = null!;
    /** 奖励文字 */
    @property(Label)
    lab_rw: Label = null!;
    /** 奖励 */
    @property(Node)
    reward_bg: Node = null!;
    @property(Node)
    no_reward_bg: Node = null!;
    /** 奖励icon */
    @property(Sprite)
    icon_rw: Sprite = null!;
    /** 剩余次数 */
    @property(RichText)
    lab_remain: RichText = null!;
    /** 骰子动画 */
    @property(Node)
    dices: Node[] = [];
    /** 奖励 */
    @property(Node)
    rw_list: Node[] = [];
    /** 骰子动画 */
    @property(Node)
    ani_dice_roll: Node = null;
    /** 骰子 */
    @property(Node)
    roll_dices: Node[] = [];
    /** 游戏名 */
    @property(Node)
    game_name: Node = null;

    /** 是否可以开始游戏 */
    private _canStart = true;

    // 初始化的相关逻辑写在这
    onLoad() {}

    // 界面打开时的相关逻辑写在这(onShow可被多次调用-它与onHide不成对)
    onShow(params: any) {
        this.lab_remain.string = "CHANCE:<color=#ff5656>" + USERDATA.point.toString() + "</color>"
        this.initRw()
        this.startFloatingAnimation()
    }

    // 界面关闭时的相关逻辑写在这(已经关闭的界面不会触发onHide)
    onHide(result: undefined) {
        // app.manager.ui.show<PageMain>({name: 'PageMain', onHide:(result) => { 接收到return的数据，并且有类型提示 }})
        return result;
    }

    initRw(){
        for (let i = 0; i < USERDATA.prize_list.length; i++) {
            const element = USERDATA.prize_list[i];
            Tools.remoteLoadSprite(element.pic, Tools.GetChildComp(this.rw_list[i], "icon", Sprite));
            Tools.SetChildText(this.rw_list[i], "lab", element.name);
        }

        this._canStart = true
    }


    /** 点击奖励确定 */
    onClickRewardSure(){
        this.reward_bg.active = false
        this.no_reward_bg.active = false
        this._canStart = true
    }

    /** 点击提示 */
    onClickTips(){
        app.manager.ui.show<PageTips>({name: 'PageTips'})
    }

    /** 点击音乐 */
    oncClickMusic(){
        let music = app.manager.sound.isMusicPlaying
        music ? app.manager.sound.stopMusic() : app.manager.sound.playDefaultMusic()
        this.loadSprite(music ? "main_btn_sounds_off" : "main_btn_sounds_on", this.btn_music)
    }

    /** 点击历史 */
    onClickRwHis(){
        app.manager.ui.show<PageRewardhistory>({name: 'PageRewardhistory'})
    }

    /** 点击开始 */
    onStartGame() { 
        if (!this._canStart) return;
        if (USERDATA.point <= 0) {
            app.manager.ui.showToast(Tools.GetLocalized("no chance"));
            return;
        }

        this._canStart = false;

        Tools.httpReq("lottery", {}, (res:any)=>{
            let n = this.checkRwId(res.prize_id)
            if (n == null){
                app.manager.ui.showToast(Tools.GetLocalized("fail"))
                return
            }

            USERDATA.point--
            this.lab_remain.string = "CHANCE:<color=#ff5656>" + USERDATA.point.toString() + "</color>"
            this.lab_rw.string = Tools.StringLFormat(res.message)
            Tools.remoteLoadSprite(USERDATA.prize_list[n].pic, this.icon_rw)

            this.startSpinAnimation(n, res.prize_type != 3);
        },()=>{
            this._canStart = true;
        })
    }

    checkRwId(prize_id: number){
        let n = null
        for (let i = 0; i < USERDATA.prize_list.length; i++) {
            const element = USERDATA.prize_list[i];
            if (prize_id == element.id){
                n = i
                break
            }
        }
        return n
    }

    loadSprite(pic: string, node: Node){
         this.loadRes(pic, Asset, (res: ImageAsset)=>{
            let sp = new SpriteFrame()
            let tex = new Texture2D();
            tex.image = res;
            sp.texture = tex
            node.getComponent(Sprite).spriteFrame = sp
        });
    }

    // 开始浮动动画
    async startFloatingAnimation() {
        // 对dices数组中的每个元素应用浮动动画
        // 创建上下浮动动画
        tween(this.dices[0])
            .by(0.8, { position: new math.Vec3(0, 50, 0) })  // 向下移动10像素
            .by(0.8, { position: new math.Vec3(0, -50, 0) })   // 向上移动10像素，回到原位
            .union()
            .repeatForever()  // 无限重复
            .start();

        tween(this.game_name)
            .to(0.7, { scale: new math.Vec3(1.1, 1.1, 0) })
            .to(1.0, { scale: new math.Vec3(1, 1, 0) })
            .union()
            .repeatForever()  // 无限重复
            .start();

        await delay(300);

        tween(this.dices[1])
            .by(1, { position: new math.Vec3(0, -30, 0) })  // 向下移动10像素
            .by(1, { position: new math.Vec3(0, 30, 0) })   // 向上移动10像素，回到原位
            .union()
            .repeatForever()  // 无限重复
            .start();
        await delay(300);

        tween(this.dices[2])
            .by(1, { position: new math.Vec3(0, -30, 0) })  // 向下移动10像素
            .by(1, { position: new math.Vec3(0, 30, 0) })   // 向上移动10像素，回到原位
            .union()
            .repeatForever()  // 无限重复
            .start();
    }

    async startSpinAnimation(n : number, win : boolean){
        this.roll_dices[0].active = false;
        this.roll_dices[1].active = false;

        // 骰子动画
        app.manager.sound.playEffect({name : "effect/shaizi"});
        this.ani_dice_roll.active = true;
        this.ani_dice_roll.getComponent(Animation).play();
        await delay(1000);
        this.ani_dice_roll.active = false;
        this.roll_dices[0].active = true;
        this.roll_dices[1].active = true;

        let n1: number, n2: number;
        let sum = n + 2
        // 确保两骰子值都在1-6范围内
        let minN1 = Math.max(1, sum - 6);  // n1最小值，确保n2不超过6
        let maxN1 = Math.min(6, sum - 1);  // n1最大值，确保n2至少为1
        
        if (minN1 <= maxN1) {
            n1 = Math.floor(Math.random() * (maxN1 - minN1 + 1)) + minN1;
            n2 = sum - n1;
        } else {
            // 理论上不应该到达这里
            n1 = 1;
            n2 = sum - 1;
        }

        this.loadSprite("main_dice_" + n1, this.roll_dices[0]);
        this.loadSprite("main_dice_" + n2, this.roll_dices[1]);

        await delay(500);
        
        // 闪烁动画
        app.manager.sound.playEffect({name : "effect/dengdeng"});
        let lightNode = this.rw_list[n].getChildByName("light")
        if (lightNode) {
        lightNode.active = true;
        // 重置初始状态
        lightNode.getComponent(UIOpacity).opacity = 255;
        // 创建闪烁动画
        tween(lightNode.getComponent(UIOpacity))
            .to(0.3, { opacity: 0 })  // 从255渐变到100
            .to(0.3, { opacity: 255 })   // 从100渐变回255
            .union() 
            .repeat(2)                   // 重复3次闪烁
            .call(()=>{
                lightNode.active = false;
                if (win) app.manager.sound.playEffect({name : "effect/win", volume: 0.6});
                this.reward_bg.active = win;
                this.no_reward_bg.active = !win;
                this._canStart = true;
            })
            .start();
        }
    }
}

// 在类外部或类内添加延迟函数
function delay(ms: number): Promise<void> {
    return new Promise(resolve => setTimeout(resolve, ms));
}