

import Sprite3D = Laya.Sprite3D;
import Transform3D = Laya.Transform3D;
import Vector3 = Laya.Vector3;
// import { AnimatorClip } from "./ColliderAndMusicType";
import { MathTool } from "../Util/MathTool";
import {CameraManager} from "../Manager/CameraManager";
import { GlobalParam } from "../Net/GlobalParam";
import { Scene3DManager } from "./Scene3DManager";
import Quaternion = Laya.Quaternion;
import {MateManager} from "../Manager/MateManager";
import { GamePool } from "./GamePool";
import { MainRoleShot } from "./MainRoleShot";
import {MainRoleManager} from "../Manager/MainRoleManager";
import { DispatcherManager, EventType } from "./DispatcherManager";
import { ParticleManager } from "./ParticleManager";
import {RoleManager} from "../Manager/RoleManager";
import { PlayerManager } from "./PlayerManager";
import {GameManager} from "./GameManager";
import { MusicType } from "./ColliderAndMusicType";

import Sprite = Laya.Sprite;
import Stage = Laya.Stage;
import Text = Laya.Text;
import Stat = Laya.Stat;
import WebGL = Laya.WebGL;

export  class Mate extends Laya.Script3D {
    public selfobj: Sprite3D;
    public tran: Transform3D;
    public animator: Laya.Animator;
    public forW: Vector3;
    private quaternion1: Quaternion;
    private rayPoint: Transform3D;
    private bulletPos: Transform3D;
    private speed: number;
    private _up = new Vector3(0, 1, 0);
    onAwake() {
        this.selfobj = this.owner as Sprite3D;
        this.tran = this.selfobj.transform;
        this.animator = this.selfobj.getChildAt(0).getComponent(Laya.Animator);
        this.rayPoint = (this.selfobj.getChildByName("rayPoint") as Sprite3D).transform;
        this.bulletPos = (this.selfobj.getChildByName("bulletPos") as Sprite3D).transform;
        this.forW = MathTool.VecZero;
        this.speed = GlobalParam.matespeed;
        this.quaternion1 = new Quaternion();
    }
    
    /******************************************* */
    private setup(): void {
        var textBox: Sprite = new Sprite();

        // 随机摆放文本
        var text: Text;
        for (var i: number = 0; i < 1000; i++) {
            text = new Text();
            text.fontSize = 20;
            text.text = (Math.random() * 100).toFixed(0);
            text.rotation = Math.random() * 360;
            text.color = "#CCCCCC";

            text.x = Math.random() * Laya.stage.width;
            text.y = Math.random() * Laya.stage.height;

            textBox.addChild(text);
        }
        //缓存为静态图像
        textBox.cacheAs = "bitmap";
        Laya.stage.addChild(textBox);
    }
    /******************************************* */


    //试用成功添加同伴
    TrialAdd(dataPar) {
        this.AnimatorPlayByType(MusicType.Idle, 1);
        this.dataPar = dataPar;
        this.dataPar["ishave"] = true;
        this.isClickCom = true;
        this.isStop = true;
        this.isreturn = true;
        this.isover=false;
        MateManager.Instance.AddModelToDic(this.selfobj.id, this);
        this.ShootFunc();
        if (MainRoleManager.Instance.IsShoot()) this.CreateShoot();
        Laya.timer.frameLoop(1, this, this.Move);
    }

    private dataPar: any;
    private tar: Sprite3D;
    private tarTra: Transform3D;
    SetTar() {
        this.isreturn = false;
        this.isClickCom = true;
        this.isStop = true;
        this.isover = false;
        this.AnimatorPlayByType(MusicType.Idle,1);
        DispatcherManager.off(EventType.Event.StopShot, this, this.StopCreate);
    }

    /**
     * 落地
     */
    FallDown() {
        let tween = Laya.Tween.to(this.tran, { localPositionY: 0 }, 400, Laya.Ease.quintIn, Laya.Handler.create(this, () => {
            let dataPar = MainRoleManager.Instance.GetMatePos();
            if (!dataPar) { console.warn("friendPar没有位置了"); return; }
            this.dataPar = dataPar;
            this.dataPar["ishave"] = true;
            this.tar = this.dataPar["sp"];
            this.tarTra = this.tar.transform;
            //this.tran.position
            tween.clear();
            this.Start();
        }, null, false));
    }

    private isreturn = false;
    private isover = false;
    Start() {
        this.AnimatorPlayByType(MusicType.RunAndGun, 2);
        this.isreturn = false;
        this.isClickCom = true;
        this.isStop = true;
        this.isover = false;
        Laya.timer.frameLoop(1, this, this.Move);
    }
    
    ArriveTarPos() {
        //if(GameManager.Instance.gameisover)return;
        this.isClickCom = true;
        this.isStop = true;
        this.isreturn = true;
        this.tar.addChild(this.selfobj);
        this.tran.localPosition = MathTool.VecZero;
        this.AnimatorPlayByType(MusicType.RunAndGun, 2);
        MateManager.Instance.AddModelToDic(this.selfobj.id, this);
        let tween = Laya.Tween.to(this.tran, { localRotationEulerY: 0 }, 100, Laya.Ease.quintIn, Laya.Handler.create(this, () => {
            tween.clear();
            this.tran.localRotationEuler = MathTool.VecZero;
            this.ShootFunc();
           // if (MainRoleManager.Instance.IsBulleting()) 
            this.CreateShoot();
        }, null, false));
    }

    private _scene;
    private rayF: Laya.Ray;
    private outHitF: Laya.HitResult;
    private rayL: Laya.Ray;
    private outHitL: Laya.HitResult;
    private rayR: Laya.Ray;
    private outHitR: Laya.HitResult;
    private RayReset() {
        //if(GameManager.Instance.gameisover)return;
        let origP = this.rayPoint.position;
        if (!this._scene) {
            this._scene = Scene3DManager.Instance.MainScene;
        }
        //前面的射线
        if (!this.rayF) {
            this.rayF = new Laya.Ray(MathTool.VecZero, new Vector3(0, 0, 1));
            this.outHitF = new Laya.HitResult();
        }
        this.rayF.origin = origP;
        let isHItF = this._scene.physicsSimulation.rayCast(this.rayF, this.outHitF, GlobalParam.playerRayLengthF);
        if (isHItF) {
            let obj = this.outHitF.collider.owner as Sprite3D;
            //console.log("前面的射线碰撞");
            this.Dead(this.outHitF.point);
            return;
        }
        //左边的射线
        if (!this.rayL) {
            this.rayL = new Laya.Ray(MathTool.VecZero, new Vector3(1, 0, 0));
            this.outHitL = new Laya.HitResult();
        }
        this.rayL.origin = origP;
        let isHItL = this._scene.physicsSimulation.rayCast(this.rayL, this.outHitL, GlobalParam.playerRayLengthLR);
        if (isHItL) {
            let obj = this.outHitL.collider.owner as Sprite3D;
            //console.log("左边的射线碰撞")
            this.Dead(this.outHitL.point);
            return;
        }
        //右边的射线
        if (!this.rayR) {
            this.rayR = new Laya.Ray(MathTool.VecZero, new Vector3(-1, 0, 0));
            this.outHitR = new Laya.HitResult();
        }
        this.rayR.origin = origP;
        let isHItR = this._scene.physicsSimulation.rayCast(this.rayR, this.outHitR, GlobalParam.playerRayLengthLR);
        if (isHItR) {
            let obj = this.outHitR.collider.owner as Sprite3D;
            //console.log("右边的射线碰撞")
            this.Dead(this.outHitR.point);
            return;
        }
    }

    /***************************************************************** */
    private ape1: Sprite;
    private ape2: Sprite;
    private createApes(): void {
        //显示两只猩猩
        this.ape1 = new Sprite();
        this.ape2 = new Sprite();
        this.ape1.loadImage("res/apes/monkey2.png");
        this.ape2.loadImage("res/apes/monkey2.png");

        this.ape1.pivot(55, 72);
        this.ape2.pivot(55, 72);

        this.ape1.pos(Laya.stage.width / 2, Laya.stage.height / 2);
        this.ape2.pos(200, 0);

        //一只猩猩在舞台上，另一只被添加成第一只猩猩的子级
        Laya.stage.addChild(this.ape1);
        this.ape1.addChild(this.ape2);

        Laya.timer.frameLoop(1, this, this.animate);
    }
    private animate(e: Event): void {
        this.ape1.rotation += 2;
        this.ape2.rotation -= 4;
    }
    /***************************************************************** */


    Move() {
        //if(GameManager.Instance.gameisover)return;
        if (this.isreturn) {
            this.RayReset(); return;
        }
        let tarPos = this.tarTra.position.clone();
        Vector3.subtract(tarPos, this.tran.position, this.forW);
        Vector3.normalize(this.forW, this.forW);
        this.forW = new Vector3(this.forW.x * this.speed, this.forW.y * this.speed, this.forW.z * this.speed);
        this.tran.translate(this.forW, false);
        if (Vector3.distance(this.tran.position, tarPos) < 0.1) {
            this.ArriveTarPos();
            return;
        }
        Quaternion.lookAt(tarPos, this.tran.position, this._up, this.quaternion1);
        this.quaternion1.invert(this.quaternion1);
        Quaternion.slerp(this.tran.rotation, this.quaternion1, 0.1, this.quaternion1);
        this.tran.rotation = this.quaternion1.clone();
    }

    public AnimatorPlayByType(clip: string, speed, callback?) {
        this.animator.play(clip);
        if (!speed) speed = 1;
        this.animator.speed = speed;
    }

    ShootFunc() {
        DispatcherManager.on(EventType.Event.StopShot, this, this.StopCreate);
    }

    LoopCreate() {
        //if(GameManager.Instance.gameisover)return;
        if (this.isStop) {
            Laya.timer.clear(this, this.LoopCreate);
            this.isClickCom = true;
            return;
        }
        this._CreateShoot();
    }
    /**
     * 创建子弹
     */
    public CreateShoot() {
        this.isStop = false;
        if (!this.isClickCom) return;
        this.isClickCom = false;
        this._CreateShoot();
        Laya.timer.loop(PlayerManager.bulletTime * 2 * 1000, this, this.LoopCreate);

    }
    private _CreateShoot() {
        //  let bulletPos = this.playerBehavior.CreateBullet();
        let bu = GamePool.Instance.GetModel(GamePool.modeltype.PlayerShoot);
        if (bu) {
            Scene3DManager.Instance.bulletCon.addChild(bu);
            bu.transform.position = this.bulletPos.position.clone();
            bu.transform.localRotationEuler = this.bulletPos.rotationEuler.clone();
            let pb: MainRoleShot = bu.getComponent(MainRoleShot);
            if (!pb) pb = bu.addComponent(MainRoleShot) as MainRoleShot;
            pb.Start(this.bulletPos, this.isover);
        }
    }
    /**
     * 停止创建子弹
     */
    private isClickCom = true;
    private isStop = true;
    public StopCreate() {
        this.isStop = true;
    }
    Dead(pos) {
        //if(GameManager.Instance.gameisover)return;
        if (this.dataPar)
            this.dataPar["ishave"] = false;
        ParticleManager.Instance.BloodEffect(pos);
        MateManager.Instance.RemoveModelToDic(this.selfobj);
        this.Recover();
        MainRoleManager.Instance.CheckGameOver();
    }

    SetPar() {
        let t = this.tran.position.clone();
        MainRoleManager.Instance.playerContainer.addChild(this.selfobj);
        this.tran.position = t.clone();
    }
    
    private r;
    private danceP: Vector3;
    TiaoWu(sp: Transform3D) {

        this.AnimatorPlayByType(MusicType.RunAndGun, 2);
        this.danceP = sp.position.clone();
        this.r = sp.rotationEuler.clone();
        Laya.timer.frameLoop(1, this, this._TiaoWu);

    }
    _TiaoWu() {
        Vector3.subtract(this.danceP, this.tran.position, this.forW);
        Vector3.normalize(this.forW, this.forW);
        this.forW = new Vector3(this.forW.x * 0.15, this.forW.y * 0.15, this.forW.z * 0.15);
        this.tran.translate(this.forW);
        if (Vector3.distance(this.tran.position, this.danceP) < 0.15) {
            Laya.timer.clear(this, this._TiaoWu);
            this.tran.position = this.danceP.clone();
            this.tran.rotationEuler = this.r.clone();
            this.AnimatorPlayByType(MusicType.Dance, 1);
            return;
        }
        Quaternion.lookAt(this.danceP, this.tran.position, this._up, this.quaternion1);
        this.quaternion1.invert(this.quaternion1);
        this.tran.rotation = this.quaternion1.clone();
    }

    
    /***************************************************** */
    private texture1: string = "res/apes/monkey2.png";
    private texture2: string = "res/apes/monkey3.png";
    private flag: boolean = false;

    private ape: Sprite;
    private onAssetsLoaded(): void {
        this.ape = new Sprite();
        Laya.stage.addChild(this.ape);
        this.ape.pivot(55, 72);
        this.ape.pos(Laya.stage.width / 2, Laya.stage.height / 2);
    }
    /***************************************************** */

    private enemyTar: Sprite3D;
    Attack() {
        Laya.timer.clear(this, this._Defense);
        this.isover = true;
        this.isFristShoot = true;
        this.enemyTar = null;
        Laya.timer.frameLoop(1, this, this._attack)
    }
    private isFristShoot = true;
    private ATKp: Vector3;
    _attack() {
        if (this.enemyTar == null) {
            this.enemyTar = RoleManager.Instance.GetOpponent();
            if (this.enemyTar != null) {
                this.ATKp = this.enemyTar.transform.position.clone();
                Quaternion.lookAt(this.ATKp, this.tran.position, this._up, this.quaternion1);
                this.quaternion1.invert(this.quaternion1);
                this.tran.rotation = this.quaternion1.clone();
            }
        } else {
            if (!this.enemyTar.active) {
                this.enemyTar = RoleManager.Instance.GetOpponent();
                if (this.enemyTar != null) {
                    this.ATKp = this.enemyTar.transform.position.clone();
                    Quaternion.lookAt(this.ATKp, this.tran.position, this._up, this.quaternion1);
                    this.quaternion1.invert(this.quaternion1);
                    this.tran.rotation = this.quaternion1.clone();
                }
            }
            if (this.enemyTar == null) {
                this.StopCreate();
                this.isFristShoot = true;
                return;
            }
            if (this.isFristShoot) {
                this.isFristShoot = false;

                this.CreateShoot();
            }

            this.ATKp = this.enemyTar.transform.position.clone();
            Quaternion.lookAt(this.ATKp, this.tran.position, this._up, this.quaternion1);
            this.quaternion1.invert(this.quaternion1);
            this.tran.rotation = this.quaternion1.clone();
        }
    }


    
    private ts = new Vector3(0, 0, 0.01);
    private tp: Vector3;
    _Defense() {
        Vector3.subtract(this.tp, this.tran.position, this.forW);
        Vector3.normalize(this.forW, this.forW);
        this.forW = new Vector3(this.forW.x * 0.15, this.forW.y * 0.15, this.forW.z * 0.15);
        this.tran.translate(this.forW, false);
        if (Vector3.distance(this.tran.position, this.tp) < 0.1) {
            Laya.timer.clear(this, this._Defense);
            let tween = Laya.Tween.to(this.tran, { localRotationEulerY: 0 }, 100, Laya.Ease.quintIn, Laya.Handler.create(this, () => {
                tween.clear();
            }, null, false));
            return;
        }
        Quaternion.lookAt(this.tp, this.tran.position, this._up, this.quaternion1);
        this.quaternion1.invert(this.quaternion1);
        this.tran.rotation = this.quaternion1.clone();
    }

    Defense(pos) {
        this.SetPar();
        this.tp = pos;
        Quaternion.lookAt(pos, this.tran.position, this._up, this.quaternion1);
        this.quaternion1.invert(this.quaternion1);
        this.tran.rotation = this.quaternion1.clone();
        this.AnimatorPlayByType(MusicType.CrouchFiring, 1);
        Laya.timer.frameLoop(1, this, this._Defense);
    }


    Recover() {
        if(this.dataPar){
            this.dataPar["ishave"] = false;
            this.dataPar = null;
        }
        MateManager.Instance.RecoverMateModel(this.selfobj);
        MateManager.Instance.RemoveModelToDic(this.selfobj);
      
        Laya.timer.clearAll(this);
        Laya.Tween.clearAll(this);
       // DispatcherManager.off(EventType.Event.StartShot, this, this.CreateBullet);
        DispatcherManager.off(EventType.Event.StopShot, this, this.StopCreate);
        GamePool.Instance.RecoverModel(this.selfobj);
    }

}