import { _decorator, CCInteger, Component, Enum, find, Node, sp, tween, UITransform, Vec3, view } from 'cc';
import { CupHeight, TakeGobletGlobalInstance, WaterColors } from '../TakeGobletGlobalInstance';
import { ANIMATION_DURATION, LevelAction } from '../LevelAction';
import { EventDispatcher } from 'db://assets/core_tgx/easy_ui_framework/EventDispatcher';
import { GameEvent } from '../Enum/GameEvent';
import { Water } from './Water';
import { OriginArea } from './OriginArea';
import { LevelManager } from '../Manager/LevelMgr';
import { tgxUITips } from 'db://assets/core_tgx/tgx';
import { GameUtil } from '../GameUtil';
import { TakeGobletAudioMgr } from '../Manager/TakeGobletAudioMgr';
const { ccclass, property, executeInEditMode } = _decorator;

//原浆杯状态 默认 抬起 倒水
export enum OriginCupState {
    Default,
    Up,
    PourWater
}

/** 原浆酒杯组件脚本*/
@ccclass('OriginCup')
@executeInEditMode
export class OriginCup extends Component {
    @property(sp.Skeleton)
    cupSkeleton: sp.Skeleton = null!;  //杯骨骼

    @property({ type: Enum(CupHeight), displayName: '杯高度' })
    cupHeight: CupHeight = CupHeight.Two

    @property(Node)
    waters: Node = null!;  //水节点

    @property(Node)
    marks: Node = null!;  //mark节点

    @property(Node)
    freeze: Node = null!;  //冰冻节点

    freezeCount: number = 0;

    get freezeActive() {
        return this.freeze.active;
    }

    set freezeActive(value: boolean) {
        this.freeze.active = value;
    }

    start() {
        this.cupSkeleton = this.node.getChildByName('Cup')?.getComponent(sp.Skeleton)!;

        this.node.on(Node.EventType.TOUCH_END, () => {
            TakeGobletAudioMgr.playOneShot(TakeGobletAudioMgr.getMusicIdName(3), 1.0);
            if (this.freezeActive) {
                tgxUITips.show('Unable to operate \n in freezing conditions!');
                return;
            }
            EventDispatcher.instance.emit(GameEvent.EVENT_CLICK_ORIGIN_CUP, this);
        });
    }

    async spawnNewOriginCup(height: CupHeight, targetPos: Vec3, colors: WaterColors[]): Promise<void> {
        return new Promise((resolve) => {
            if (!this.node) return;
            TakeGobletAudioMgr.playOneShot(TakeGobletAudioMgr.getMusicIdName(6), 1.0);
            const levelAction = this.node.parent?.parent?.getComponent(LevelAction)!;

            // 设置初始位置（屏幕左侧）
            const uiTransform = levelAction.node.getComponent(UITransform)!;
            this.node.setPosition(-uiTransform.width / 2, 0, 0);
            this.node.getComponent(OriginCup)!.cupHeight = height;
            levelAction.originArea?.addChild(this.node);
            // console.log(`spawnNewOriginCup 设置初始位置:${this.node.position}`);
            this.setupOriginCupColors(this.node, colors);
            this.setupFrozen();

            // 记录新杯子的初始位置
            levelAction.originCupPositions.set(this.node.uuid, targetPos);

            // 移动动画到原位置
            tween(this.node)
                .to(ANIMATION_DURATION, { position: targetPos })
                .call(() => {
                    const markCount = levelAction.originArea?.getComponent(OriginArea)?.getTotalMarkCount();
                    console.log(`mark总数:${markCount}`);
                    LevelManager.instance.levelModel.createQuestionCount = markCount;
                    resolve();
                })
                .start();
        });
    }

    // 设置原浆杯颜色
    private setupOriginCupColors(cupNode: Node, colors: WaterColors[]) {
        const levelAction = this.node.parent?.parent?.getComponent(LevelAction)!;
        const originCup = cupNode.getComponent(OriginCup)!;
        const marks = cupNode.getChildByName('Marks')!;
        const waters = originCup.waters.children;
        // console.log(`新创建原浆杯，高度: ${originCup.cupHeight}`);
        const markCount = levelAction.originArea.getComponent(OriginArea)?.getTotalMarkCount();
        const waterCount = originCup.cupHeight;
        for (let i = 0; i < waterCount; i++) {
            const waterNode = waters[i];
            if (!waterNode) continue;

            const water = waterNode.getComponent(Water)!;
            const mark = TakeGobletGlobalInstance.instance.refreshQuestionWater(markCount);
            water.color = colors[Math.floor(Math.random() * colors.length)];
            waterNode.active = true;
            // console.log(`i:${i} --  marks.children[i].name:${marks.children[i].name}`);
            if (mark) {
                marks.children[i].active = true;
            }
        }
    }

    // 设置原浆冰冻
    private setupFrozen() {
        const levelAction = this.node.parent?.parent?.getComponent(LevelAction)!;
        const freezeCount = levelAction.originArea.getComponent(OriginArea)?.getFrozenCupCount();
        const freeze = TakeGobletGlobalInstance.instance.refreshFreezeWater(freezeCount);
        this.freezeActive = freeze;
    }

    //解除冰冻
    unFreeze() {
        TakeGobletAudioMgr.playOneShot(TakeGobletAudioMgr.getMusicIdName(9), 1.0);
        this.freezeCount++;
        this.freeze.children.forEach((freezeNode, i) => {
            freezeNode.getComponent(sp.Skeleton)!.setAnimation(0, `freeze_0${this.freezeCount}`, false);
        })

        if (this.freezeCount >= this.cupHeight) {
            this.freezeActive = false;
        }
    }

    /** 倒水动画*/
    pourWater() {
        TakeGobletAudioMgr.playOneShot(TakeGobletAudioMgr.getMusicIdName(4), 1.0);
        const activeWaters = this.waters.children.filter(n => n.active);
        const topIndex = this.waters.children.length - activeWaters.length;
        if (activeWaters.length >= 0) {
            this.playAnimation(OriginCupState.PourWater, topIndex + 1);
        }
    }

    hideCurrentWaterLayer() {
        if (!this.waters) return;
        const activeWaters = this.waters!.children.filter(n => n.active);
        if (activeWaters.length >= 0) {
            activeWaters[activeWaters.length - 1].active = false;
        }
    }

    //播放原浆杯倒水动画
    playAnimation(state: OriginCupState, index?: number) {
        switch (state) {
            case OriginCupState.Up:
                this.playUpAnimation();
                break;
            case OriginCupState.PourWater:
                this.playPourWaterAnimation(index);
                break;
            default:
                break;
        }
    }

    playUpAnimation() {
        if (!this.cupSkeleton) return;
        this.cupSkeleton.setAnimation(0, 'pour_idle', false);

        this.waters.children.forEach(water => {
            water.getComponent(Water)?.playAnimation(OriginCupState.Up);
        });
    }

    playPourWaterAnimation(index: number) {
        if (!this.cupSkeleton) return;
        this.setSpineTimeScale(1.5);
        this.cupSkeleton.setAnimation(0, `pour_0${index}`, false);
        this.waters.children.forEach(water => {
            water.getComponent(Water)?.playAnimation(OriginCupState.PourWater, index);
        });
    }

    //设置spine 时间缩放率
    setSpineTimeScale(timeScale: number = 1) {
        if (!this.node) return;
        const spineComponents = this.node.getComponentsInChildren(sp.Skeleton);
        spineComponents.forEach(spine => {
            spine.timeScale = timeScale;
        });
    }

    setMark(bool: boolean) {
        this.marks.active = bool;
    }

    async destroyOriginCup() {
        const id = this.node.uuid;
        const uiTransform = this.node.getComponent(UITransform)!;
        const screenWidth = view.getVisibleSize().width;
        const targetX = -screenWidth - uiTransform.width * 1.5;

        await new Promise<void>(resolve => {
            tween(this.node)
                .to(0.2, { position: new Vec3(targetX, this.node.position.y, 0) }, { easing: 'sineIn' })
                .call(async () => {
                    LevelManager.instance.levelModel.currentOriginCup++;
                    EventDispatcher.instance.emit(GameEvent.EVENT_ORIGIN_CUP_DESTROYED, id);
                    this.node.destroy();
                    resolve();
                })
                .start();
        });
    }
}


