import { setSoundOn } from './../ctrls/soundCtrl';
import { DataManager } from './../../libs/tw/manager/DataManager';
import { ModuleTypes } 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 Loading from '../loading/Loading';
import { Buried } from '../../libs/tw/util/Buried';
import { GCache } from '../../libs/tc/util/GCache';
import { playBg, toggleSound } from '../ctrls/soundCtrl';
import { GTime } from '../../libs/tc/util/GTime';
import { TimeFormat } from '../../libs/tc/enum/TimeFormat';
export default class StartScene extends Scene {
    
    public ruleBtn:eui.Button;
    public moreBtn:eui.Button;
    public prizeBtn:eui.Button;
    public startBtn:eui.Button;
    public startBtn2:eui.Button;
    public startBtn3:eui.Button;
    public uiGroup:eui.Group;
    public effMcGroup:eui.Group;
    public act0:egret.tween.TweenGroup;

    public timeTickLb:eui.Label;
    public integralLb:eui.Label;
    public titleLb:eui.Label;

    public mainbg:eui.Image;

    private effMc:egret.MovieClip;
    private currBtn:eui.Button;
    private desTime:number;

    private isEnd:boolean;

    public get skinKey() { return 'StartScene' }
    public get groupName() { return 'start_scene' }

    constructor(data?) {
        super(data);//95fcf3

        this.isEnd = this.data;
    }

    initEvents() {
        super.initEvents();

        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        this.startBtn2.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn2, this);
        this.startBtn3.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn3, this);
        this.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        this.moreBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_moreBtn, this);
        // this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_this, this);
    }

    removeEvents() {
        super.removeEvents();
        if(this.ruleBtn){
            this.ruleBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
            this.startBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
            this.prizeBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
            this.startBtn3.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn3, this);
            this.startBtn2.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn2, this);
            this.moreBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_moreBtn, this);
            // this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_this, this);

        }
    }

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

    }

    private bgtexture: egret.Texture;
    protected async preLoadRes() {
        //加载背景并设置背景图片
        this.bgtexture = await RES.getResAsync('startBg_jpg');

        var mcJson = await RES.getResAsync('effect_json');
        var mcImg = await RES.getResAsync('effect_png');
        var mcFactory = new egret.MovieClipDataFactory(mcJson, mcImg);

        this.effMc = new egret.MovieClip(mcFactory.generateMovieClipData());
        // console.log('载背景并设置背景图片mainscene');

        return new Promise(function (resolve, reject) {
            resolve();
        });
    }

    protected onSkinComplete(): void {
        super.onSkinComplete();

        this.timeTickLb.text = '';
        this.mainbg.texture = this.bgtexture;

        this.once(egret.Event.ADDED_TO_STAGE, this.onLoad, this);
        if (this.stage) {
            this.onLoad();
        }
    }

    private onLoad(): void {

        let startDpmOut = Buried.connectDpm(110, 1, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.showLog(exposure);

        let startDpmOut1 = Buried.connectDpm(110, 2, 1); // 点击埋点   
        let startDcmOut1 = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure1 = Buried.createExposure(startDpmOut1, startDcmOut1);

        NetManager.ins.showLog(exposure1);

        let startDpmOut2 = Buried.connectDpm(110, 13, 1); // 点击埋点   
        let startDcmOut2 = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure2 = Buried.createExposure(startDpmOut2, startDcmOut2);

        NetManager.ins.showLog(exposure2);

        this.initUI();

    }

    private initUI():void{
        this.playAnimation(this.act0);
        this.effMc.play(-1);
        this.effMcGroup.addChild(this.effMc);
        
        this.desTime = window['desTime'] ? window['desTime'] : 0;

        this.initTime();

        this.uiGroup.alpha = 0;
        egret.Tween.get(this.uiGroup).to({alpha:1}, 500);
    }

    //初始化时间
    private initTime():void{
        egret.Tween.removeTweens(this.timeTickLb);
        if(this.currBtn){
            egret.Tween.removeTweens(this.currBtn);
        }
        this.moreBtn.visible = false;

        let idata = DataManager.ins.getInformationZhaohangData.data;
        let startTime;
        let endTime;

        //活动结束的特殊处理
        if(this.isEnd){
            console.log('1111111')
            idata = {isNewActivityGuide:true, todayTimesIsEnd:true};
        }else{

            console.log('22222222')
            startTime = idata.scenes[0].startTime - idata.serverTime + this.desTime;
            endTime = idata.scenes[0].endTime - idata.serverTime  - this.desTime;;
            console.log('startTime='+startTime);
        }

        if(idata.isNewActivityGuide && idata.todayTimesIsEnd){//如果是最后一天
            this.startBtn.visible = false;
            this.startBtn2.visible = false;
            this.startBtn3.visible = false;
            this.moreBtn.visible = true;

            this.titleLb.text = '';
            this.timeTickLb.text = '活动已结束';

            this.currBtn = this.moreBtn;
        }else{

            if(endTime <= 0){
                console.log('不应该出现当前状态');
                this.startBtn.visible = false;
                this.startBtn2.visible = false;
                this.startBtn3.visible = false;
                this.moreBtn.visible = false;

            }else{
                if(startTime > 0){

                    this.titleLb.text = '开始倒计时';
                    startTime = Math.floor(startTime / 1000);
                    this.timeTickLb.text = GTime.formatTime(startTime, TimeFormat.HMS, false,[':',':','','']);
                    egret.Tween.get(this.timeTickLb, {loop:true}).wait(1000).call(() => {
                        startTime --;
                        this.timeTickLb.text = GTime.formatTime(startTime, TimeFormat.HMS, false,[':',':','','']);
                        if(startTime <= 0){
                            // egret.Tween.removeTweens(this.timeTickLb);
                            startTime = Math.floor(endTime / 1000);

                            this.startBtn.currentState = '';
                            this.startBtn.touchEnabled = true;

                            this.titleLb.text = '本场结束倒计时';

                            egret.Tween.get(this.startBtn, {loop:true})
                            .to({scaleX:1.1, scaleY:1.1}, 150)
                            .to({scaleX:0.9, scaleY:0.9}, 150)
                            .to({scaleX:1.1, scaleY:1.1}, 150)
                            .to({scaleX:0.9, scaleY:0.9}, 150).wait(500);

                        }
                    });
                    this.startBtn.visible = true;
                    this.startBtn2.visible = false;
                    this.startBtn3.visible = false;
                    this.moreBtn.visible = false;

                    this.startBtn.currentState = 'disabled';
                    this.startBtn.touchEnabled = false;
                }else{

                    this.titleLb.text = '本场结束倒计时';
                    
                    console.log('endTime=',endTime);
                    endTime = Math.floor(endTime / 1000);
                    this.timeTickLb.text = GTime.formatTime(endTime, TimeFormat.HMS, false,[':',':','','']);
                    egret.Tween.get(this.timeTickLb, {loop:true}).wait(1000).call(() => {
                        endTime --;
                        this.timeTickLb.text = GTime.formatTime(endTime, TimeFormat.HMS, false,[':',':','','']);
                        if(endTime <= 0){
                            // egret.Tween.removeTweens(this.timeTickLb);
                            if(idata.isNewActivityGuide){
                                this.startBtn.visible = false;
                                this.startBtn2.visible = false;
                                this.startBtn3.visible = false;
                                this.moreBtn.visible = true;
                    
                                this.titleLb.text = '';
                                this.timeTickLb.text = '活动已结束';
                    
                                this.currBtn = this.moreBtn;

                                egret.Tween.removeTweens(this.timeTickLb);
                            }else{
                                endTime = 22 * 60 * 60;
                                this.titleLb.text = '开始倒计时';
                                
                                this.startBtn.visible = true;
                                this.startBtn2.visible = false;
                                this.startBtn3.visible = false;
                                this.moreBtn.visible = false;
                
                                this.startBtn.currentState = 'disabled';
                                this.startBtn.touchEnabled = false;

                                this.currBtn = null;
                            }
                        }
                    });

                    if(idata.joinTimes > 0){

                        if(idata.joinTimes == 1){
                            if(idata.ifCanAddJoinTimesByShare){

                                this.moreBtn.visible = false;
                                this.startBtn.visible = false;
                                this.startBtn2.visible = false;
                                this.startBtn3.visible = true;
                                this.currBtn = this.startBtn3;
        
        
                                this.startBtn3.currentState = '';
                                this.startBtn3.touchEnabled = true;


                                let startDpmOut5 = Buried.connectDpm(110, 4, 1); // 点击埋点   
                                let startDcmOut5 = Buried.connectDcm(202, 0, 0); // 曝光埋点
                                let exposure5 = Buried.createExposure(startDpmOut5, startDcmOut5);

                                NetManager.ins.showLog(exposure5);
                            }else{

                                this.moreBtn.visible = false;
                                this.startBtn.visible = false;
                                this.startBtn2.visible = true;
                                this.startBtn3.visible = false;
        
                                this.startBtn2.currentState = '';
                                this.startBtn2.touchEnabled = true;

                                this.currBtn = this.startBtn2;

                                let startDpmOut4 = Buried.connectDpm(110, 5, 1); // 点击埋点   
                                let startDcmOut4 = Buried.connectDcm(202, 0, 0); // 曝光埋点
                                let exposure4 = Buried.createExposure(startDpmOut4, startDcmOut4);

                                NetManager.ins.showLog(exposure4);
                            }
                        }else{
                            
                            this.moreBtn.visible = false;
                            this.startBtn.visible = false;
                            this.startBtn2.visible = true;
                            this.startBtn3.visible = false;

                            this.startBtn2.currentState = 'disabled';
                            this.startBtn2.touchEnabled = false;
                        }

                    }else{
                        let startDpmOut3 = Buried.connectDpm(110, 3, 1); // 点击埋点   
                        let startDcmOut3 = Buried.connectDcm(202, 0, 0); // 曝光埋点
                        let exposure3 = Buried.createExposure(startDpmOut3, startDcmOut3);
                
                        NetManager.ins.showLog(exposure3);

                        this.moreBtn.visible = false;
                        this.startBtn.visible = true;
                        this.startBtn2.visible = false;
                        this.startBtn3.visible = false;
                        this.startBtn.currentState = '';
                        this.startBtn.touchEnabled = true;

                        this.currBtn = this.startBtn;

                    }
                }
            }
        }
        
        // PanelCtrl.instance.isLoseCoin = false;

        if(this.currBtn){
            egret.Tween.get(this.currBtn, {loop:true})
            .to({scaleX:1.1, scaleY:1.1}, 150)
            .to({scaleX:0.9, scaleY:0.9}, 150)
            .to({scaleX:1.1, scaleY:1.1}, 150)
            .to({scaleX:0.9, scaleY:0.9}, 150).wait(500);

        }
    }

    private onTap_ruleBtn():void{
        console.log('点击rule');
        PanelCtrl.instance.btnDelay(this.ruleBtn);


        let startDpmOut = Buried.connectDpm(110, 1, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);

        PanelCtrl.instance.show(ModuleTypes.RULE_PANEL); 
    }

    //马上开抢
    private onTap_startBtn():void{
        PanelCtrl.instance.btnDelay(this.startBtn);
        
        let startDpmOut = Buried.connectDpm(110, 3, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);
        this.dostart();

    }

    //立即开抢夺
    private onTap_startBtn2():void{
        PanelCtrl.instance.btnDelay(this.startBtn2);
        
        let startDpmOut = Buried.connectDpm(110, 5, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);
        this.dostart();

    }

    //分享
    private onTap_startBtn3():void{
        PanelCtrl.instance.btnDelay(this.startBtn3);

        let startDpmOut = Buried.connectDpm(110, 4, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);

        var param = {
			"shareTitle" : window['shareTitle'] ? window['shareTitle'] : '下载苏州银行APP 百万豪礼免费拿',// 标题
			"shareTextUrl" : window['shareTextUrl'] ? window['shareTextUrl'] : 'https://www.baidu.com',//window.basePath + '/page/conductBuy/cBuyMain.html',// 链接
			"shareText" : window['shareText'] ? window['shareText'] : '下载苏州银行APP 百万豪礼免费拿'// 分享文本内容
        };
        if(window['ThirdApp']){
            window['ThirdApp'].webviewShare(param);
            console.log('ThirdApp',window['ThirdApp']);
            console.log('param',param);
            console.log('webviewShare',window['ThirdApp'].webviewShare);
        }
        Loading.instace.show();
        NetManager.ins.shareZhaohang((success) => {
            if(success && DataManager.ins.getShareZhaohangData.code == '0000000000'){
                setTimeout(() => {    
                    PanelCtrl.instance.show(ModuleTypes.GAMEOVER_PANEL, {type: 0, isstart:true});

                    Loading.instace.hide();
                }, 5000);
            }else{
                Loading.instace.hide();
            }
        }, DataManager.ins.getInformationZhaohangData.data.scenes[0].scene, DataManager.ins.customCfgData.actId, DataManager.ins.getInformationZhaohangData.data.recentJoinResult ? DataManager.ins.getInformationZhaohangData.data.recentJoinResult : 1);

    }

    //刷新游戏数据
    private goStart():void{
        
        NetManager.ins.ajaxElementNew(function(success){
            console.log(DataManager.ins.ajaxElementDataNew);
            if(success && DataManager.ins.ajaxElementDataNew.code == '0000000000'){
                NetManager.ins.informationZhaohang((success) => {
                    if(success){    
                        //初始化首页时间按钮状态
                        this.initTime();
                    }else{
                        if(DataManager.ins.getInformationZhaohangData.code == 'E1002060003'){
                            SceneCtrl.instance.change(ModuleTypes.START_SCENE, true);
                        }else{
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'获取场次信息失败，请刷新重试'});
                        }
                    }
                }, DataManager.ins.customCfgData.actId);
            }else{
                // console.log('errorCode:' + DataManager.ins.doJoinData.code);
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'请刷新重试', line: 1});
                // PanelCtrl.instance.show(ModuleTypes.WARNING_PANEL, {idx:1});
                Loading.instace.hide();
            }
        }.bind(this));
    }

    private dostart(): void {
        Loading.instace.show();
        // if(DataManager.ins.ajaxElementDataNew.element.freeLimit < 1){
        //     // PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'您的次数已不足！'});

        //     PanelCtrl.instance.show(ModuleTypes.WARNING_PANEL, () =>{
        //         this.doJion();
        //     });
        // }else{
        // }
        NetManager.ins.informationZhaohang((success) => {
            if(success){
                this.doJion();
            }else{
                if(DataManager.ins.getInformationZhaohangData.code == 'E1002060003'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动结束了！'});
                }else{
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'获取场次信息失败，请刷新重试'});
                }
            }
        }, DataManager.ins.customCfgData.actId);
    }

    private doJion():void{
        let type = '';
        if(DataManager.ins.getInformationZhaohangData.data.joinTimesDetail 
            && DataManager.ins.getInformationZhaohangData.data.joinTimesDetail.length){
            type = DataManager.ins.getInformationZhaohangData.data.joinTimesDetail[0].type;
        }else{
            type = '';
        }
        PanelCtrl.instance.isLoseCoin = false;
        NetManager.ins.doJoinZhaohang(function(success: boolean){
            if(success && DataManager.ins.doJoinData.code == '0000000000'){
                NetManager.ins.getNgameStartStatus(function(data){
                    if (data == 'pollingFaild' || !data) {
                        //此时不能中奖
                        PanelCtrl.instance.isLoseCoin = true;
                        SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                        return;
                    } else {
                        SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                    }
                }.bind(this), DataManager.ins.doJoinData.orderId, () => {
                    return !(DataManager.ins.getNgameStartStatusData.code == '0000000000');
                });
            }else{
                if(DataManager.ins.doJoinData){
                    console.log('errorCode:' + DataManager.ins.doJoinData.code);
                }
                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.TOAST_PANEL, {msg:'已达到次数上限！', line: 1});
                    Loading.instace.hide();
                }else if(DataManager.ins.doJoinData.code == 'E100201007'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'您的积分不足！'});
                    Loading.instace.hide();
                }else{//未中奖
                    PanelCtrl.instance.isLoseCoin = true;
                    Loading.instace.hide();
                    SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                }
            }
        }.bind(this),type , DataManager.ins.getInformationZhaohangData.data.currentTimes);
    }

    private onTap_prizeBtn():void{
        console.log('点击prizeBtn'); 
        PanelCtrl.instance.btnDelay(this.prizeBtn);


        let startDpmOut = Buried.connectDpm(110, 2, 1); // 点击埋点   
        let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure = Buried.createExposure(startDpmOut, startDcmOut);

        NetManager.ins.clickLog(exposure);

        window.location.href = this.gotoRecord();//window["recordUrl"];
    }

    private onTap_moreBtn():void{
        PanelCtrl.instance.btnDelay(this.moreBtn);
        if(window['moreGame']){
            window.location.href = window['moreGame']
        }
    }

    private onTap_this():void{

        PanelCtrl.instance.btnDelay(this);

        let startDpmOut2 = Buried.connectDpm(110, 13, 1); // 点击埋点   
        let startDcmOut2 = Buried.connectDcm(202, 0, 0); // 曝光埋点
        let exposure2 = Buried.createExposure(startDpmOut2, startDcmOut2);

        NetManager.ins.clickLog(exposure2);
    }

    //获取我的奖品
    private gotoRecord():string{
        let recordUrl: string;
        let oaId: number;
        if (DataManager.ins.customCfgData) {
            oaId = DataManager.ins.customCfgData.oaId;
            recordUrl = DataManager.ins.customCfgData.recordUrl;
        } else {
            oaId = DataManager.ins.gameCfgData.gameInfo.oaId;
            recordUrl = window['recordUrl'];
        }

        if(recordUrl.indexOf('?') != -1){
            recordUrl += '&origins=' + oaId + '00';
        }else{
            recordUrl += '?origins=' + oaId + '00';
        } 
        // recordUrl += ',' + (window['plugId'] ? window['plugId'] : 4500) + '01';

        // for(let i = 0; i < window['plugIdArr'].length; i++){
        //     recordUrl += ',' + window['plugIdArr'][i] + '01';
        // }

        return recordUrl;
    }

    //循环播放动画
	private playAnimation(target: egret.tween.TweenGroup, isLoop: boolean = true): void {
		if (isLoop) {
			for (var key in target.items) {
				target.items[key].props = { loop: true };
			}
		}
		target.play();
    }
    

}
