import { BoxCollider, Button, Collider, Component, ConeCollider, CylinderCollider, ITriggerEvent, Label, Node, NodeEventType, RigidBody, SphereCollider, Vec3, _decorator, find, game } from 'cc';
import { StormSunderAudioMgr } from '../Manager/StormSunderAudioMgr';
import { EventDispatcher } from 'db://assets/core_tgx/easy_ui_framework/EventDispatcher';
import { GameEvent } from '../Enum/GameEvent';
import { UIJoyStick } from '../UIJoyStick';
import { GameMgr, GameStatus } from '../Manager/GameMgr';
import { PropComponent, PropStatus } from './PropComponent';
import { PlayerInfo } from './PlayerInfoComponent';
import { Effect2DUIMgr } from '../Manager/Effect2DUIMgr';
const { ccclass, property } = _decorator;

const rotateSpeed = 500;
export enum PlayerStatus {
    LIFE,
    DIE
}

/** 龙卷风组件*/
@ccclass('TornadoComponent')
export class TornadoComponent extends Component {
    @property({ type: [Node] })
    points: Node[] = [];

    tornado: Node = null!;
    rigidBody: RigidBody = null!;
    tigger: Collider = null!; //龙卷风触发器
    radiusTigger: Collider = null!;     //龙卷风半径检测触发器

    attack: number = 20;
    speed: number = 50;
    currentExp: number = 0;
    currentLv: number = 1;
    nextExp: number = 100;
    nickName: string = null;
    playerStatus: PlayerStatus = PlayerStatus.LIFE;
    playerInfo: PlayerInfo = null;
    isColliding: boolean = false;
    private _ai: boolean = false;
    public get ai(): boolean {
        return this._ai;
    }
    public set ai(value: boolean) {
        this._ai = value;
    }

    _attackInterval: number = 0.5; // 攻击间隔
    _lastAttackTime: Map<string, number> = new Map(); // 记录上次攻击时间

    protected start(): void {
        this.initializeData();
        this.initilizeUI();
        this.registerEvent();
    }

    initilizeUI(): void {
        if (!this.node) return;

        this.tornado = this.node.getChildByName('tornado')!;
        this.rigidBody = this.tornado.getComponent(RigidBody)!;
        this.tigger = this.tornado.getComponent(Collider)!;

        this.tigger.on('onTriggerEnter', this.onTriggerEnter, this);
        this.tigger.on('onTriggerStay', this.onTriggerStay, this);
        this.tigger.on('onTriggerExit', this.onTriggerExit, this);
    }

    initializeData() {
        //DOTO 计算方式根据配置表
        this.currentLv = 1;
        this.currentExp = 0;
        this.nextExp = 100;
        this.attack = 20;
        this.speed = 50;
        this.nickName = '爸爸在此';
        this.ai = false;

        this.playerInfo = {
            nickName: '爸爸在此',
            level: 1,
            exp: 0,
        }

        this.changeStatus(PlayerStatus.LIFE);
    }

    protected registerEvent() {
        EventDispatcher.instance.on(GameEvent.EVENT_STORM_LEVEL_UP, this.stormLevelUp, this);
    }

    onTriggerEnter(event: ITriggerEvent): void {
        let _originalPosition = this.node.position.clone();
        if (event.otherCollider.getGroup() === 1 << 2) {
            if (this.isColliding) return; // 防止重复触发

            this.isColliding = true;
            _originalPosition = this.node.position.clone(); // 记录碰撞前坐标

            // 计算反方向移动（保持Y轴不变）
            const reverseDirection = this.calculateReverseDirection(event);
            const newPosition = _originalPosition.add(reverseDirection);

            // 直接修改坐标
            this.node.setPosition(newPosition);
            setTimeout(() => {
                this.isColliding = false;
            }, 500);
        }
    }

    // 计算反方向（基于障碍物位置）
    private calculateReverseDirection(event: ITriggerEvent): Vec3 {
        // 获取障碍物节点位置
        const obstaclePos = event.otherCollider.node.worldPosition;
        const selfPos = this.node.worldPosition;

        // 计算方向向量（从障碍物指向自己）
        const direction = new Vec3(
            selfPos.x - obstaclePos.x,
            0, // Y轴保持0
            selfPos.z - obstaclePos.z
        );

        // 归一化并乘以反冲距离
        return direction.normalize().multiplyScalar(5);
    }

    onTriggerStay(event: ITriggerEvent): void {
        if (event.otherCollider.getGroup() == 1 << 4) {
            const otherCollider = event.otherCollider;
            const propComp = otherCollider.node.getComponent(PropComponent);

            if (!propComp) return;

            const currentTime = game.totalTime;
            const nodeId = otherCollider.node.uuid;
            const lastTime = this._lastAttackTime.get(nodeId) || 0;

            // 检查是否达到攻击间隔
            if (currentTime - lastTime >= this._attackInterval * 1000) {
                this._lastAttackTime.set(nodeId, currentTime);

                if (propComp.status == PropStatus.DIE) return
                // 造成伤害
                propComp.hurt(this.attack);

                // 检查道具是否被摧毁
                if (propComp.currentHp <= 0) {
                    // 随机选择一个吸收点
                    const randomPoint = this.points[Math.floor(Math.random() * this.points.length)];
                    if (randomPoint) {
                        otherCollider.node.parent = randomPoint;
                        otherCollider.node.setPosition(Vec3.ZERO);
                        propComp.swallow();
                        this.addExpByProp(propComp);
                    }
                }
            }
        }
    }

    onTriggerExit(event: ITriggerEvent) {
    }

    update(deltaTime: number) {
        if (GameMgr.inst.gameStatus != GameStatus.Playing) return;

        this.onPlayerInfoHandler();
        this.onMoveHandler();
        this.onRotateHandler();
    }

    async onPlayerInfoHandler() {
        await Effect2DUIMgr.inst.addPlayerInfo(this.node, this.playerInfo);
    }

    onRotateHandler(): void {
        this.node.eulerAngles = new Vec3(this.node.eulerAngles.x, this.node.eulerAngles.y + rotateSpeed * game.deltaTime, this.node.eulerAngles.z);
    }

    onMoveHandler(): void {
        if (this.isColliding) return;
        const playerDir = UIJoyStick.ins.dir;
        const playerX = playerDir.x * this.speed * game.deltaTime;
        const playerZ = playerDir.y * this.speed * game.deltaTime;

        this.node.setPosition(this.node.position.x + playerX, 0, this.node.position.z - playerZ);
    }

    private addExpByProp(propComp: PropComponent) {
        const propExp = propComp.exp;
        this.currentExp += propExp;
        if (this.currentExp >= this.nextExp) {
            this.stormLevelUp();
            this.currentLv++;

            this.playerInfo.level = this.currentLv;
            Effect2DUIMgr.inst.updatePlayerInfo(this.node, this.playerInfo);
        }
    }

    private stormLevelUp() {
        //DOTO  计算攻击速度等属性
        this.attack += this.attack;
        this.speed += this.speed * 0.1;
        this.nextExp += this.nextExp;
        this.currentExp = 0;
    }

    private changeStatus(status: PlayerStatus) {
        this.playerStatus = status;
    }

    protected onDestroy(): void {
        this.unregisterEvent();
    }

    protected unregisterEvent() {
        EventDispatcher.instance.off(GameEvent.EVENT_STORM_LEVEL_UP, this.stormLevelUp, this);
    }

}
