import { DataManager } from './../../libs/tw/manager/DataManager';
import { ModuleTypes } from './../types/sceneTypes';
import { PopupType } from './../types/sceneTypes';

import Scene from "../views/Scene";
import PanelCtrl from "../ctrls/panelCtrl";
import SceneCtrl from '../ctrls/sceneCtrl';

import { NetManager } from '../../libs/tw/manager/NetManager';
import { Buried } from '../../libs/tw/util/Buried';
import { WinnerItemComponent } from "../components/WinnerItemComponent";

export default class StartScene1 extends Scene {
    public ruleBtn:eui.Button;
    public recordLabBtn:eui.Button;

    public drawTimelab:eui.Label;
 
    public winPrizeGroup:eui.Group;

    public activityTIme:eui.Label;
    public monthlyCardCount:eui.Label;
    public yearCardCount:eui.Label;

    public prizeEgg1:eui.Image;
    public prizeEgg2:eui.Image;
    public prizeEgg3:eui.Image;
    public hammer:eui.Image;

    private splitEgg:egret.Texture;
    private brokenEgg:egret.Texture;
    //private tweenArray:Array<any> = [];

    private chooseEgg:any;
    //private arrayIndex = 0;
    private mData;

    public bg:eui.Image;
    private bgTexture:egret.Texture;
    public get skinKey() { return 'StartScene' }
    public get groupName() { return 'start_scene' }

    private hammerMove = false;
    private pollingEnd = false;
    private channel;
    constructor(data?) {
        super(data);//95fcf3
    }

    initEvents() {
        super.initEvents();
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onClickRule, this);
        this.recordLabBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);

        this.prizeEgg1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeEgg, this);
        this.prizeEgg2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeEgg, this);
        this.prizeEgg3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeEgg, this);
    }

    removeEvents() {
        super.removeEvents();
        this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onClickRule, this);
        this.recordLabBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);

        this.prizeEgg1.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeEgg, this);
        this.prizeEgg2.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeEgg, this);
        this.prizeEgg3.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeEgg, this);
    }

    start(data?) {
        super.start(data);
        this.mData = data;
        this.percentHeight = 100;
    }

    protected async preLoadRes() {

        this.splitEgg = await RES.getResAsync('splitEgg_png');
        this.brokenEgg = await RES.getResAsync('brokenEgg_png');
        this.bgTexture = await RES.getResAsync('stratBg_jpg');
        return new Promise(function (resolve) {
            resolve();
        });
        
    }
    protected onSkinComplete(): void {
        super.onSkinComplete();
        this.bg.texture = this.bgTexture;
        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
    }
  
    private onLoad(): void {

        //1暂定app渠道Banner  2暂定小程序首页Banner
        this.channel = this.getParamString("from");
        console.log("渠道-",this.channel);

        let ruleDpmOut = Buried.connectDpm(110, 1, 1); 
        let ruleDcmOut = Buried.connectDcm(202, 0, 0); 
        let ruleDomOut = Buried.connectDom(this.channel); 
        let ruleExposure = Buried.createExposureNew(ruleDpmOut, ruleDcmOut,ruleDomOut);
        NetManager.ins.showLog(ruleExposure);

        let startDpmOut = Buried.connectDpm(110, 2, 1); 
        let startDcmOut = Buried.connectDcm(202, 0, 0); 
        let starDomOut = Buried.connectDom(this.channel); 
        let exposure = Buried.createExposureNew(startDpmOut, startDcmOut,starDomOut);
        NetManager.ins.showLog(exposure);

        let recordDpmOut = Buried.connectDpm(110, 3, 1); 
        let recordDcmOut = Buried.connectDcm(202, 0, 0); 
        let recordDomOut = Buried.connectDom(this.channel); 
        let recordExposure = Buried.createExposureNew(recordDpmOut, recordDcmOut,recordDomOut);
        NetManager.ins.showLog(recordExposure);

        this.initUI();
      
        this.getMoble();
        if(this.mData && this.mData.refresh == false)
        {
            let timeData = DataManager.ins.getData('remainTimes').data.remainTimes;
            if(timeData){
                this.drawTimelab.text = timeData + "次";
            }else{
                this.drawTimelab.text = "0次";
            }
        }
        else{
            this.updateRemainTimes();
        }
        this.winPrizeGroup.visible = false;
    }
    private initUI(){
        let getStartTime1:string = window['startTime'];
        let startTime1 = getStartTime1.split(' ');
        let showTimeLab1 = startTime1[0].split('-');

        let getEndTime1:string = window['endTime'];
        let endTime1 = getEndTime1.split(' ');
        let showTimeLab2 = endTime1[0].split('-');

        this.activityTIme.text = showTimeLab1[1]+'.'+showTimeLab1[2]+'-'+showTimeLab2[1]+'.'+showTimeLab2[2];

        this.monthlyCardCount.text = window['monthlyCardCount']?window['monthlyCardCount']:'66,666';
        this.yearCardCount.text = window['yearCardCount']?window['yearCardCount']:'666';
 
        this.setRandom1();
        this.setRandom2();
        this.setRandom3();
        egret.Tween.get(this.hammer,{loop:true})
        .to({rotation:-5}, 500)
        .to({rotation:0}, 500)
        .to({rotation:5},500)
        .to({rotation:0},500)
    }
    private setRandom1(){
        let random = Math.floor(Math.random()*500);
        setTimeout(() => {
            this.setTween(this.prizeEgg1);
        }, random);

    }
    private setRandom2(){
        let random = Math.floor(Math.random()*1200);
        setTimeout(() => {
            this.setTween(this.prizeEgg2);
        }, random);
    }
    private setRandom3(){
        let random = Math.floor(Math.random()*1800);
        setTimeout(() => {
            this.setTween(this.prizeEgg3);
        }, random);
    }
    private setTween(tweenNode){
        egret.Tween.get(tweenNode,{loop:true})
        .to({rotation:-10}, 400)
        .to({rotation:0}, 400)
        .to({rotation:10},400)
        .to({rotation:0},400)
        // .wait(300)
        // .call(function(){this.arrayIndex++;if(this.arrayIndex > 2){this.arrayIndex = 0;};this.setTween()}.bind(this))
        
    }
    private getParamString(name) {
        var reg=new RegExp('(^|&)'+name+'=([^&]*)(&|$)');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
           return unescape(r[2]);
        }
        return null;
    }

    //更新数据
    private updateRemainTimes(){
        NetManager.ins.getRemainTimes(function(success,result){
            let startDate = new Date(window['startTime'].replace(/-/g, '/')); 
            let startTime = startDate.valueOf();

            let endDate = new Date(window['endTime'].replace(/-/g, '/')); 
            let endTime = endDate.valueOf();
           
            if(!result)
            {
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                        content:["活动过于火爆，",'请稍后再试~']});
                return;
            }
            if(result && result.timestamp < startTime){
                console.log('服务器时间-',result.timestamp,'开始时间-',startTime);
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:3});
                return;
            }
            if(result && result.timestamp > endTime){
                console.log('服务器时间-',result.timestamp,'结束时间-',endTime);
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:1});
                return;
            }
            if(success){
                if(result.data.remainTimes){
                    this.drawTimelab.text = result.data.remainTimes + "次";
                }else{
                    this.drawTimelab.text = "0次";
                }
                
            }else{
                this.drawTimelab.text = "0次";
                switch (result.code) {
                    case '100197':
                        PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_NOTIME,
                                                content:["很抱歉，您无抽奖资格"]});
                        break;
                    case '100198':
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:2});
                        break;
                    case '14100012':
                        console.log("手动下线");
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:1});
                        break;
                    default:
                        this.networkErrorPopup();
                        break;
                }
                console.log('更新次数失败 code-',result.code);
            }
        }.bind(this));
    }
    private haveStock(){
        if(!DataManager.ins.getData('remainTimes').data.hasStock)
        {
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_NOSTOCK,
                                    content:["活动过于火爆，奖品已发完~"]});
            return false;
        }
        return true;
    }
    //egret.lifecycle.onResume
    private onTap_prizeEgg(e:egret.TouchEvent){
        //console.log('敲击',e.target.name)
        if(!this.haveStock()){
            console.log('库存情况',DataManager.ins.getData('remainTimes'));
            return;
        }
        this.chooseEgg = e.target;
        this.prizeEgg1.touchEnabled = false;
        this.prizeEgg2.touchEnabled = false;
        this.prizeEgg3.touchEnabled = false;
        egret.Tween.removeTweens(this.hammer);
        egret.Tween.removeTweens(this.prizeEgg1);
        egret.Tween.removeTweens(this.prizeEgg2);
        egret.Tween.removeTweens(this.prizeEgg3);
        this.hammer.rotation = 0;
        this.prizeEgg1.rotation = 0;
        this.prizeEgg2.rotation = 0;
        this.prizeEgg3.rotation = 0;
        
        let eggId =this.chooseEgg.name.substr(this.chooseEgg.name.length -1 ,1);
        let eggPostation = 0;
        if(eggId == 1){
            eggPostation = 240;
        }
        if(eggId == 2){
            eggPostation = 470;
        }
        if(eggId == 3){
            eggPostation = 700;
        }
        let hammerSpeed = window['hammerSpeed']?window['hammerSpeed']:500;
        egret.Tween.get(this.hammer,{loop:false})
        .to({x:eggPostation,y:600}, hammerSpeed).call(function(){this.hammerMove = true;this.smashEggs()}.bind(this))

        if(DataManager.ins.getData('remainTimes').data.remainTimes < 1){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_NOTIME,
                content:["每日消费1笔即可获得砸蛋机会哦，",'每日最多获得1次砸蛋机会~']});
        }else{
            this.dostart();
        }
      
    }
    private smashEggs(){
        if(!this.hammerMove || !this.pollingEnd)
        {
            return;
        }
        this.hammerMove = true;
        this.pollingEnd = true;

        egret.Tween.get(this.hammer,{loop:false})
        .to({rotation:40}, 200)
        .to({rotation:-30}, 100)
        .wait(100)
        .call(function(){
            this.chooseEgg.texture = this.splitEgg;
        }.bind(this))
        .wait(100)
        .call(function(){
            this.chooseEgg.texture = this.brokenEgg;
        }.bind(this))
        .wait(300)
        .call(function(){
            this.handlePrize();
        }.bind(this))
        
    }
    private dostart(): void {
        NetManager.ins.doJoinWeBank(function(success: boolean,result){
            if(!result)
            {
                console.log("接口返回result出错");
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                        content:["活动过于火爆，",'请稍后再试~']});
                return;
            }
            if(success && DataManager.ins.doJoinData.code == '0000000000'){
                this.goGame();
            }else{
                console.log("返回code-",DataManager.ins.doJoinData.code);
                if(!DataManager.ins.doJoinData){
                    console.log('errorCode:数据出错');
                    return;
                }
                if (DataManager.ins.doJoinData.code == 'E100202007' || DataManager.ins.doJoinData.code == 'E100202008' || DataManager.ins.doJoinData.code == 'E100202009' || DataManager.ins.doJoinData.code == 'E100202010'){  
                    //次数已用完
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_TIMETOPLIMIT,
                                            content:["今天已经砸过蛋啦，",'每人每天只能砸1次蛋呦~']});

                }else if(DataManager.ins.doJoinData.code == 'E1002090020'){
                    console.log("尚有抽奖流程未结束");
                    this.winRecordPopup();
                }
                else{//未中奖
                    console.log("抽奖出错");
                    this.networkErrorPopup();
                }
            }
        }.bind(this));
    }
    private winRecordPopup(){
        PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_2,
                                content:["活动过于火爆，",'请稍后前往中奖记录查看是否中奖~']});
    }
    private networkErrorPopup(){
        PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
            content:["活动过于火爆，",'请稍后重试~']});
    }
    private goGame():void{
        let startDpmOut = Buried.connectDpm(110, 2, 1); 
        let startDcmOut = Buried.connectDcm(202, 0, 0); 
        let startDomOut = Buried.connectDom(this.channel); 
        let exposure = Buried.createExposureNew(startDpmOut, startDcmOut,startDomOut);
        NetManager.ins.clickLog(exposure);

        this.submit();
        let drawTime = DataManager.ins.getData('remainTimes').data.remainTimes - 1;
        this.drawTimelab.text = (drawTime>0?drawTime:0) + '次';
    }
    //捞奖
    private submit():void{
            NetManager.ins.getOrderStatusNew((data) => {
                if (data == 'pollingFaild' || !data) {
                    console.log('轮询失败：' + data);
                    this.winRecordPopup();
                }else{//出奖
                    this.pollingEnd = true;
                    this.smashEggs();
                }
            }, DataManager.ins.doJoinData.orderId, () => {
                return DataManager.ins.getCustomOrderStatusData.code == 'C000000001';
            });
    }

    private handlePrize(){
        console.log('中奖的奖品数据',DataManager.ins.getCustomOrderStatusData.lottery);
        if(DataManager.ins.getCustomOrderStatusData.lottery && DataManager.ins.getCustomOrderStatusData.lottery.itemId != window['thanks']){
            let lotteryData = DataManager.ins.getCustomOrderStatusData.lottery;
            let prizeUrl:string = '';
            if(window['DirectChargeInput'].indexOf(lotteryData.itemId) > -1)
            {
                prizeUrl = "/pages/coupon/prize?id=" + DataManager.ins.doJoinData.orderId + "&receive=true";
            }
            if(window['CDKeyType'].indexOf(lotteryData.itemId) > -1)
            {
                prizeUrl = "/pages/coupon/prize?id=" + DataManager.ins.doJoinData.orderId
            }
            if(window['ObjectType'].indexOf(lotteryData.itemId) > -1)
            {
                prizeUrl = "/pages/coupon/prize?id=" + DataManager.ins.doJoinData.orderId;
            }
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_WINPRIZE,
                content:[lotteryData.name],
                icon:lotteryData.img,
                url:prizeUrl,
            });
        }else if(DataManager.ins.getCustomOrderStatusData.lottery && DataManager.ins.getCustomOrderStatusData.lottery.itemId ==  window['thanks']){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_NOPRIZE,
                                    content:["抱歉，奖品与你擦肩而过"]});
        }
        else{
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                    content:["活动过于火爆，",'请稍后重试~']});
        }
    }
    //规则
    private onClickRule(){
        PanelCtrl.instance.btnDelay(this.ruleBtn);
        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL); 

        let startDpmOut = Buried.connectDpm(110, 1, 1); 
        let startDcmOut = Buried.connectDcm(202, 0, 0); 
        let startDomOut = Buried.connectDom(this.channel); 
        let exposure = Buried.createExposureNew(startDpmOut, startDcmOut,startDomOut);
        NetManager.ins.clickLog(exposure);

    }
    private onTap_prizeBtn():void{
        console.log('点击prizeBtn');

        let startDpmOut = Buried.connectDpm(110, 3, 1); 
        let startDcmOut = Buried.connectDcm(202, 0, 0); 
        let startDomOut = Buried.connectDom(this.channel); 
        let exposure = Buried.createExposureNew(startDpmOut, startDcmOut,startDomOut);
        NetManager.ins.clickLog(exposure);

        PanelCtrl.instance.btnDelay(this.recordLabBtn);
        SceneCtrl.instance.change(ModuleTypes.PRIZE_PANEL,{type:1});
    }

    private getMoble() {
        for(let i=0; i< 2; i++)
        {
            let dItem = new WinnerItemComponent();
            this.winPrizeGroup.addChild(dItem);
            dItem.x = 750;
            dItem.y = i * (22+35);
        }
    }
}