import Sprite3D = Laya.Sprite3D;
import Vector3 = Laya.Vector3;
import { AssetManager } from "../Tools/AssetManager";
import { EventManager, StageState } from "../Tools/EventManager";
import { GameTools } from "../Tools/GameTools";
import { ChaseNpc } from "./ChaseNpc";
import { DataManager } from "./DataManager";
import { AccountManager } from "../Net/AccountManager";
import { GameManager } from "./GameManager";
import { StageControl } from "./StageControl";
import { WXSDK } from "../Net/WXSDK";
export enum HostageState{Run,Rescue,Arrest,Die }

export class Hostage extends Laya.Script{
    private static ins:Hostage;
    private m_hostagemodel:Sprite3D;
    private m_hostageanimator:Laya.Animator;
    private m_hostagestate:HostageState;
    //人质速度
    private _hostagespeed:number = 0;
    //追逐人质的敌人
    private enemy:Sprite3D;
    //游戏是否开始
    private begin:boolean = false;
    //是否遇到障碍物
    private isbarrier:boolean = false;
    public canmove:boolean = false;
    //是否死亡
    public isdead:boolean = false;
    //底部射线打到的东西
    private DownHit:Laya.HitResult = new Laya.HitResult();
    //前方射线打到的东西
    private FowardHit:Laya.HitResult = new Laya.HitResult();

    constructor(){
        super();
        Hostage.ins = this;
        EventManager.StageOn(StageState.Start,this,this.Begin);
        EventManager.StageOn(StageState.Lose,this,this.GameOver);
        EventManager.StageOn(StageState.Win,this,this.GameOver);
        EventManager.StageOn(StageState.Press,this,this.AddSpeed)
        EventManager.StageOn(StageState.UnPress,this,this.SlowSpeed)
    }
    public static get Instance():Hostage{
        if(Hostage.ins){
            return Hostage.ins
        }
        else{
            return new Hostage();
        }
    }
    onAwake(){
        this.m_hostagemodel = this.owner as Sprite3D;
        this.m_hostageanimator = this.m_hostagemodel.getComponent(Laya.Animator) as Laya.Animator;
        this.enemy = this.owner.parent.parent.getChildByName("enemy").getChildAt(0) as Sprite3D;

        this._hostagespeed = StageControl.Instance.curstage.hostspeed;
    }
    Begin(){
        this.ChangeState(HostageState.Run);
        // this.canmove = true;
        this.begin = true;
        // this.HelpPiaoZi();
    }
    currotV = new Vector3();
    hostagedir = new Vector3();
    onUpdate(){
        if(!this.begin)return;
        if(this.isdead){
            this.ChangeState(HostageState.Die)
            return
        }
        let npc = this.enemy.getComponent(ChaseNpc) as ChaseNpc;
        if(npc.isdead || this.enemy == null || this.enemy.destroyed){
            this.canmove = false;
            this.ChangeState(HostageState.Rescue);return
        }
        this.RayCheck();
        let target = this.LookforRoad();
        if(this.canmove){
            if(target){
                Vector3.subtract(target.transform.position,this.m_hostagemodel.transform.position,this.currotV);
                Vector3.normalize(this.currotV,this.currotV);
                this.m_hostagemodel.transform.lookAt(new Vector3(this.m_hostagemodel.transform.position.x-this.currotV.x,this.m_hostagemodel.transform.position.y,this.m_hostagemodel.transform.position.z-this.currotV.z),new Vector3(0,1,0));
                this.hostagedir = this.currotV;
                if(!this.isbarrier){
                    this.Move(this.currotV,this._hostagespeed)
                }
            }
            else{
                if(!this.isbarrier){
                    this.Move(new Vector3(0,0,1),this._hostagespeed)
                }
            }
        }
    }
    offest = new Vector3();
    curpos = new Vector3();


    //人质寻路
    LookforRoad():Laya.Sprite3D{
        var doorarr = [];
        for (let i = 0; i < DataManager.DoorArray.length; i++) {
            let _door = DataManager.DoorArray[i];
            if(this.m_hostagemodel.transform.position.z < _door.transform.position.z){
                doorarr.push(_door);
            }
        }
        for (let i = 0; i < doorarr.length; i++) {
            for (let j = 0; j < doorarr.length-i-1; j++) {
                var _dis = Vector3.distance(doorarr[i].transform.position,this.m_hostagemodel.transform.position);
                var _dis2 = Vector3.distance(doorarr[i+1].transform.position,this.m_hostagemodel.transform.position)
                if(_dis>_dis2){
                    let door1 = doorarr[i];
                    doorarr[i] = doorarr[i+1];
                    doorarr[i+1] = door1;
                }
            }
        }
        return doorarr[0];
    }
    curspeed = 0;
    Move(_dir:Vector3,_speed:number){
        let stage = Number(AccountManager.Instance.curplayerData.GainAccount("stage")); 
        if(stage == 1)return;
        if(this.canmove ){
            var sp = GameTools.Instance.lerp(this.curspeed,_speed,0.1);
            this.curspeed = sp;
            Vector3.scale(_dir,this.curspeed,this.offest);
            Vector3.add(this.m_hostagemodel.transform.position,this.offest,this.curpos);
            Vector3.lerp(this.m_hostagemodel.transform.position,this.curpos,0.15,this.curpos);
            this.curpos = new Vector3(this.curpos.x,this.curpos.y,this.curpos.z);
            this.m_hostagemodel.transform.position = this.curpos;
        }
    }
    AddSpeed(){
        this._hostagespeed = StageControl.Instance.curstage.hostspeed;
    }
    SlowSpeed(){
        this._hostagespeed = StageControl.Instance.curstage.hostspeed/2;
    }
    GameOver(){
        EventManager.StageOff(StageState.Press,this,this.AddSpeed);
        EventManager.StageOff(StageState.UnPress,this,this.SlowSpeed);
        EventManager.StageOff(StageState.Start,this,this.Begin);
        Laya.timer.clearAll(this);
        this.canmove = false;
    }
    ChangeState(_state:HostageState){
        if(this.m_hostagestate == _state)return;
        this.m_hostagestate = _state;
        switch (this.m_hostagestate) {
            case HostageState.Run:
                this.Run();
                break;
            case HostageState.Arrest:
                this.Arrest();
                break;
            case HostageState.Rescue:
                this.Rescue();
                break;
            case HostageState.Die:
                this.Die();
                break;
        }
    }
    Run(){
        this.m_hostageanimator.play("run");
    }
    Rescue(){
        this.m_hostageanimator.play("thank");
        this.PiaoZi();
    }
    Arrest(){
        this.m_hostageanimator.play("dierear");
        this.canmove = false;
    }
    Die(){
        WXSDK.Shake(true);
        this.m_hostageanimator.play("dierear");
        this.canmove = false;
        EventManager.StageOff(StageState.Start,this,this.Begin);
        Laya.timer.clearAll(this);
        
        EventManager.StageTrigger(StageState.Lose);
    }
    RayCheck(){
        if(this.FowardRayCheck){
            this.CrashBarrier();
            this.isbarrier = true
        }
        else{
            this.isbarrier = false;
        }
    }
    PiaoZi(){
        let smile = new Laya.Image();
        smile.skin = "Game/res/textrue/happy.png";
        smile.scaleX = 0.05;
        smile.scaleY = 0.05;
        smile.anchorX = 0.5;
        smile.anchorY = 0.5;
        Laya.stage.addChild(smile);
        Laya.timer.once(1000,this,()=>{
            smile.visible = false;
            Laya.timer.clear(this,this.UIFollow);
        })
        GameManager.Instance.UIArray.push(smile);
        let UIPos = this.m_hostagemodel.getChildByName("UIPos") as Laya.Sprite3D;
        let screenpos = new Vector3();
        Laya.timer.frameLoop(1,this,this.UIFollow,[UIPos,smile,screenpos]);
    }
    UIFollow(UIPos:Laya.Sprite3D,UI:Laya.Image,POS:Laya.Vector3){
        AssetManager.Instance.maincamera.worldToViewportPoint(UIPos.transform.position,POS);
        UI.pos(POS.x,POS.y);
    }
    // HelpPiaoZi(){
    //     let help = new Laya.Image();
    //     help.skin = "Game/res/textrue/help.png";
    //     help.scaleX = 0.5;
    //     help.scaleY = 0.5;
    //     Laya.stage.addChild(help);
        
    //     let screenpos = new Vector3();
    //     Laya.timer.frameLoop(1,this,()=>{
    //         AssetManager.Instance.maincamera.worldToViewportPoint(this.m_hostagemodel.transform.position,screenpos);
    //         help.pos(screenpos.x+2,screenpos.y+10);
    //     })
    //     // console.log("help的位置--",screenpos.x,screenpos.y);
    // }
    //撞到障碍物
    CrashBarrier(){
        var target = this.FowardHit.collider.owner.parent as Laya.Sprite3D;
        if(target.name == "stone"){
            this._hostagespeed = 0;
        }
        else if(target.name == "bonfire"){
            // this.ChangeState(HostageState.Arrest);
            // this.isdead = true;
        }
        else if(target.name == "big_fence"){
            this._hostagespeed = 0;
        }
        else if(target.name == "wood_Cylinder"){
            this._hostagespeed = 0;
        }
    }

    // /**竖直方向射线检测*/
    // get DownRayCheck():boolean{
    //     var isDownHit = false;
    //     var startPos:Vector3 = new Vector3(this.m_hostagemodel.transform.position.x,this.m_hostagemodel.transform.position.y+1.5,this.m_hostagemodel.transform.position.z+0.5);
    //     var direction:Vector3 = new Vector3(0,-1,0);
    //     var DownRay:Laya.Ray = new Laya.Ray(startPos,direction);
    //     if(AssetManager.Instance.mainscene.physicsSimulation.rayCast(DownRay,this.DownHit,100)){
    //         if (this.DownHit.collider.collisionGroup == 100) {
    //             isDownHit = true;
    //         }
    //     }
    //     return isDownHit;
    // }
    /**水平方向射线检测*/
    get FowardRayCheck():boolean{
        var isFowardHit = false;
        var startPos:Vector3 = new Vector3(this.m_hostagemodel.transform.position.x,this.m_hostagemodel.transform.position.y+1,this.m_hostagemodel.transform.position.z+0.5);
        var direction:Vector3 = new Vector3(0,0,1);
        var DownRay:Laya.Ray = new Laya.Ray(startPos,direction);
        if(AssetManager.Instance.mainscene.physicsSimulation.rayCast(DownRay,this.FowardHit,1)){
            if (this.FowardHit.collider.collisionGroup == 100) {
                isFowardHit = true;
            }
        }
        return isFowardHit;
    }


}