import { AccountManager } from "../Net/AccountManager";
import Ball from "../Main/Ball";
import { EventManager, StageMode } from "./EventManager";
import { GameTools } from "./GameTools";
import { GameManager } from "../Main/GameManager";
import { ServerManager, BlastToMerge } from "../Net/ServerManager";
import { AudioManager, MusicType } from "./AudioManager";
import { GamePool } from "./GamePool";
import { AssetManager } from "../Main/AssetManager";

export class DropRule{
    private static ins:DropRule;
    public progress:any;
    constructor(){
        DropRule.ins = this;
        this.Init();
        this.InitEffect();
        // EventManager.StageOn(StageMode.ReStart,this,this.Init);
        EventManager.StageOn(StageMode.Refresh,this,this.Init);
    }
    public static get Instance():DropRule{
        if(DropRule.ins){
            return DropRule.ins
        }
        else{
            return new DropRule();
        }
    }
    //特效名字数组
    public EffectName:string[] = new Array<string>("blue","yellow","purple","green");
    //特效预制体数组
    public EffectArray:Laya.Prefab[] = [];
    //球名字数组
    public PrefabName:string[] = new Array<string>("2","4","8","16","32","64","128","256","512","1024","2048","4096","8192","16384","32768","65536","131072","262144");
    //是否已经克隆完毕
    public Cloned:boolean = false;
    //本关卡数
    public STAGE:number;
    //本关卡目标分数
    public GoalScore:number;
    //本关卡能出球的区间
    public BallNum:string[];
    //本关卡能出现的最小球的数字
    public MinBall:number;
    //本关卡能出现的次小球的数字
    public MinNextBall:number;
    //本关卡掉落线
    public DropHeight:number;
    //本关卡开始的掉落球数量
    public StartNum:number;
    //本关卡一次性掉落数量区间  
    public DropNum:string[];
    //本关卡球Size大小序列
    public SizeIndex:string[];
    //本关卡球乘幂序列
    public EdgeIndex:string[];
    Init(_data?){
        this.STAGE = Number(AccountManager.Instance.curplayerData.GainAccount("stage")); 
        let level = AccountManager.Instance.curplayerData.GainCollocation("level");
        if(_data){
            for(var key in level){
                if(level[key].id  == this.STAGE){
                    let Level = level[Number(key)];
                    this.DropHeight = Number(Level.hight);
                    this.GoalScore = Number(Level.goal);
                    // this.SizeIndex = Level.index.split(";");//不重新开始游戏不更新球的大小序列
                    this.BallNum = Level.edge.split(";");
                    this.StartNum = Number(Level.start_number);
                    this.DropNum = Level.drop_number.split(";");
                    // this.EdgeIndex = Level.edgeindex.split(";");
                    let min =Number(this.BallNum[0]);
                    let minnext = Number(this.BallNum[1]);
                    //获取消除道具中 本局 最小球 及 次小球
                    this.MinBall =Number(this.PrefabName[min-1]);
                    this.MinNextBall = Number(this.PrefabName[minnext-1]);
                }
            }
        }
        else{
            for(var key in level){
                if(level[key].id  == this.STAGE){
                    let Level = level[Number(key)];
                    this.DropHeight = Number(Level.hight);
                    this.GoalScore = Number(Level.goal);
                    this.SizeIndex = Level.index.split(";");
                    console.log(this.SizeIndex);
                    this.BallNum = Level.edge.split(";");
                    this.StartNum = Number(Level.start_number);
                    this.DropNum = Level.drop_number.split(";");
                    this.EdgeIndex = Level.edgeindex.split(";");
                    let min =Number(this.BallNum[0]);
                    let minnext = Number(this.BallNum[this.BallNum.length-1]);
                    //获取消除道具中 本局 最小球 及 次小球
                    this.MinBall =Number(this.PrefabName[min-1]);
                    this.MinNextBall = Number(this.PrefabName[minnext-1]);
                }
            }
        }
        this.Read();
    }
    //特效
    InitEffect(){
        for (let i = 0; i < this.EffectName.length; i++) {
            this.ReadJson(i)
        }
    }
    ReadJson(i:number){
        Laya.loader.create("Effect/"+this.EffectName[i]+".json",Laya.Handler.create(this,this.creat));
    }
    creat(Prefab:any){
        let obj = new Laya.Prefab();
        obj.json = Prefab;
        this.EffectArray.push(obj);
    }
    
    /**传入分数及位置  克隆相应销毁特效 */
    CreateEffect(_score:number,_pos:Laya.Vector2){
        let effect;
        let index;
        if(_score == 2 || _score == 16 || _score == 256 || _score == 2048 || _score == 32768 || _score == 262144){
            effect = this.EffectArray[3];
            index = 3;
        }
        else if(_score == 8 || _score == 32 || _score == 4096 || _score == 131072){
            effect = this.EffectArray[1];
            index = 1;
        }
        else if(_score == 64 || _score == 512 || _score == 16384){
            effect = this.EffectArray[2];
            index = 2;
        }
        else if(_score == 4 || _score ==128 || _score == 1024 || _score == 8192 || _score == 65536){
            effect = this.EffectArray[0];
            index = 0;
        }
        let pre = Laya.Pool.getItemByCreateFun(this.EffectName[index],effect.create,effect) as Laya.Animation;
        pre.pos(_pos.x,_pos.y);
        Laya.stage.addChild(pre);
        pre.on(Laya.Event.COMPLETE,this,()=>{
            pre.removeSelf();
            pre.destroy();
        })
    }
    /** 传入分数获取球的序号*/
    GetBallIndex(_score:number):number{
        let num;
        for (let i = 0; i < this.PrefabName.length; i++) {
            if(_score == Number(this.PrefabName[i])){
                num = i;
            }
            else if(_score>Number(this.PrefabName[i]) && _score<Number(this.PrefabName[i+1])){
                num = i;
            }
        }
        return num;
    }
    /**传入消掉的分数获取应加的分数*/
    GetScore(_score:number):number{
        let num;
        for (let i = 0; i < this.PrefabName.length; i++) {
            if(_score == Number(this.PrefabName[i])){
                num = Number(this.PrefabName[i]);
            }
            else if(_score>Number(this.PrefabName[i]) && _score<Number(this.PrefabName[i+1])){
                num = Number(this.PrefabName[i]);
            }
        }
        return num;
    }
    /**传入分数获取本关卡球的size */
    GetBallSize(_score:number):number{
        let num ;
        let index;
        let size = 0;
        for (let i = 0; i < this.PrefabName.length; i++) {
            if(_score == Number(this.PrefabName[i])){
                num = i;
            }
            else if(_score>Number(this.PrefabName[i]) && _score<Number(this.PrefabName[i+1])){
                num = i;
            }
        }
        for (let j = 0; j < this.EdgeIndex.length; j++) {
            if(num+1 == Number(this.EdgeIndex[j])){
                index = Number(this.SizeIndex[j]);
                size = this.Size(num+1,index);
            }
        }
        if(size == 0){
            let cimi = Number(this.EdgeIndex[this.EdgeIndex.length-1]);
            index = Number(this.SizeIndex[this.EdgeIndex.length-1]);
            size = this.Size(cimi,index);
            let n = (num+1) - cimi;
            size = size + (n*5);
        }
        return size
    }
    /**传入球的序号（2的次幂）,等级  获取球的大小 */
    Size(_index:number,sizelevel:number):number{
        let ballsize ;
        let ball = AccountManager.Instance.curplayerData.GainCollocation("ball");
        for (var key in ball) {
            let item = ball[key];
            if(_index == item.ball && sizelevel == item.size_level){
                ballsize = Number(item.size)
            }
        }
        return ballsize
    }
    /**创建球的预制  合成克隆*/
    CreatBall(_index:number,size:number,pos:Laya.Vector2){
        // let ball = GamePool.Instance.GetModel(AssetManager.Instance.Ball.get(_index),_index.toString());
        let ball = GamePool.Instance.GetModel("img"+_index.toString());
        // let ball = Laya.Pool.getItemByClass("img" + _index.toString(),Laya.Image);
        // let ball:Laya.Image = new Laya.Image();
        ball.skin = "Game/res/Ball/blast"+ _index + ".png";
        ball.anchorX = 0.5;
        ball.anchorY = 0.5;
        ball.height = size;
        ball.width = size;
        //刚体碰撞器
        let _rig = ball.getComponent(Laya.RigidBody) as Laya.RigidBody;
        if(!_rig ){//|| _rig.destroyed
            let rig = ball.addComponent(Laya.RigidBody) as Laya.RigidBody;
            rig.allowRotation = true;
            rig.gravityScale = 3;
        }
        else{
            _rig.enabled = true;
        }
        let _collider = ball.getComponent(Laya.CircleCollider) as Laya.CircleCollider;
        if(!_collider ){//|| !_collider.destroyed
            let collider = ball.addComponent(Laya.CircleCollider) as Laya.CircleCollider;
            collider.restitution = AccountManager.Instance.curplayerData.Restitution;
            if (this.STAGE == 1 && GameManager.Instance.Wave < 3) {
                collider.restitution = 0;
            }
            collider.radius = size / 2;
        }
        else{
            _collider.enabled = true;
            _collider.isSensor = false;
        }
        
        //字体
        let _num = ball.getChildByName("num") as Laya.FontClip;
        let zi;
        if(!_num){
            let num :Laya.FontClip = new Laya.FontClip();
            num.name = "num";
            num.skin = "Game/res/Ball/44.png";
            num.anchorX = 0.5;
            num.anchorY = 0.5;
            num.sheet = "0123456789";
            zi = this.PrefabName[_index];
            num.value = zi;
            ball.addChild(num);
            num.centerX = 0;
            num.centerY = 0;
        }
        
        //光效
        let _light = ball.getChildByName("light") as Laya.Image;
        if(!_light){
            let light:Laya.Image = new Laya.Image();
            light.skin = "Game/res/Ball/"+ zi + ".png";
            light.anchorX = 0.5;
            light.anchorY = 0.5;
            light.width = this.LightSize(size);
            light.height =this.LightSize(size);
            light.name = "light";

            ball.addChild(light);
            light.centerX = 0;
            light.centerY = 0;
        }
        else{
            _light.anchorX = 0.5;
            _light.anchorY = 0.5;
            _light.width = this.LightSize(size);
            _light.height =this.LightSize(size);
            _light.centerX = 0;
            _light.centerY = 0;
        }
        //脚本
        let _script = ball.getComponent(Ball) as Ball;
        if(!_script){
            let script = ball.addComponent(Ball) as Ball;
        }
        ball.pos(pos.x,pos.y);
        // this.SetPosition(ball,pos);
        Laya.timer.once(1,this,()=>{
            EventManager.StageTrigger(StageMode.Clone,[ball]);
        })
        this.Cloned = true;
        AudioManager.playMusic(MusicType.down);
    }
    /**创建球的预制  自动掉球*/
    CreatBall2(_index:number,size:number,pos:Laya.Vector2){
        let ball = GamePool.Instance.GetModel("img"+_index.toString());
        // let ball = GamePool.Instance.GetModel(AssetManager.Instance.Ball.get(_index),_index.toString());
        // let ball = Laya.Pool.getItemByClass("img" +_index.toString(),Laya.Image);
        // let ball:Laya.Image = new Laya.Image();
        ball.skin = "Game/res/Ball/blast"+ _index + ".png";
        ball.anchorX = 0.5;
        ball.anchorY = 0.5;
        ball.height = size;
        ball.width = size;
        //碰撞器
        let _collider = ball.getComponent(Laya.CircleCollider) as Laya.CircleCollider;
        if(!_collider ){//|| _collider.destroyed
            let collider = ball.addComponent(Laya.CircleCollider) as Laya.CircleCollider;
            collider.restitution = AccountManager.Instance.curplayerData.Restitution;
            if ( this.STAGE == 1 && GameManager.Instance.Wave < 3 ) {
                collider.restitution = 0;
            }
            collider.radius = size / 2;
        }
        else{
            ball.getComponent(Laya.CircleCollider).enabled = true;
            ball.getComponent(Laya.CircleCollider).isSensor = true;
            // _collider.enabled = true;
            // _collider.isSensor = false;
        }
        //刚体
        let _rig = ball.getComponent(Laya.RigidBody) as Laya.RigidBody;
        if(!_rig ){//|| _rig.destroyed
            let rig = ball.addComponent(Laya.RigidBody) as Laya.RigidBody;
            rig.allowRotation = true;
            rig.gravityScale = 3;
        }
        else{
            ball.getComponent(Laya.RigidBody).enabled = true;
            // _rig.enabled = true;
        }
       
        //字体
        let _num = ball.getChildByName("num") as Laya.FontClip;
        let zi;
        if(!_num){
            let num :Laya.FontClip = new Laya.FontClip();
            num.name = "num";
            num.skin = "Game/res/Ball/44.png";
            num.anchorX = 0.5;
            num.anchorY = 0.5;
            num.sheet = "0123456789";
            zi = this.PrefabName[_index];
            num.value = zi;
            ball.addChild(num);
            num.centerX = 0;
            num.centerY = 0;
        }
        
        //光效
        let _light = ball.getChildByName("light") as Laya.Image;
        if(!_light){
            let light:Laya.Image = new Laya.Image();
            light.skin = "Game/res/Ball/"+ zi + ".png";
            light.anchorX = 0.5;
            light.anchorY = 0.5;
            light.width = this.LightSize(size);
            light.height =this.LightSize(size);
            light.name = "light";

            ball.addChild(light);
            light.centerX = 0;
            light.centerY = 0;
        }
        else{
            _light.anchorX = 0.5;
            _light.anchorY = 0.5;
            _light.width = this.LightSize(size);
            _light.height =this.LightSize(size);
            _light.centerX = 0;
            _light.centerY = 0;
        }
        
        //脚本
        let _script = ball.getComponent(Ball) as Ball;
        if(!_script){
            let script = ball.addComponent(Ball) as Ball;
        }
        ball.pos(pos.x,pos.y);
        // this.SetPosition(ball,pos);
        Laya.timer.once(1,this,()=>{
            EventManager.StageTrigger(StageMode.Clone,[ball]);
        })
        AudioManager.playMusic(MusicType.down);
    }
    //设置球的位置
    SetPosition(_node:Laya.Image,_pos:Laya.Vector2){
        _node.pos(_pos.x,_pos.y);
    }
    /**根据球的大小调节光圈大小 */
    LightSize(_size:number):number{
        let num;
        switch (_size) {
            case 65:
                num = 79;
                break;
            case 70:
                num = 87
                break;
            case 75:
                num = 95
                break;
            case 80:
                num = 100
                break;
            case 85:
                num = 105
                break;
            case 90:
                num = 110
                break;
            case 95:
                num = 117
                break;
            case 100:
                num = 124
                break;
            case 105:
                num = 130
                break;
            case 110:
                num = 136
                break;
            case 115:
                num = 143
                break;
            case 120:
                num = 150
                break;
            case 125:
                num = 152
                break;
            case 130:
                num = 160
                break;
            case 135:
                num = 165
                break;
            case 140:
                num = 174
                break;
            case 145:
                num = 181
                break;
            case 150:
                num = 186
                break;
            case 155:
                num = 192
                break;
            case 160:
                num = 199
                break;
            case 165:
                num = 202
                break;
            case 170:
                num = 210
                break;
            case 175:
                num = 215
                break;
            case 180:
                num = 223
                break;
            case 185:
                num = 231;
                break;
            case 190:
                num = 236;
                break;
            case 195:
                num = 241;
                break;
            case 200:
                num = 247;
                break;
            case 205:
                num = 253;
                break;
            case 210:
                num = 260;
                break;
            case 215:
                num = 268;
                break;
            case 220:
                num = 275;
                break;
            case 225:
                num = 280;
                break;
            case 230:
                num = 287;
                break;
        }
        return num
    }
    /**消除掉球 */
    FallDown(_time?:number){
        if(!_time){
            let mindrop = Number(this.DropNum[0]);
            let maxdrop = Number(this.DropNum[1]);
            _time = GameTools.RandomANumber(mindrop,maxdrop+1);
        }
        let min = Number(this.BallNum[0]);
        let max =Number(this.BallNum[this.BallNum.length-1]);
        let index;
        let size;
        for (let j = 0; j < _time; j++) {
            let num = GameTools.RandomANumber(min,max+1);
            for (let i = 0; i < this.BallNum.length; i++) {
                if(num == Number(this.BallNum[i])){
                    index = Number(this.SizeIndex[i]);
                    size = this.Size(num,index);
                }
            }
            let X = GameTools.RandomANumber(100,500);
            let pos = new Laya.Vector2(X, 30);
            this.CreatBall2(num-1,size,pos);
        }
    }
    //新手指引关掉球规律
    GuideFallDown(){
        GameManager.Instance.CheckHeight = false;
        let num;
        let shuliang;
        let gaoduxin;
        if(GameManager.Instance.Wave == 1){
            shuliang = 2;
            num = 1;
        }
        else if(GameManager.Instance.Wave == 2){
            shuliang = 2;
            num = 2;
        }
        else if(GameManager.Instance.Wave == 3){
            shuliang = 6;
            num = 1;
        }
        else if(GameManager.Instance.Wave == 4){
            shuliang = 12;
            num = 1;
        }
        else if(GameManager.Instance.Wave == 5){
            shuliang = 6;
            num = 2;
        }
        else if(GameManager.Instance.Wave == 6){
            shuliang = 12;
            num = 2
        }
        else{
            GameManager.Instance.CheckHeight = true;
            this.DropHeight = AccountManager.Instance.curplayerData.GuideHeight;
            let mindrop = Number(this.DropNum[0]);
            let maxdrop = Number(this.DropNum[1]);
            num = GameTools.RandomANumber(mindrop,maxdrop+1);
        }
        let score = Number(this.PrefabName[num-1]);
        let index = this.GetBallIndex(score);
        let size = this.GetBallSize(score);
        for (let j = 0; j < shuliang; j++) {
            let X = GameTools.RandomANumber(100,500);
            let pos = new Laya.Vector2(X, 30);
            this.CreatBall2(num-1,size,pos);
        }
    }
    /**恢复场景 */
    RecoverScene(){
        for (let i = 0; i < this.progress.length-3; i++) {
            let item = this.progress[i];
            this.CreatBall2(Number(item.index)-1,Number(item.size),new Laya.Vector2(Number(item.pos.x),Number(item.pos.y)));
        }
    }
    /**读取进度*/
    Read(){
        if(this.STAGE>1){
            var args =[{"stage":"0"}] 
            ServerManager.Instance.SendHttp(BlastToMerge.GetProgress,args,Laya.Handler.create(this,(res)=>{
                let json =JSON.parse(res.user_game.detail);
                this.progress = json;
                if(this.progress.length>1){
                    let items = this.progress[this.progress.length-2];
                    let _score = Number(items.jindu); 
                    GameManager.Instance.ScoreProgress = _score;
                    this.SizeIndex = this.progress[this.progress.length-1].sizeindex;
                    this.EdgeIndex = this.progress[this.progress.length -3].edgeindex;
                }
                console.log("获取进度成功");
            }),Laya.Handler.create(this,()=>{
                console.log("获取进度失败");
            }))
        }
    }
}