import { ui } from "../ui/layaMaxUI";
import { GameTools } from "../Tool/GameTools";
import { SC } from "./ViewManager";
import { EventManager, PropEffecf,StageMode } from "../Tool/EventManager";
import { AccountManager } from "../Net/AccountManager";
import Ball from "../Main/Ball";
import { GameManager } from "../Main/GameManager";
import { DropRule } from "../Tool/DropRule";
import { ServerManager, BlastToMerge } from "../Net/ServerManager";

export default class InGameView extends ui.InGameSceneUI implements SC{
    private static ins:InGameView;
    //本关卡
    public STAGE:number;
    //是否弹出失败界面
    public LoseView = false;
    //是否弹出成功界面
    public WinView = false;
    constructor(){
        super();
        InGameView.ins = this;
        EventManager.StageOn(StageMode.Clone,this,this.AddPrefab);
        EventManager.StageOn(StageMode.Win,this,this.Win);
        EventManager.StageOn(StageMode.Lose,this,this.Lose);
        EventManager.StageOn(StageMode.ReStart,this,this.ReStart);
        EventManager.StageOn(StageMode.Over,this,this.Over);
        EventManager.StageOn(StageMode.Revive,this,this.Revive);
        EventManager.StageOn(StageMode.Check,this,this.Check);
    }
    public static get Instance():InGameView{
        if(InGameView.ins){
            return InGameView.ins
        }
        else{
            return new InGameView();
        }
    }
    Show(){
        let stage = AccountManager.Instance.curplayerData.GainAccount("stage");
        this.STAGE = Number(stage);
        Laya.timer.loop(AccountManager.Instance.curplayerData.Save * 1000,this,this.Save);
        Laya.timer.once(200,this,this.SkillRefresh);
        Laya.timer.frameLoop(2,this,this.CheckHeight);
        Laya.timer.frameLoop(1,this,this.Progress);
        Laya.timer.once(AccountManager.Instance.curplayerData.CheckLose * 1000,this,this.CheckLose);
        Laya.timer.frameLoop(500,this,this.SkillAnimation);
        this.ScoreRefresh();
        this.SkillNumRefresh();
        this.arrowbtn.clickHandler = new Laya.Handler(this,this.ClickArrow);
        this.zhunxin1btn.clickHandler = new Laya.Handler(this,this.ClickZhunXin1);
        this.zhunxin2btn.clickHandler = new Laya.Handler(this,this.ClickZhunXin2);
        this.doublebtn.clickHandler = new Laya.Handler(this,this.ClickDouble);
        this.hammerbtn.clickHandler = new Laya.Handler(this,this.ClickHammer);
        this.height = Laya.stage.height; 
        this.BG.height = Laya.stage.height;
        Laya.stage.on(Laya.Event.RESIZE,this,()=>
        {
            this.height = Laya.stage.height;
            this.BG.height = Laya.stage.height;
        })
    }
    //失败检测
    Check(){
        Laya.timer.clear(this,this.CheckLose);
        Laya.timer.once(AccountManager.Instance.curplayerData.CheckLose * 1000,this,this.CheckLose);
    }
    //添加预设
    AddPrefab(ball){
        this.prefabbox.addChild(ball);
    }
    //检测高度
    CheckHeight(){
        if(GameManager.Instance.CheckHeight){
            let down = false;
            for (let i = 0; i < this.prefabbox.numChildren; i++) {
                let child = this.prefabbox.getChildAt(i) as Laya.Image;
                if(child.y < DropRule.Instance.DropHeight){
                    down = true;
                }
            }
            if(!down){
                DropRule.Instance.FallDown();
            }
        }
    }
    //检测是否游戏失败
    CheckLose(){
        if(!this.LoseView){
            let lose = true;
            for (let i = 0; i < this.prefabbox.numChildren; i++) {
                let ball = this.prefabbox.getChildAt(i) as Laya.Image;
                let light = ball.getChildByName("light") as Laya.Image;
                if(light.visible){
                    lose = false;
                }
            }
            if(lose){
                this.LoseView = true;
                Laya.timer.clear(this,this.Save);
                this.Save(true);
                EventManager.StageTrigger(StageMode.Lose);
            }
        }
    }
    //开局刷新一下过关要求
    ScoreRefresh(){
        // let level = AccountManager.Instance.curplayerData.GainCollocation("level");
        let score = DropRule.Instance.GoalScore; 
        this.NowLv.value = DropRule.Instance.STAGE.toString();
        this.NextLv.value = (DropRule.Instance.STAGE+1).toString();
        this.NowScore.text = GameManager.Instance.ScoreProgress.toString();
        this.RequireScore.text = score.toString();
        // let stage = level[GameManager.Instance.STAGE];
        // score = Number(stage.goal); 
        // let id =Number(stage.id) ;
        // this.NowLv.value = id.toString();
        // this.NextLv.value = (id+1).toString();
        // this.NowScore.text = GameManager.Instance.ScoreProgress.toString();
        // this.RequireScore.text = score.toString();
    }
    //进入游戏时刷新一下道具数量
    SkillNumRefresh(){
        this.Func1num.text = AccountManager.Instance.curplayerData.GetPropNum(1).toString();
        this.Func2num.text = AccountManager.Instance.curplayerData.GetPropNum(2).toString();
        this.Func3num.text = AccountManager.Instance.curplayerData.GetPropNum(3).toString();
        this.Func4num.text = AccountManager.Instance.curplayerData.GetPropNum(4).toString();
        this.Func5num.text = AccountManager.Instance.curplayerData.GetPropNum(5).toString();
    }
    //进入游戏时刷新一下技能icon
    SkillRefresh(){
        this.ani1.play(null,false);
        this.ani2.play(null,false);
        this.ani3.play(null,false);
        this.ani4.play(null,false);
        this.ani5.play(null,false);
    }
    //技能图标动画效果
    SkillAnimation() {
        let random = GameTools.RandomANumber(1, 6);
        switch (random) {
            case 1:
                this.ani1.play(null, false);
                break;
            case 2:
                this.ani2.play(null, false);
                break;
            case 3:
                this.ani3.play(null, false);
                break;
            case 4:
                this.ani4.play(null, false);
                break;
            case 5:
                this.ani5.play(null, false);
                break;
        }
    }
    //比例
    private get Ratio():number{
        let score = DropRule.Instance.GoalScore; 
        let value = GameManager.Instance.ScoreProgress/score;
        return value;
    }
    //进度条
    Progress(){
        if(!this.WinView){
            this.LevelProgress.value = this.Ratio;
            if(GameManager.Instance.ScoreProgress>=Number(this.RequireScore.text)){
                GameManager.Instance.ScoreProgress = Number(this.RequireScore.text);
                this.NowScore.text = GameManager.Instance.ScoreProgress.toString();
                Laya.timer.clear(this,this.Save);
                this.Save(true);
                EventManager.StageTrigger(StageMode.Win);
                this.WinView = true;
            }
            this.NowScore.text = GameManager.Instance.ScoreProgress.toString();
        }
    }
    //推球道具
    ClickArrow(){
        console.log("点到了推球道具--");
       
        if(Number(this.Func5num.text)>0){
            var args = [{"t":AccountManager.Instance.ServerTime.toString()},{"play_id":GameManager.Instance.play_id},{"fid":"5"}]
            ServerManager.Instance.SendHttp(BlastToMerge.Use,args,Laya.Handler.create(this,()=>{
                for (let i = 0; i < this.prefabbox.numChildren; i++) {
                    let ball = this.prefabbox.getChildAt(i) as Laya.Image;
                    if(ball.destroyed){
                        continue
                    }
                    else{
                        let _rig = ball.getComponent(Laya.RigidBody) as Laya.RigidBody;
                        _rig.applyLinearImpulseToCenter({x:0,y:-1000});
                    }
                }
                this.SkillNumRefresh();
            }),Laya.Handler.create(this,()=>{

            }))
        }
    }
    //双倍道具
    ClickDouble(){
        if(EventManager.PropState == PropEffecf.DOUBLE){
            EventManager.EventTrigger(PropEffecf.NONE);
            console.log("切换为普通模式");
            return;
        }
        if(EventManager.PropState != PropEffecf.NONE){
            this.EffectMode(false);
            return;
        }
       
        if(Number(this.Func1num.text)>0){
            EventManager.EventTrigger(PropEffecf.DOUBLE);
            console.log("切换为双倍模式");
        }
    }
    //消除最小的球道具
    ClickZhunXin1(){
        console.log("点到了准心1道具--");
        
        if(Number(this.Func2num.text)>0){
            if(EventManager.PropState == PropEffecf.NONE){
                this.EffectMode(true,PropEffecf.CLEARLAST);
            }
            else{
                this.EffectMode(false);
            }
        }
    }
    //消除次小的球道具
    ClickZhunXin2(){
        console.log("点到了准心2道具--");
        
        if(Number(this.Func3num.text)>0){
            if(EventManager.PropState == PropEffecf.NONE){
                this.EffectMode(true,PropEffecf.CLEARTWO);
            }
            else{
                this.EffectMode(false);
            }
        }
    }
    //锤子道具
    ClickHammer(){
        console.log("点到了锤子道具--");
        
        if(Number(this.Func4num.text)>0){
            if(EventManager.PropState == PropEffecf.NONE){
                this.EffectMode(true,PropEffecf.HAMMER);
            }
            else{
                this.EffectMode(false);
            }
        }
    }
    //使用道具
    EffectMode(_open:boolean,_type:PropEffecf = null){
        this.Effect.visible = _open;
        if (_open) {
            EventManager.PropState = _type;
            let describe2 = this.Effect.getChildByName("describe2") as Laya.Text;
            let describe = this.Effect.getChildByName("describe") as Laya.Text;
            let icon = this.Effect.getChildByName("ICON") as Laya.Image;
            switch (_type) {
                case PropEffecf.CLEARLAST:
                    this.EffectBtn.visible = true;
                    describe.visible = true;
                    describe2.visible = false;
                    icon.visible = true;
                    icon.skin = this.GetIcon(DropRule.Instance.MinBall);
                    this.ClearNum.text = DropRule.Instance.MinBall.toString();
                    this.EffectBtn.clickHandler = Laya.Handler.create(this, this.ClearLast);
                    break;
                case PropEffecf.CLEARTWO:
                    this.EffectBtn.visible = true;
                    describe.visible = true;
                    describe2.visible = false;
                    icon.visible = true;
                    icon.skin = this.GetIcon(DropRule.Instance.MinNextBall);
                    this.ClearNum.text = DropRule.Instance.MinNextBall.toString();
                    this.EffectBtn.clickHandler = Laya.Handler.create(this, this.ClearTwo);
                    break;
                case PropEffecf.HAMMER:
                    this.EffectBtn.visible = false;
                    describe.visible = false;
                    describe2.visible = true;
                    icon.visible = false;
                    EventManager.EventTrigger(PropEffecf.HAMMER);
                    break;
            }
        }
        else{
            EventManager.PropState = PropEffecf.NONE;
            this.EffectBtn.clickHandler = null;
        }
    }
    //清除场景中最小的球
    ClearLast(){
        var args = [{"t":AccountManager.Instance.ServerTime.toString()},{"play_id":GameManager.Instance.play_id},{"fid":"2"}]
        ServerManager.Instance.SendHttp(BlastToMerge.Use,args,Laya.Handler.create(this,()=>{
            for (let i = this.prefabbox.numChildren-1; i >-1 ; i--) {
                let prefab = this.prefabbox.getChildAt(i) as Laya.Image;
                let ball = prefab.getComponent(Ball) as Ball;
                if(ball.score == DropRule.Instance.MinBall){
                    GameManager.Instance.ScoreProgress += ball.score;
                    DropRule.Instance.CreateEffect(ball.score,new Laya.Vector2(prefab.x,prefab.y));
                    prefab.removeSelf();
                }
            }
            this.SkillNumRefresh();
            this.Effect.visible = false;
            this.EffectBtn.clickHandler = null;
            EventManager.PropState = PropEffecf.NONE;
        }),Laya.Handler.create(this,()=>{
            console.log("道具使用失败");
        }))
    }
    //清除场景中第二小的球
    ClearTwo(){
        var args = [{"t":AccountManager.Instance.ServerTime.toString()},{"play_id":GameManager.Instance.play_id},{"fid":"3"}]
        ServerManager.Instance.SendHttp(BlastToMerge.Use,args,Laya.Handler.create(this,()=>{
            for (let i = this.prefabbox.numChildren-1; i >-1 ; i--) {
                let prefab = this.prefabbox.getChildAt(i) as Laya.Image;
                let ball = prefab.getComponent(Ball) as Ball;
                if(ball.score == DropRule.Instance.MinNextBall){
                    GameManager.Instance.ScoreProgress += ball.score;
                    DropRule.Instance.CreateEffect(ball.score,new Laya.Vector2(prefab.x,prefab.y));
                    prefab.removeSelf();
                }
            }
            this.SkillNumRefresh();
            this.Effect.visible = false;
            this.EffectBtn.clickHandler = null;
            EventManager.PropState = PropEffecf.NONE;
        }),Laya.Handler.create(this,()=>{
            console.log("道具使用失败");
        }))
    }
    /**传入分数 获取球的icon */
    GetIcon(_score:number):string{
        let index;
        for (let i = 0; i < DropRule.Instance.PrefabName.length; i++) {
            if(_score == Number(DropRule.Instance.PrefabName[i])){
                index = i.toString();
            }
        }
        return "Ball/blast"+ index + ".png"
    }
    //清除舞台上的球
    ClearStage(){
        if(!this.prefabbox.destroyed){
            for (let i = this.prefabbox.numChildren-1; i > -1; i--) {
                let ball = this.prefabbox.getChildAt(i) as Laya.Image;
                let _rig = ball.getComponent(Laya.RigidBody) as Laya.RigidBody;
                let _collider = ball.getComponent(Laya.CircleCollider) as Laya.CircleCollider;
                _collider.enabled = false;
                _rig.enabled = false;
                Laya.timer.clearAll(ball);
                ball.removeSelf();
                ball.destroy();
            }
        }
    }
    //游戏结束
    Over(){
        this.ClearStage();
        EventManager.StageOff(StageMode.Clone,this,this.AddPrefab);
        EventManager.StageOff(StageMode.Win,this,this.Win);
        EventManager.StageOff(StageMode.Lose,this,this.Lose);
        EventManager.StageOff(StageMode.ReStart,this,this.ReStart);
        EventManager.StageOff(StageMode.Over,this,this.Over);
        EventManager.StageOff(StageMode.Revive,this,this.Revive);
        EventManager.StageOff(StageMode.Check,this,this.Check);
        //清除碰撞器
        this.ClearCollider(this.BottomCollider);
        this.ClearCollider(this.RightCollider);
        this.ClearCollider(this.LeftCollider);
    }
    //复活
    Revive(){
        for (let i = this.prefabbox.numChildren-1; i >-1 ; i--) {
            let prefab = this.prefabbox.getChildAt(i) as Laya.Image;
            let ball = prefab.getComponent(Ball) as Ball;
            for (let j = 0; j < DropRule.Instance.BallNum.length; j++) {
                let Score = DropRule.Instance.GetBallIndex(ball.score);
                if(Score+1 ==Number(DropRule.Instance.BallNum[j]) ){
                    DropRule.Instance.CreateEffect(ball.score,new Laya.Vector2(prefab.x,prefab.y));
                    prefab.removeSelf();
                }
            }
        }
        Laya.timer.frameLoop(2,this,this.CheckHeight);
        Laya.timer.once(500,this,()=>{
            this.LoseView = false;
        })
    }
    //游戏胜利
    Win(){
        Laya.timer.clear(this,this.CheckHeight);
    }
    //游戏失败
    Lose(){
        Laya.timer.clear(this,this.CheckHeight);
    }
    //再来一局
    ReStart(_data?){
        if(_data){
            for (let i = this.prefabbox.numChildren-1; i >-1 ; i--) {
                let prefab = this.prefabbox.getChildAt(i) as Laya.Image;
                let ball = prefab.getComponent(Ball) as Ball;
                for (let j = 0; j < DropRule.Instance.BallNum.length; j++) {
                    let Score = DropRule.Instance.GetBallIndex(ball.score);
                    if(Score+1 ==Number(DropRule.Instance.BallNum[j]) ){
                        DropRule.Instance.CreateEffect(ball.score,new Laya.Vector2(prefab.x,prefab.y));
                        prefab.removeSelf();
                    }
                }
            }
            Laya.timer.loop(5000,this,this.Save);
            this.WinView = false;
            this.ScoreRefresh();
            this.Progress();
            DropRule.Instance.FallDown(DropRule.Instance.StartNum);
            Laya.timer.frameLoop(2,this,this.CheckHeight);
        }
        else{
            this.ClearStage();
            this.LoseView = false;
            this.WinView = false;
            this.ScoreRefresh();
            this.Progress();
            if(DropRule.Instance.STAGE == 1){
                this.Guide.visible = false;
                GameManager.Instance.Wave = 1;
                DropRule.Instance.GuideFallDown();
                GameManager.Instance.CheckHeight = false;
            }
            else{
                DropRule.Instance.FallDown(DropRule.Instance.StartNum);
            }
            Laya.timer.frameLoop(2,this,this.CheckHeight);
        }
    }
    //清除碰撞器
    ClearCollider(_node:Laya.Image){
        let collier = _node.getComponent(Laya.ChainCollider) as Laya.ChainCollider;
        let rig = _node.getComponent(Laya.RigidBody) as Laya.RigidBody;
        if(collier){
            collier.enabled = false;
        }
        if(rig){
            rig.enabled = false;
        }
        if(_node){
            _node.removeSelf();
            _node.destroy();
        }
    }
    Close(){
        Laya.timer.clearAll(this);
    }

    //保存关卡进度
    Save(_data?){
        let str = "";
        let ball;
        let score;
        let size;
        let index;
        let point;
        let obj = {};
        let objarray = [];
        if(!_data){
            for (let i = 0; i < this.prefabbox.numChildren; i++) {
                let prefab = this.prefabbox.getChildAt(i) as Laya.Image;
                ball = prefab.getComponent(Ball) as Ball;
                //分数
                score = ball.score;
                index =(DropRule.Instance.GetBallIndex(score) + 1).toString();
                //尺寸
                size = prefab.width.toString();
                //坐标
                point = new Laya.Vector2(prefab.x,prefab.y);
                obj =  {"index":index,"size":size,"pos":point};
                objarray.push(obj);
            }
            
            let jindutiao = {"jindu":GameManager.Instance.ScoreProgress.toString()};
            let sizeindex = {"sizeindex":DropRule.Instance.SizeIndex};
            let edgeindex = {"edgeindex":DropRule.Instance.EdgeIndex};
            objarray.push(edgeindex);
            objarray.push(jindutiao);
            objarray.push(sizeindex);
            var progress = JSON.stringify(objarray);
            var args =[{"stage":DropRule.Instance.STAGE.toString()},{"progress":progress}] 
        }
        else{
            obj = {"0":"0"};
            objarray.push(obj);
            var progress = JSON.stringify(objarray);
            var args =[{"stage":DropRule.Instance.STAGE.toString()},{"progress":progress}] 
        }
        ServerManager.Instance.SendHttp(BlastToMerge.Save,args,Laya.Handler.create(this,(res)=>{

        }),Laya.Handler.create(this,()=>{
           console.log("保存进度失败++");
        }))
    }
}