import { _decorator, Label,sp, UITransform, Vec2, Vec3 ,Node, isValid, tween} from 'cc';
import { ObjectUtil } from '../../../../framework/util/ObjectUtil';
import { BattleNodeBase } from './BattleNodeBase';
import { HeroData } from '../data/HeroData';
import { AudioID } from '../../../../framework/config/AudioConf';
import { Framework } from '../../../../framework/Framework';
import { UptypeConf } from '../conf/UptypeConf';
import { HeroConf } from '../conf/HeroConf';
const { ccclass, property } = _decorator;


//英雄基类
@ccclass('Hero')
export class Hero extends BattleNodeBase {



    @property({ type: sp.Skeleton, tooltip: '骨骼动画' })
    modelSpine: sp.Skeleton = null;
    @property({ type: Label, tooltip: '等级' })
    levelLabel: Label = null;

    @property({ type: Node, tooltip: '枪' })
    gunNode: Node = null;


    //所属格子 -1表示暂无
    private _posID = -1;

  
    private _bAttackAnimation: boolean = false;

    attackNode = null;
    attackBone = null;
    attackSlot = null;
    typeID: number = -1; 
    level: number = 1; 
    radius = 1; //半径





    set posID(posID:number){
        this._posID = posID;
    }
    get posID(){
        return this._posID;
    }

    protected onLoad(): void {
         this.modelSpine.setCompleteListener(this.actionComplete.bind(this))
        this.modelSpine.setEventListener(this.actionCallback.bind(this))

        let bone = this.modelSpine.findBone("gun")
        if(bone){
            this.attackBone = bone
            let rot = this.attackBone.rotation
        }
    }

    start() {
       
    }


    resetData(heroData:HeroData) {
        this.typeID = heroData.typeID;
        this.level = heroData.level;
        this.radius = heroData.attackRadius;
        this.levelLabel.string = heroData.level.toString();
        this.node.active = true;
        this.modelSpine.node.active = true;
        let conf = UptypeConf.data
        let speedScale = conf.HeroSpeedColArr[this.level]
        this.modelSpine.timeScale = speedScale;
        this.stand()
        // let id: string = heroData.heroID;
        
    }


    clearData() {
        this.node.active = false;
        this.modelSpine.node.active = false;
        this._posID = -1;
        this.typeID = -1;
        this.level = 0;
        this._isLock = false;
    }


    update(deltaTime: number) {
        super.update(deltaTime);
        if(this._bAttackAnimation && isValid(this.attackNode)){
            let pos = this.attackNode.position;
            // 获取子节点的世界坐标
            let worldPosition = this.gunNode.getComponent(UITransform).convertToWorldSpaceAR(Vec3.ZERO);
            // 将子节点的世界坐标转换为父节点的局部坐标
            let localPosition = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(worldPosition);
            // 计算从p0到p1的向量
            let deltaX: number = pos.x - localPosition.x;
            let deltaY: number = pos.y - localPosition.y;

            // 计算旋转角度（弧度）
            let rotationAngleRadians: number = Math.atan2(deltaY, deltaX);
            // 将旋转角度转换为度数
            let rotationAngleDegrees: number = (rotationAngleRadians * (180 / Math.PI)+360)%360;

            // console.log("旋转角度：", rotationAngleDegrees);

            // let scaleX = this.modelSpine.node.scale.x
            // if(rotationAngleDegrees > 90 && rotationAngleDegrees < 270){
            //     // if(scaleX > 0){
            //     //     scaleX= -scaleX;
            //     // }
            //     // this.gunNode.angle = 180 - rotationAngleDegrees;
            //     this.attackBone.rotation = 180 - rotationAngleDegrees
            // }
            // else{
            //     // if(scaleX < 0){
            //     //     scaleX= -scaleX;
            //     // }
            //     // this.gunNode.angle = rotationAngleDegrees;
            //     this.attackBone.rotation = rotationAngleDegrees
            // }
            // this.modelSpine.node.scale = new Vec3(scaleX,this.modelSpine.node.scale.y,this.modelSpine.node.scale.z);
            // console.log("旋转角度：", rotationAngleDegrees);
            if(rotationAngleDegrees<67.5 || rotationAngleDegrees > 292.5){
                this.attackBone.rotation = rotationAngleDegrees
                if(this.modelSpine.animation != "fire_0")
                    this.modelSpine.setAnimation(0, 'fire_0', true);
            }
            else if(rotationAngleDegrees < 112.5){
                this.attackBone.rotation = rotationAngleDegrees
                if(this.modelSpine.animation != "fire_90")
                    this.modelSpine.setAnimation(0, 'fire_90', true);
            }
            else if(rotationAngleDegrees < 247.5){
                this.attackBone.rotation = 180-rotationAngleDegrees
                if(this.modelSpine.animation != "fire_180")
                    this.modelSpine.setAnimation(0, 'fire_180', true);
            }
            else if(rotationAngleDegrees < 292.5){
                this.attackBone.rotation = rotationAngleDegrees
                if(this.modelSpine.animation != "fire_270")
                    this.modelSpine.setAnimation(0, 'fire_270', true);
            }
        }

       
    }
    //屏幕坐标
    bTouch(pos: Vec2){
       return this.node.getComponent(UITransform).hitTest(pos,0);
    }

    get bAttackAnimation(): boolean{
        return this._bAttackAnimation;
    }


    //通过目标坐标 来确定朝向
    attack(attackNode:Node){
        if(!this.modelSpine.node.active) return;
        
        // if(this._bAttackAnimation) return; 
        this._bAttackAnimation = true;

        this.attackNode = attackNode;

        Framework.audio.playEffect(AudioID.Tututu);
    }

    stand() {
        if(!this.modelSpine.node.active) return;
        this._bAttackAnimation = false;
        // this.gunNode.angle = 0;
        this.gunNode.active = true;
                this.attackBone.rotation = 0
                // this._attackCallback = null;
        if(this.modelSpine.animation == "stand_0") return; 
        this.modelSpine.setAnimation(0, 'stand_0', true);
        // if(this.modelSpine.node.scale.x < 0)
        //     this.modelSpine.node.scale = new Vec3(-this.modelSpine.node.scale.x,this.modelSpine.node.scale.y,this.modelSpine.node.scale.z);

    }

    levelUp() {
        this.level++;
        this.levelLabel.string = this.level.toString();
        let conf = UptypeConf.data
        let speedScale = conf.HeroSpeedColArr[this.level]
        this.modelSpine.timeScale = speedScale;
    }

    actionCallback(trackEntry){
        // console.log("动作回调：",trackEntry.animation.name)
        if (trackEntry.animation.name && trackEntry.animation.name.includes("fire")) {

            // if (this._attackCallback) {
            //     this._attackCallback(trackEntry);
            // }
        } 
    }

    actionComplete(trackEntry:sp.spine.TrackEntry){
        // console.log("动作完成：",trackEntry.animation.name,this._posID)
        if (trackEntry.animation.name && trackEntry.animation.name.includes("fire")) {

            // this._bAttackAnimation = false;
            // // this.gunNode.angle = 0;
            // // this.gunNode.active = false;
            
            //     this.attackBone.rotation = 0
                // this._attackCallback = null;
        } 
    }

    //
    flyTo(pos:Vec3, callback:Function){
        if(this._isLock){ return false; }
        this.isLock = true;
        let length = Vec3.distance(this.node.position,pos);
        if(length > 300){
            length = 300;
        }
        tween(this.node).to(length/500,{position:pos}).call(()=>{
            this.isLock = false;
            if(callback) callback();
        }).start();
        
    }

    hitTest(pos:Vec2){
        return this.modelSpine.getComponent(UITransform).hitTest(pos);
    }

    
}


