
import { INetData } from 'duiba-tc';
import { NetManager, DataManager, NetName } from 'duiba-tw';
import Scene from "../views/Scene";
import PanelCtrl from '../ctrls/panelCtrl';
import { ModuleTypes } from '../types/sceneTypes';

const { TouchEvent } = egret;
export default class PlayScene extends Scene {
    
    // 游戏参数
    private userCredits:number = 0;
    private unitNum:number = 10;
    private unitName:string;
    private currCostCredits:number = 0;
    private lightCount:number = 0;
    private lightRate = 30;
    private isLight:boolean = false;
    private wbgloop:any;
    private multiplesArr:any[] = [];
    private angleArr:any[] = [];
    private ranArr:any[] = [];
    private coinsArr:any[] = [];
    private gravity:number = 4.5;
    private multiple:number;

    // 导出的元件
    public bg:eui.Image;
    public ruleBtn:eui.Button;
    public addBtn:eui.Button;
    public reduceBtn:eui.Button;
    public WheelBg:eui.Component;
    public outShell:eui.Image;
    public startBtn:eui.Button;
    public unitTxt:eui.Label;
    public costTxt:eui.Label;
    public myCreditsBg:eui.Image;
    public userCreditsUnitName:eui.Label;
    public userCreditsNum:eui.Label;
    public circleLight1:eui.Image;
    public circleLight2:eui.Image;
    public sideLightD:eui.Image;
    public sideLightL:eui.Image;
    public finger:eui.Image;
    public resulePanel:eui.Panel;
    public rulePanel:eui.Panel;

    initEvents() {
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_startBtn,this);
        this.reduceBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_reduceBtn,this);
        this.addBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_addBtn,this);
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_ruleBtn,this);
    }

    removeEvents() {
        this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_startBtn,this);
        this.reduceBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_reduceBtn,this);
        this.addBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_addBtn,this);
        this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP,this.onClick_ruleBtn,this);
    }

    start() {
        this.once(egret.Event.ADDED_TO_STAGE,this.onLoad,this);
        this.circleLight1.$touchEnabled = false;
        this.circleLight2.$touchEnabled = false;
        this.finger.$touchEnabled = false;
        this.sideLightL.visible = false;
        this.userCredits = DataManager.ins.getInfoData ? DataManager.ins.getInfoData.credits : 0;
        this.unitName = DataManager.ins.getCreditsData ? `${DataManager.ins.getCreditsData.unitName}` : `积分`;
        if(this.userCredits<10){
            this.currCostCredits = 0;
        }else if(this.userCredits <= 200){
            this.currCostCredits = 10;
        }else if(this.userCredits <= 500){
            this.currCostCredits = 20;
        }else if(this.userCredits <= 1000){
            this.currCostCredits = 30;
        }else if(this.userCredits <= 5000){
            this.currCostCredits = 50;
        }else if(this.userCredits <= 10000){
            this.currCostCredits = 100;
        }else if(this.userCredits > 10000){
            this.currCostCredits = 200;
        }
        this.costTxt.text = `${this.currCostCredits}`;
        this.unitTxt.text = `投入${this.unitName}`; 
        this.userCreditsUnitName.text = `总${this.unitName}`;
        this.userCreditsNum.text = `${this.userCredits}`;
        let fingerTw = egret.Tween.get( this.finger, {loop: true} );
        fingerTw.to({scaleX:0.9, scaleY:0.9}, 500).to({scaleX:1, scaleY:1}, 500)

        this.WheelBg['realRotation'] = 0;
        console.log(this.WheelBg)


        // 按从小到大排序
        this.multiplesArr = [0, 0.2, 0.4, 0.5, 0.8, 1.0, 1.1, 1.2, 1.4, 1.5, 2];
        let unitAngle = 360/16;
        this.angleArr = [13*unitAngle, 11*unitAngle, 0, 5*unitAngle, 8*unitAngle, 14*unitAngle, 12*unitAngle, 6*unitAngle, 10*unitAngle, 3*unitAngle, 2*unitAngle];
        this.ranArr = [1/11,1/11,1/11,1/11,1/11,1/11,1/11,1/11,1/11,1/11,1/11];
    }


    private timeOnEnterFrame:number = 0;

    private onLoad(event:egret.Event) {
        this.addEventListener(egret.Event.ENTER_FRAME,this.onEnterFrame,this);
    }

    private onEnterFrame(e:egret.Event){
        let scope = this;  
        scope.lightCount ++;
        if(scope.lightCount%scope.lightRate == 0){
            scope.isLight = !scope.isLight;
        }
        scope.circleLight2.visible = scope.isLight;
        
        if(scope.coinsArr.length > 0){
            for(let c = scope.coinsArr.length-1; c>=0;c--){
                scope.coinsArr[c].x += scope.coinsArr[c].dirX * scope.coinsArr[c].vx;
                scope.coinsArr[c].y -= scope.coinsArr[c].vy;
                scope.coinsArr[c].vy -= scope.gravity;
            } 
        }
    }
    
    // 开始游戏
    private onClick_startBtn(e:egret.TouchEvent){
        if(window['requirelogin']) {
            window['requirelogin']();
            return;
        }

        if(this.userCredits < 10){
            let data = {msg:`${this.unitName}不足最小投值10${this.unitName}快去赚取${this.unitName}吧`, type:'creditsOut'}
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
            return;
        }

        let scope = this;
        let wbg = egret.Tween.get( this.WheelBg, {onChange: scope.onWbgRotationChange.bind(scope)});
        
        scope.removeChild(scope.goAni)

        let func:Function;
        wbg.to({realRotation:(scope.WheelBg['realRotation'] + 3600)}, 2000, egret.Ease.quartIn).call( func = function(){ 
            
            let _rotation = scope.WheelBg['realRotation'] + 360;
            scope.wbgloop = egret.Tween.get( scope.WheelBg, {onChange: scope.onWbgRotationChange.bind(scope), loop: true});
            scope.wbgloop.to({realRotation: _rotation}, 300).call(()=>{
                _rotation = scope.WheelBg['realRotation'] + 360;
            }); 
        });

        this.finger.visible = false;
        this.lightRate = 5;
        this.sideLightL.visible = true;
        this.buttonEnable(false);
        this.startBtn.currentState = 'wating';
        this.doStart(this.doStartResult.bind(this), false, this.currCostCredits, 1);
    }

    // 开始游戏接口
    public doStart(callback: Function, isAgain = false, credits?: number, customizedType?: number): void {
        if(window['requirelogin']) {
            window['requirelogin']();
            return;
        }
        NetManager.ins.doStart((success: boolean) => {
            if(success) {
                this.getStartStatus(callback, customizedType);
            } else {
                callback(success);
            }
        },
        isAgain,
        credits,
        customizedType);
    }

    // 查询开始状态
    private getStartStatus(callback: Function, customizedType?: number): void {
        const param: any = {
            ticketId: DataManager.ins.doStartData.ticketId
        };
        if (customizedType) {
            param.customizedType = customizedType
        }
        const net: INetData = {
            name: 'getStartStatus',
            uri: '/ngapi/getStartStatus',
            type: 'post',
            dataType: 'json',
            param: param,
            callback: callback,
            pollingCount: 5,
            pollingCheck: () => { return DataManager.ins.getData('getStartStatus').code != 1; }
        };
        NetManager.ins.send(net)
    }

    // 开始的回调
    private doStartResult(success:boolean){
        let scope = this;
        if(!success) {
            this.defaultErr()
            return;
        }

        let upperCreditsLimit = DataManager.ins.getData('getStartStatus').upperCreditsLimit ? DataManager.ins.getData('getStartStatus').upperCreditsLimit : scope.currCostCredits;
        // 取得的返回最大倍数
        let maxMultiple = upperCreditsLimit/scope.currCostCredits;
        console.log(`最大倍数:${maxMultiple}`)
        // 改变数组
        let newMultiplesArr:any[] = [];
        for(let m = 0; m<scope.multiplesArr.length; m++){
            if(scope.multiplesArr[m] < maxMultiple){
                newMultiplesArr.push(scope.multiplesArr[m]);
            }
        }
        
        // 更新用户积分文案
        scope.userCreditsNum.text = `${DataManager.ins.getInfoData ? DataManager.ins.getInfoData.credits : scope.userCredits}`
        
        // 拿到倍数
        let newAngleArr:any[] = [];
        let newRanArr:any[] = [];
        let arr:any[] = [];
        for(let i = 0; i < newMultiplesArr.length; i++){
            newAngleArr.push(scope.angleArr[i]);
            newRanArr.push(scope.ranArr[i]);

            let num = Math.round(120 * newRanArr[i]);
            let a = (new Array(num))["fill"](newAngleArr[i]);
            arr = arr.concat(a);
        }
        
        let randomT = (e, n?) => {
            return e && "number" == typeof e.length && e.length ? e[Math.floor(Math.random() * e.length)] : ("number" != typeof n && (n = e || 1, e = 0), e + Math.random() * (n - e))
        }

        let targetAngle = randomT(arr);
        let i = scope.angleArr.indexOf(targetAngle);
        let multiple = scope.multiplesArr[i];
        this.multiple = multiple;
        console.log(`随机倍数:${multiple}`)

        let timeout = setTimeout(() => {
            clearTimeout(timeout)
            egret.Tween.removeTweens( scope.WheelBg );
            let tw = egret.Tween.get( scope.WheelBg, {onChange:scope.onWbgRotationChange.bind(scope)} );
            let _rotation = Math.random() > 0.5 ? scope.WheelBg['realRotation'] + ( 360 - scope.WheelBg['realRotation'] % 360 ) + targetAngle + 1440 + Math.random() * 8 : scope.WheelBg['realRotation'] + ( 360 - scope.WheelBg['realRotation'] % 360 ) + targetAngle + 1440 - Math.random() * 8;
            tw.to({realRotation:_rotation}, 8000 ,egret.Ease.quartOut).call(()=>{
                scope.startBtn.currentState = 'up';
                scope.buttonEnable(false)
                scope.sideLightL.visible = false;
                scope.lightRate = 30;
                scope.coinsFall(true)
            });        
        }, 1000);

        // 延时提交分数
        let timeout2 = setTimeout(()=>{
            this.gameSubmitData(this.gameSubmitResult.bind(this), this.currCostCredits * multiple, false, 1);
        },500)
    }

    private gameSubmitResult(){
        NetManager.ins.getInfo(()=>{})
        console.log('提交成功')
    }


    /**
     * 提交游戏成绩
     * @param callback 
     * @param score 得分
     * @param allDynamics 防作弊数据
     * @param checkScore  是否校验得分
     * @param customizedType 定制类型 1推币机    
     */
    protected gameSubmitData(callback: Function, score: number, checkScore?: boolean, customizedType?: number): void {
        NetManager.ins.gameSubmit(
            (success: boolean) => { 
                if(success) {
                    this.getSubmitResult(callback, DataManager.ins.gameSubmitData.orderId); 
                } else {
                    callback(success);
                }
            },
            DataManager.ins.doStartData.ticketId,
            score,
            '[]',
            DataManager.ins.doStartData.submitToken,
            '',
            checkScore,
            customizedType);
    }
    
    /**
     * 查询提交结果
     * @param callback 
     * @param orderId 
     */
    private getSubmitResult(callback: Function, orderId: number): void {
        NetManager.ins.getSubmitResult(callback, orderId, () => {
            return DataManager.ins.gameGetSubmitResultData.flag;
        });
    }

    // 默认出错——转到0后弹错误窗
    private defaultErr(){
        let timeout = setTimeout(() => {
            clearTimeout(timeout)
            egret.Tween.removeTweens( this.WheelBg );
            let tw = egret.Tween.get( this.WheelBg, {onChange:this.onWbgRotationChange.bind(this)} );
            this.multiple = 0;
            let _rotation = this.WheelBg['realRotation'] + ( 360 - this.WheelBg['realRotation'] % 360 ) + 360*13/16 + 1440;
            tw.to({realRotation:_rotation}, 8000 ,egret.Ease.quartOut).call(()=>{
                this.startBtn.currentState = 'up';
                this.buttonEnable(true);
                this.sideLightL.visible = false;
                this.lightRate = 30;
                this.coinsFall(false)
            });        
        }, 2000);
    }
    private onWbgRotationChange(){
        this.WheelBg.rotation = this.WheelBg['realRotation'];
    }

    // 减号
    private onClick_reduceBtn(e:egret.TouchEvent){
        if(window['requirelogin']) {
            window['requirelogin']();
            return;
        }
        if((this.currCostCredits - this.unitNum) > 0 && (this.userCredits - this.unitNum) > 0 ){
            this.currCostCredits -= this.unitNum;
        }
        this.costTxt.text = `${this.currCostCredits}`;
    }

    // 加号
    private onClick_addBtn(e:egret.TouchEvent){
        if(window['requirelogin']) {
            window['requirelogin']();
            return;
        }
        if((this.currCostCredits + this.unitNum) <= this.userCredits && this.currCostCredits < 500){
            this.currCostCredits += this.unitNum;
        }
        this.costTxt.text = `${this.currCostCredits}`;
    }

    // 规则按钮
    private onClick_ruleBtn(e:egret.TouchEvent){
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL);
    }

    // 加载动画资源
    private goAni:any;
    protected childrenCreated():void{
        super.childrenCreated();
        this.ayncLoad2Mc("goBtn_json");
        this.ayncLoad2Mc("coin_json");
    }
    private ayncLoad2Mc( resname : string) : void{
        let scope = this;
        RES.getResAsync(resname,
        (data: any,key: string): void => {
            if(key == "coin_json") {
                scope.ayncLoad2Mc("coin_png");
            }else if(key == "coin_png") {
                for(let i=0;i<100;i++){
                    let data2mc = RES.getRes("coin_json");
                    let texture2mc = RES.getRes("coin_png");
                    let mcFactory : egret.MovieClipDataFactory = new egret.MovieClipDataFactory(data2mc,texture2mc);
                    let mc:egret.MovieClip = new egret.MovieClip(mcFactory.generateMovieClipData("coin"));
                    scope.coinsArr.push(mc);
                }
            }else if(key == "goBtn_json") {
                scope.ayncLoad2Mc("goBtn_png");
            }else if(key == "goBtn_png") {
                let data2mc = RES.getRes("goBtn_json");
                let texture2mc = RES.getRes("goBtn_png");
                let mcFactory : egret.MovieClipDataFactory = new egret.MovieClipDataFactory(data2mc,texture2mc);
                let mc:egret.MovieClip = new egret.MovieClip(mcFactory.generateMovieClipData("go"));
                mc.gotoAndPlay('light', -1);
                scope.goAni = mc;
                scope.addChild(scope.goAni)
                scope.addChild(scope.finger)
                mc.x = 279;
                mc.y = 494;
            }
        },
        this);
    }

    // 金币掉落效果
    private coinsFall(isSuccess:boolean):void{
        let scope = this;
        let count = 0;
        let coinsFall = setInterval(()=>{
            if(count<100){
                scope.addChild(scope.coinsArr[count]);
                scope.coinsArr[count].gotoAndPlay('rotate', -1);
                if(Math.random()>0.5){
                    scope.coinsArr[count].dirX = 1;
                }else{
                    scope.coinsArr[count].dirX = -1;
                }
                scope.coinsArr[count].vy = Math.random() * 60;
                scope.coinsArr[count].vx = Math.random() * 30;
                scope.coinsArr[count].x = this.stage.stageWidth/2 - scope.coinsArr[count].width/2;
                scope.coinsArr[count].y = 500;
                count++;
                this.addChild(this.resulePanel)
            }else{
                if(!isSuccess){
                   // 失败
                    let msg = DataManager.ins.doStartData ? DataManager.ins.doStartData.message : `网络出了点小问题请退出后重试`;
                    let data = {msg:msg, type:'err'}
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data) 
                }
                clearInterval(coinsFall)
            }
        },10)
        
        scope.showResultPanel()
    }

    private currEarnCredits:number = 0;
    private showResultPanel(){
        let scope = this;
        scope.currEarnCredits = scope.currCostCredits * scope.multiple;
        let resultPanelTw = egret.Tween.get( scope.resulePanel );
        resultPanelTw.to({scaleX:1, scaleY:1}, 300).wait(2000).call(()=>{
            scope.resulePanel.scaleX = 0;
            scope.resulePanel.scaleY = 0;
            scope.buttonEnable(true);
            scope.addChild(scope.goAni);
        })
        this.resulePanel['credits'].text = `0`;
        let credits:any = {num:0}; 
        credits.num = Number(this.resulePanel['credits'].text);
        let creditTw = egret.Tween.get( credits , { onChange:onCreditsChange});
        creditTw.to({num: this.currEarnCredits},1000)

        function onCreditsChange(){
            let c = Math.floor(credits.num);
            scope.resulePanel['credits'].text = `${c}`
        }
    }

    // 按钮状态
    private buttonEnable(enabled:boolean){
        this.startBtn.enabled = enabled;
        this.addBtn.enabled = enabled;
        this.reduceBtn.enabled = enabled;
        this.ruleBtn.enabled = enabled;
    }



    protected get skinKey() { return 'Play' }
}