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";
import { NetName } from '../../libs/tw/enum/NetName';

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

    public timeLab:eui.Label;

    public playBtn_1:eui.Button;
    public playBtn_2:eui.Button;
    public playBtn_3:eui.Button;

    public selection_1:eui.Image;
    public selection_2:eui.Image;
    public selection_3:eui.Image;

    public card_1:eui.Image;
    public card_2:eui.Image;
    public card_3:eui.Image;

    public aniGroup:eui.Group;
    public cardGroup:eui.Group;

    public pageGroup:eui.Group;

    private mData;

    public bg:eui.Image;
    private bgTexture:egret.Texture;

    private pollingEnd:boolean = false;
    private playAniEnd:boolean = false;
    //是否可以点击翻牌抽奖
    private canDrow:boolean = true; 
    public get skinKey() { return 'StartScene' }
    public get groupName() { return 'start_scene' }

    private channel;
    constructor(data?) {
        super(data);//95fcf3
    }

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

        this.playBtn_1.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prize, this);
        this.playBtn_2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prize, this);
        this.playBtn_3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prize, this);
    }

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

        this.playBtn_1.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prize, this);
        this.playBtn_2.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prize, this);
        this.playBtn_3.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prize, this);
    }

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

    protected async preLoadRes() {

        this.bgTexture = await RES.getResAsync('stratBg_jpg');
        return new Promise(function (resolve) {
            resolve();
        });
        
    }
    protected onSkinComplete(): void {
        super.onSkinComplete();
        this.bg.texture = this.bgTexture;
        this.card_1.source = 'card_1_jpg';
        this.card_2.source = 'card_2_jpg';
        this.card_3.source = 'card_3_jpg';
        this.selection_1.source = 'selection_1_jpg';
        this.selection_2.source = 'selection_2_jpg';
        this.selection_3.source = 'selection_3_jpg';
        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
    }
  
    private onLoad(): void {
        console.log('用户uid',window['CFG'].uid);
        this.timeLab.text = '还剩0次翻牌机会';
        this.playAniEnd = false;
        this.pollingEnd = false;
        //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);

        let flopDpmOut = Buried.connectDpm(110, 4, 1); 
        let flopDcmOut = Buried.connectDcm(202, 0, 0); 
        let flopDomOut = Buried.connectDom(this.channel); 
        let flopExposure = Buried.createExposureNew(flopDpmOut, flopDcmOut,flopDomOut);
        NetManager.ins.showLog(flopExposure);

        let flopSuccessDpmOut = Buried.connectDpm(110, 5, 1); 
        let flopSuccessDcmOut = Buried.connectDcm(202, 0, 0); 
        let flopSuccessDomOut = Buried.connectDom(this.channel); 
        let flopSuccessExposure = Buried.createExposureNew(flopSuccessDpmOut, flopSuccessDcmOut,flopSuccessDomOut);
        NetManager.ins.showLog(flopSuccessExposure);
      
        if(this.mData && this.mData.refresh == false)
        {
            let timeData = DataManager.ins.getData('remainTimes').data.remainTimes>0 ? DataManager.ins.getData('remainTimes').data.remainTimes : 0;
            this.timeLab.text = `还剩${timeData}次翻牌机会`;
        }else if(this.mData && this.mData.refresh == 'abnormal'){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                                            content:["活动过于火爆，",'请稍后再试~']});
        }else if(this.mData && this.mData.refresh == 'notime'){
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_NOTIME,
                                                            content:["很抱歉，您无抽奖资格"]});
        }
        else{
            this.updateRemainTimes();
        }
    }

    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(){
        if(!this.activityTime()){
            this.timeLab.text = '还剩0次翻牌机会';
            return;
        }
        NetManager.ins.getRemainTimes(function(success,result){
           
            if(!result)
            {
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                        content:["活动过于火爆，",'请稍后再试~']});
                return;
            }
            if(success){
                if(result.data.remainTimes){
                    this.timeLab.text = `还剩${result.data.remainTimes}次翻牌机会`;
                }else{
                    this.timeLab.text = '还剩0次翻牌机会';
                }
                
            }else{
                this.timeLab.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;
                    case '14100007':
                        console.log("活动未开始");
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:3});
                        break;
                    default:
                        this.networkErrorPopup();
                        break;
                }
                console.log('更新次数失败 code-',result.code);
            }
        }.bind(this));
    }
    private haveStock(){
        console.log('库存情况',DataManager.ins.getData('remainTimes'));
        if(!DataManager.ins.getData('remainTimes').data.hasStock)
        {
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                    content:["活动过于火爆，奖品已发完~"]});
            return false;
        }
        return true;
    }
  
    private onTap_prize(e:egret.TouchEvent){
        if(!this.canDrow)
        {
            return;
        }
        this.canDrow = false;
        
        let flopDpmOut = Buried.connectDpm(110, 4, 1); 
        let flopDcmOut = Buried.connectDcm(202, 0, 0); 
        let flopDomOut = Buried.connectDom(this.channel); 
        let flopExposure = Buried.createExposureNew(flopDpmOut, flopDcmOut,flopDomOut);
        NetManager.ins.clickLog(flopExposure);

        if(!this.haveStock()) return;
        if(DataManager.ins.getData('remainTimes').data.remainTimes < 1){
            this.judgeIsPlay();
        }else{
            this.dostart(e.target.parent);
            //this.judgeIsPlay(e.target.parent);
            //this.playAni(e.target.parent);
        }
    }
    //判断是否有抽奖资格
    judgeIsPlay(){
        NetManager.ins.getJoinCount(function(success: boolean,result){
            if(!result)
            {
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                        content:["活动过于火爆，",'请稍后再试~']});
                return;
            }
            if(success){
                if( result.data == '0'){
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_NOTIME,
                        content:["很抱歉，您无抽奖资格"]});
                }else{
                    //this.dostart(parentNode);
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_TIMETOPLIMIT,
                        content:["每日消费1笔即可获得砸蛋机会哦，",'每日最多获得1次砸蛋机会~']});
                }
            }else{
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                    content:["活动过于火爆，",'请稍后再试~']});
            }
        }.bind(this));
    }

    //翻牌动画
    //卡片移动到中间
    playAni(cardNode){
        this.aniGroup.x = cardNode.x;
        
        let card:eui.Image = cardNode.getChildByName('card');
        let aniCard:any = this.aniGroup.getChildByName('card');
        aniCard.texture = card.texture;
    
        this.aniGroup.y = cardNode.y;
        this.aniGroup.scaleX = cardNode.scaleX;
        this.aniGroup.scaleY = cardNode.scaleY;
        cardNode.visible = false;
        this.aniGroup.visible = true;

        egret.Tween.get(this.aniGroup,{loop:false})
        .to({x:375,y:812,scaleX:1.5,scaleY:1.5},500,egret.Ease.backIn)
        .wait(300)
        .call(()=>{
            cardNode.visible = false;
            this.aniGroup.visible = true;
            this.playAniRotation(cardNode);
        })
       
    }
    //卡片翻滚及返回原处
    playAniRotation(cardNode){
        egret.Tween.get(this.aniGroup,{loop:false})
        .to({scaleX:-1.5},450,egret.Ease.cubicIn)
        .to({scaleX:1.5},200)
        .to({scaleX:-1.5},200)
        .to({scaleX:1.5},650,egret.Ease.cubicOut)
        .wait(300)
        .to({x:cardNode.x,y:cardNode.y,scaleX:1,scaleY:1},500,egret.Ease.backIn)
        .call(()=>{
            cardNode.visible = true;
            this.aniGroup.visible = false;
            this.playAniMove(cardNode);
        })
    }
    //卡片上移
    playAniMove(cardNode){
        let selection = this.pageGroup.getChildByName('selection_' + cardNode.name);
        if(!selection)return;
        egret.Tween.get(cardNode,{loop:false})
        .wait(400)
        .to({y:selection.y},300,egret.Ease.backIn)
        .wait(200)
        .call(()=>{
            cardNode.visible = false;
            selection.visible = true;
            this.playAniScale(selection);
        })
    }
    //出现金边卡片
    playAniScale(selection){
        egret.Tween.get(selection,{loop:false})
        .to({scaleX:1.1,scaleY:1.1},300,egret.Ease.bounceOut)
        .call(()=>{
            this.playAniEnd = true;
            setTimeout(() => {
                this.handlePrize();
            }, 500);
        })
    }
    private dostart(parentNode:any): void {
        NetManager.ins.doJoinWeBank(function(success: boolean,result){
            if(!result)
            {
                console.log("/hdtool/webank/doJoin接口错误");
                PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                                        content:["活动过于火爆，",'请稍后再试~']});
                return;
            }
            if(success && DataManager.ins.doJoinData.code == '0000000000'){
                //开始
                this.goGame();
                this.playAni(parentNode);
            }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'){  
                    //次数已用完
                    console.log('dojoin无次数')
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_TIMETOPLIMIT,
                                            content:["每日消费1笔即可获得砸蛋机会哦，",'每日最多获得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 flopDpmOut = Buried.connectDpm(110, 5, 1); 
        let flopDcmOut = Buried.connectDcm(202, 0, 0); 
        let flopDomOut = Buried.connectDom(this.channel); 
        let flopExposure = Buried.createExposureNew(flopDpmOut, flopDcmOut,flopDomOut);
        NetManager.ins.clickLog(flopExposure);

        this.submit();
        let drawTime = DataManager.ins.getData('remainTimes').data.remainTimes - 1;
        this.timeLab.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.handlePrize();
                }
            }, DataManager.ins.doJoinData.orderId, () => {
                return DataManager.ins.getCustomOrderStatusData.code == 'C000000001';
        });
    }
    private handlePrize(){
        if(!this.pollingEnd || !this.playAniEnd) return;
        this.canDrow = true;
        let lotteryData = DataManager.ins.getCustomOrderStatusData.lottery;
        console.log('中奖奖品数据',lotteryData);
        if(lotteryData && lotteryData.itemId != window['thanks']){
            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(lotteryData && lotteryData.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);

        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.show(ModuleTypes.RULE_PANEL); 
    }
    private onTap_prizeBtn():void{
        PanelCtrl.instance.btnDelay(this.prizeBtn);

        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);

        SceneCtrl.instance.change(ModuleTypes.PRIZE_PANEL,{type:1});
    }

    private activityTime(){
        let data = DataManager.ins.ajaxElementDataNew.getTimestamp;
        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(data < startTime){
            console.log('服务器时间-',data,'开始时间-',startTime);
            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:3});
            return false;
        }
        if(data > endTime){
            console.log('服务器时间-',data,'结束时间-',endTime);
            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{type:1});
            return false;
        }
        return true;
    }
}