/**
 * 冲锋
 */
import CMath from "../../../../util/CMath";
import FSprite, { SpriteActionType } from "../FSprite";
import PSprite from "../PSprite";
import ChargeCollision from "./ChargeCollision";
import SkillBase from "./SkillBase";

const {ccclass, property} = cc._decorator;

@ccclass
export default class SkillCharge extends SkillBase {

    @property({
        type:cc.Node,
        displayName: '预警显示'
    })
    mRedGo: cc.Node = null;
    /**
     * 预警延时
     */
    @property({
        displayName: '预警延时'
    })
    public dtime = 2;
    /**
     * 冲刺消耗的时间
     */
    @property({
        displayName: '冲刺消耗的时间'
    })
    public ctime = 0.7;

    onLoad(){
        super.onLoad();
        this.mRedGo.active = false;
    }
    
    public exe(target:FSprite,callback:()=>void){
        this.time = new Date().getTime();
        // this.sprite.setDir({x:0,y:0});

        this.mRedGo.active = true;
        let p1 = this.node.getPosition();
        let p2 = target.node.getPosition();
        let angle = CMath.getAngle(p1,p2);
        this.mRedGo.angle = angle*180/Math.PI;

        if(target instanceof PSprite){
            target.tangentMove(this.sprite.node);
        }

        cc.tween(this.node).sequence(
            cc.delayTime(this.dtime),
            cc.callFunc(()=>{
                this.mRedGo.active = false;
                this.moveGO(angle,callback);
            })
        ).start();
    }

    private moveGO(angle,callback:()=>void){
        this.sprite.playAction(SpriteActionType.atk,false,()=>{
            // this.AI.walk(this.range);
            this.sprite.playAction(SpriteActionType.stand,true)
        });
        let pos = cc.v2();
        let length = this.mRedGo.width;
        pos.x = length*Math.cos(angle);
        pos.y = length*Math.sin(angle);
       
        //copy当前碰撞区域，创建子弹打出去
        let boxCollider = this.node.getComponent(cc.PhysicsBoxCollider);
       
        let node = new cc.Node();
        node.x = this.node.x;
        node.y = this.node.y;
        node.group = 'bullet'
        let rigidBody = node.addComponent(cc.RigidBody);
        rigidBody.type = cc.RigidBodyType.Dynamic;
        // rigidBody.allowSleep = false;
        rigidBody.enabledContactListener = true;
        let physicsBoxCollider = node.addComponent(cc.PhysicsBoxCollider);
        physicsBoxCollider.sensor = true;
        physicsBoxCollider.size = boxCollider.size.clone();
        physicsBoxCollider.offset = boxCollider.offset.clone();
        
        let chargeCollision = node.addComponent(ChargeCollision);
        chargeCollision.skillBase = this;
        node.parent = this.sprite.ff.mMap.mSprites;


        cc.tween(this.node).sequence(
            cc.moveBy(this.ctime,pos),
            cc.callFunc(()=>{
            })
        ).start();

        cc.tween(node).sequence(
            cc.moveBy(this.ctime,pos),
            cc.callFunc(()=>{
                node.destroy();
                callback()
            })
        ).start();
    }
   
}
