import Sprite3D = Laya.Sprite3D;
import Vector3 = Laya.Vector3;
import Transform3D = Laya.Transform3D;
import { GamePool, PoolType } from "../GameLogic/GamePool";
import MainRole from "../GameLogic/MainRole";
import { Scene3DManager } from "../GameLogic/Scene3DManager";
import CameraManager from "./CameraManager";
import { MatrixTransform } from "../Util/MatrixTransform";
import {  MusicType } from "../GameLogic/ColliderAndMusicType";
import { Mathf } from "../Util/Mathf";
import { GlobalVariable } from "../game_module/GlobalVariable";
import { MainRoleShot } from "../GameLogic/MainRoleShot";
import GameManager from "../GameLogic/GameManager";
import { PlayerManager } from "../GameLogic/PlayerManager";
import { DispatcherManager, EventType } from "../GameLogic/DispatcherManager";
import MouseEvent from "../GameLogic/MouseEvent";
import MateManager from "./MateManager";
import PlaneManager from "./PlaneManager";
import { WXSdk } from "../game_module/WXSdk";
import { SettingController, SoundType } from "../GameLogic/SettingController";
export default class MainRoleManager {
    private static instance: MainRoleManager;
    public static get Instance(): MainRoleManager {
        return this.instance || (this.instance = new MainRoleManager());
    }

    public playerContainer: Sprite3D;
    public playerStartTra: Transform3D;
    public player: Sprite3D;
    public playerTra: Transform3D;
    public playerBehavior: MainRole;
    public isover = false;
    public Init(startPos: Sprite3D, playerCon: Sprite3D) {
        this.playerStartTra = startPos.transform;
        this.playerContainer = playerCon;
    }

    public CreatePlayer() {
        let p = GamePool.Instance.SetActiveObject(GamePool.pooltype.player + PlayerManager.Instance.equipId);
        if (p) {
            this.player = p;
            this.SetFriendPoint(p);
            this.playerTra = this.player.transform;
            this.playerTra.position = this.playerStartTra.position.clone();
            this.playerTra.rotationEuler = this.playerStartTra.rotationEuler.clone();
            this.playerContainer.addChild(this.player);
            let ps = this.player.getComponent(MainRole);
            if (ps) this.playerBehavior = ps;
            else this.playerBehavior = this.player.addComponent(MainRole);
        }else{
            console.error("player不存在")
        }
    }
    InitPlayerPos() {
        this.player.active=true;
        this.playerTra.position = this.playerStartTra.position.clone();
        this.playerTra.rotationEuler = this.playerStartTra.rotationEuler.clone();
        this.playerBehavior.PlayAni(MusicType.Idle, 1);
    }

    ChangePlayer(){
        if(this.player) GamePool.Instance.SetDisableObject(this.player);
        let p = GamePool.Instance.SetActiveObject(GamePool.pooltype.player + PlayerManager.Instance.equipId);
        if (p) {
            this.player = p;
            this.SetFriendPoint(p);
            this.playerTra = this.player.transform;
            this.playerTra.position = this.playerStartTra.position.clone();
            this.playerTra.rotationEuler = this.playerStartTra.rotationEuler.clone();
            this.playerContainer.addChild(this.player);
            let ps = this.player.getComponent(MainRole);
            if (ps) this.playerBehavior = ps;
            else this.playerBehavior = this.player.addComponent(MainRole);
        }
    }

    public FriendArrPos: Array<any>;
    /**
     * 设置friend的位置
     */
    private SetFriendPoint(player: Sprite3D) {
        this.FriendArrPos = [];
        let par = player.getChildByName("FriendSpawPos") as Sprite3D;
        if (!par) console.error("friend父物体不存在");
        for (let index = 0; index < par.numChildren; index++) {
            let data = {};
            data["ishave"] = false;
            data["sp"] = par.getChildAt(index);
            this.FriendArrPos.push(data);
        }
    }

    /**
     * 获取friend所占的位置
     */
    public GetFrindPar() {
        for (let index = 0; index < this.FriendArrPos.length; index++) {
            const element = this.FriendArrPos[index];
            if (!element["ishave"])
                return element;
        }
        return null;
    }



    /**
     * 鼠标点击瞬移
     */
    private _camera: Laya.Camera;
    private _dis: number;
    private _y: number;
    public SetPlayerPos(x) {
        if(!this.player){
            this.CreatePlayer();
            this.InitPlayerPos();
        }
        if (!this._camera) {
            this._camera = CameraManager.Instance._camer;
            this._dis = -Vector3.distance(this.playerTra.position, this._camera.transform.position);
            this._y = MatrixTransform.WorldToScreen2(this._camera, this.playerTra.position).y;
        }
        let uiP = new Vector3(x, this._y, this._dis);
        let p = MatrixTransform.ScreenToWorld(this._camera, uiP);
        this.playerTra.localPositionX = p.x;
    }

    public StartGame() {
        if (this.playerBehavior) {
            this.playerBehavior.StartMove();
            this.playerBehavior.PlayAni(MusicType.RunAndGun, 2);
        }
    }

    public SliderPlayer(offsetX: number) {
        let x = offsetX.toFixed(2);  // 输出结果为 2.45
        let x1 = Number(x) * GlobalVariable.sliderFactor;
        if (this.playerBehavior) this.playerBehavior.Slider(x1);
    }

    /**
     * 创建子弹
     */
    public CreateBullet(isgameover = false) {
        if (!this.playerBehavior) return;
        this.isStop = false;
        // if (!isgameover)
        //     DispatcherManager.event(EventType.Event.StartShot);
        if (!this.isClickCom) return;
        console.log("开始创建子弹");
        this.isClickCom = false;
        this._CreateBullet();
        Laya.timer.loop(PlayerManager.bulletTime * 1000, this, this.LoopCreate);

    }
    LoopCreate() {
        if (this.isStop) {
            Laya.timer.clear(this, this.LoopCreate);
            this.isClickCom = true;
            return;
        }
        this._CreateBullet();
    }
    private _CreateBullet() {
        WXSdk.ShortVibrate();
        SettingController.Instance.PlaySound(SoundType.hit);
        let bulletPos = this.playerBehavior.CreateBullet();
        if (bulletPos == null) return;
        let bu = GamePool.Instance.SetActiveObject(GamePool.pooltype.PlayerBullet);
        if (bu) {
            Scene3DManager.Instance.bulletCon.addChild(bu);
            bu.transform.position = bulletPos.position.clone();
            bu.transform.localRotationEuler = bulletPos.rotationEuler.clone();
            let pb: MainRoleShot = bu.getComponent(MainRoleShot);
            if (!pb) pb = bu.addComponent(MainRoleShot) as MainRoleShot;
            pb.StartMove(bulletPos, this.isover);
        }
    }
    /**
     * 停止创建子弹
     */
    private isClickCom = true;
    private isStop = true;
    public StopCreate(isgameover = false) {
        this.isStop = true;
        if (!isgameover)
            DispatcherManager.event(EventType.Event.StopShot);
    }
    public IsBulleting() {
        return !this.isStop;
    }


    /**
     * 到达终点
     */
    ArriveFinal() {
        MouseEvent.Instance.OnClickUp();
        MainRoleManager.Instance.StopCreate();
        MouseEvent.Instance._Switch = false;
        GameManager.Instance.Arrive();
        if (!this.playerBehavior) return;
        this.playerBehavior.Arrive();
    }
    ArriveIsdead() {
        if (!this.playerBehavior) return true;
        return this.playerBehavior.isdead;
    }
    ToArrive(count, z: number) {
        if (!this.playerBehavior) return;
        if (count == 1) {
            this.playerBehavior.ToStand(new Vector3(0, 0, z));
        } else {
            this.playerBehavior.ToStand(new Vector3(-GlobalVariable.arriveStandWidth, 0, z));
        }
    }

    StartAtkEnemy() {
        if (!this.playerBehavior) return;
        this.isover = true;
        this.playerBehavior.StartAtkEnemy();
    }

    /**
     * 检测游戏是否结束
     */
    CheackGame(isplayer?) {
        if (isplayer) {
            let count = MateManager.Instance.GetArrive();
            if (count == 0) {
                this.playerBehavior.Arrive();
                GameManager.Instance.GameOver();
            }
        } else {
            let count = MateManager.Instance.GetArrive();
            if (count == 0) {
                let isplayerdead = this.playerBehavior.isdead;
                if (isplayerdead) {
                    this.playerBehavior.Arrive();
                    GameManager.Instance.GameOver();
                }
            }
        }
    }

    GoToDance() {
        if (!this.playerBehavior) return;
        let t = PlaneManager.Instance.GetDancePos();
        if (!t) return;
        this.playerBehavior.Dance(t);
    }

    Reset() {
        for (let index = 0; index < this.FriendArrPos.length; index++) {
            const element = this.FriendArrPos[index];
            element["ishave"] = false;
        }
        this.isover = false;
        if (!this.playerBehavior) return;
        this.playerBehavior.Reset();
    }
    SetActiveFalse(){
       if(this.player)this.player.active=false;
    }

}