import Sprite3D = Laya.Sprite3D;
import Vector3 = Laya.Vector3;
import Transform3D = Laya.Transform3D;
import { GamePool, PoolType } from "../Game/GamePool";
import {MainRole} from "../Game/MainRole";
import { Scene3DManager } from "../Game/Scene3DManager";
import {CameraManager} from "./CameraManager";
import { MatrixTransform } from "../Util/MatrixTransform";
import {  MusicType } from "../Game/ColliderAndMusicType";
import { GlobalParam } from "../Net/GlobalParam";
import { MainRoleShot } from "../Game/MainRoleShot";
import {GameManager} from "../Game/GameManager";
import { PlayerManager } from "../Game/PlayerManager";
import { DispatcherManager, EventType } from "../Game/DispatcherManager";
import {MouseEvent} from "../Game/MouseEvent";
import {MateManager} from "./MateManager";
import {PlaneManager} from "./PlaneManager";
import { WXSdk } from "../Net/WXSdk";
import { SettingController, SoundType } from "../Game/SettingController";

import Stage = Laya.Stage;
import Text = Laya.Text;
import Browser = Laya.Browser;
import HScrollBar = Laya.HScrollBar;
import VScrollBar = Laya.VScrollBar;
import Handler = Laya.Handler;
import WebGL = Laya.WebGL;


export  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 playerScript: MainRole;
    public isover = false;
    public Init(startPos: Sprite3D, playerCon: Sprite3D) {
        this.playerStartTra = startPos.transform;
        this.playerContainer = playerCon;
    }

    //更换玩家模型
    ChangeModel(){
        if(this.player) GamePool.Instance.RecoverModel(this.player);
        let p = GamePool.Instance.GetModel(GamePool.modeltype.Player + PlayerManager.Instance.equipId);
        if (p) {
            this.player = p;
            this.SetMatePos(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.playerScript = ps;
            else this.playerScript = this.player.addComponent(MainRole);
        }
    }

    public MateArrPosition: Array<any>;
    /**
     * 设置friend的位置
     */
    private SetMatePos(player: Sprite3D) {
        this.MateArrPosition = [];
        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.MateArrPosition.push(data);
        }
    }

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

/*************************************************************** */
    private createTexts(): void {
        var t1: Text = this.createText();
        t1.overflow = Text.VISIBLE;
        t1.pos(10, 10);

        var t2: Text = this.createText();
        t2.overflow = Text.SCROLL;
        t2.pos(10, 110);
        var t3: Text = this.createText();
        t3.overflow = Text.HIDDEN;
        t3.pos(10, 210);
    }
    private createText(): Text {
        var txt: Text = new Text();
        txt.text =
            "Layabox是HTML5引擎技术提供商与优秀的游戏发行商，面向AS/JS/TS开发者提供HTML5开发技术方案！\n" +
            "Layabox是HTML5引擎技术提供商与优秀的游戏发行商，面向AS/JS/TS开发者提供HTML5开发技术方案！\n" +
            "Layabox是HTML5引擎技术提供商与优秀的游戏发行商，面向AS/JS/TS开发者提供HTML5开发技术方案！";
        txt.borderColor = "#FFFF00";
        txt.size(300, 50);
        txt.fontSize = 20;
        txt.color = "#ffffff";
        Laya.stage.addChild(txt);
        return txt;
    }
/*************************************************************** */

   

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

   
    /**
     * 停止创建子弹
     */
    private isClickCom = true;
    private isend = true;
    public CreateOver(isgameover = false) {
        this.isend = true;
        if (!isgameover)
            DispatcherManager.event(EventType.Event.StopShot);
    }
    public IsShoot() {
        return !this.isend;
    }

    /**
     * 到达终点destination
     */
    Destination() {
        MouseEvent.Instance.OnClickUp();
        MainRoleManager.Instance.CreateOver();
        MouseEvent.Instance._Switch = false;
        GameManager.Instance.Near();
        if (!this.playerScript) return;
        this.playerScript.Near();
    }
    NearIsdead() {
        if (!this.playerScript) return true;
        return this.playerScript.isdead;
    }
    Near(count, z: number) {
        if (!this.playerScript) return;
        if (count == 1) {
            this.playerScript.Defense(new Vector3(0, 0, z));
        } else {
            this.playerScript.Defense(new Vector3(-GlobalParam.arriveStandWidth, 0, z));
        }
    }

    Attack() {
        if (!this.playerScript) return;
        this.isover = true;
        this.playerScript.Attack();
    }


     /**
     * 创建子弹
     */
    public CreateShoot(isgameover = false) {
        if (!this.playerScript) return;
        this.isend = false;
        // if (!isgameover)
        //     DispatcherManager.event(EventType.Event.StartShot);
        if (!this.isClickCom) return;
        console.log("开始创建子弹");
        this.isClickCom = false;
        this._CreateShoot();
        Laya.timer.loop(PlayerManager.bulletTime * 1000, this, this._Loop);
    }
    _Loop() {
        if (this.isend) {
            Laya.timer.clear(this, this._Loop);
            this.isClickCom = true;
            return;
        }
        this._CreateShoot();
    }
    private _CreateShoot() {
        WXSdk.ShortVibrate();
        SettingController.Instance.PlaySound(SoundType.hit);
        let bulletPos = this.playerScript.CreateBullet();
        if (bulletPos == null) return;
        let bu = GamePool.Instance.GetModel(GamePool.modeltype.PlayerShoot);
        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.Start(bulletPos, this.isover);
        }
    }

    /**
     * 检测游戏是否结束
     */
    CheckGameOver(isplayer?) {
        if (isplayer) {
            let count = MateManager.Instance.NearDestination();
            if (count == 0) {
                this.playerScript.Near();
                GameManager.Instance.Over();
            }
        } else {
            let count = MateManager.Instance.NearDestination();
            if (count == 0) {
                let isplayerdead = this.playerScript.isdead;
                if (isplayerdead) {
                    this.playerScript.Near();
                    GameManager.Instance.Over();
                }
            }
        }
    }

    GoToTiaoWu() {
        if (!this.playerScript) return;
        let t = PlaneManager.Instance.GetWuDaoPosition();
        if (!t) return;
        this.playerScript.TiaoWu(t);
    }

    Reset() {
        for (let index = 0; index < this.MateArrPosition.length; index++) {
            const element = this.MateArrPosition[index];
            element["ishave"] = false;
        }
        this.isover = false;
        if (!this.playerScript) return;
        this.playerScript.Reset();
    }

    //隐藏
    HidePlayer(){
       if(this.player)this.player.active=false;
    }

    /************************************************************* */
    private onSkinLoadComplete(): void {
        this.placeHScroller();
        this.placeVScroller();
    }
    private placeHScroller(): void {
        var hs: HScrollBar = new HScrollBar();
        hs.skin = "res/ui/hscroll.png";
        hs.width = 300;
        hs.pos(50, 170);
        hs.min = 0;
        hs.max = 100;
    }
    private placeVScroller(): void {
        var vs: VScrollBar = new VScrollBar();
        vs.skin = "res/ui/vscroll.png";
        vs.height = 300;
        vs.pos(400, 50);
        vs.min = 0;
        vs.max = 100;
        Laya.stage.addChild(vs);
    }
    /************************************************************* */

    public MadePlayer() {
        let p = GamePool.Instance.GetModel(GamePool.modeltype.Player + PlayerManager.Instance.equipId);
        if (p) {
            this.player = p;
            this.SetMatePos(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.playerScript = ps;
            else this.playerScript = this.player.addComponent(MainRole);
        }else{
            console.error("player不存在")
        }
    }
    SetPlayerPosition() {
        this.player.active=true;
        this.playerTra.position = this.playerStartTra.position.clone();
        this.playerTra.rotationEuler = this.playerStartTra.rotationEuler.clone();
        this.playerScript.PlayAni(MusicType.Idle, 1);
    }


     /**
     * 鼠标点击瞬移
     */
    private _maincamera: Laya.Camera;
    private _distance: number;
    private _posy: number;
    public SetModelPos(x) {
        if(!this.player){
            this.MadePlayer();
            this.SetPlayerPosition();
        }
        if (!this._maincamera) {
            this._maincamera = CameraManager.Instance._maincamera;
            this._distance = -Vector3.distance(this.playerTra.position, this._maincamera.transform.position);
            this._posy = MatrixTransform.WorldToScreen2(this._maincamera, this.playerTra.position).y;
        }
        let uiP = new Vector3(x, this._posy, this._distance);
        let p = MatrixTransform.ScreenToWorld(this._maincamera, uiP);
        this.playerTra.localPositionX = p.x;
    }

    public Start() {
        if (this.playerScript) {
            this.playerScript.Start();
            this.playerScript.PlayAni(MusicType.RunAndGun, 2);
        }
    }

}