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';
export default class StartScene extends Scene {
    public mainbg:eui.Image;
    public ruleBtn:eui.Button;
    public prizeBtn:eui.Button;
    public shareBtn:eui.Button;
    public timesLb:eui.Label;
    public startBtn:eui.Button;    

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

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

    initEvents() {
        super.initEvents();
        this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_this, this);
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.startBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_startBtn, this);
        this.prizeBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_prizeBtn, this);
        this.shareBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
    }

    removeEvents() {
        super.removeEvents();

        this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_this, this);
        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.shareBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_shareBtn, this);
    }


    onTap_shareBtn(){
        window.location.href=`http://www.abchina.com/luascript/shareOnClick/{"return":{"share_title":"中国农业银行无感支付","share_text":"无感支付是一种不需刷卡，抬杆即走的快捷支付产品","share_url":"http://wechatshare.com?id=000001","share_img_url":"https://enjoy.abchina.com/yh-web/file/download/UINB28289CNA289NA3"}}`
    }

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

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

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

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

        this.mainbg.texture = this.bgtexture;

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

    private onLoad(): void {

        this.initUI();

    }

    private initUI():void{
        this.timesLb.text = '··········  今日免费次数:' + DataManager.ins.ajaxElementDataNew.element.freeLimit + '次  ··········';
        PanelCtrl.instance.isLoseCoin = false;
        egret.Tween.get(this.startBtn, {loop:true})
            .to({scaleX:1.05, scaleY:1.05}, 150)
            .to({scaleX:0.9, scaleY:0.9}, 150)
            .to({scaleX:1.05, scaleY:1.05}, 150)
            .to({scaleX:0.9, scaleY:0.9}, 150).wait(500);

    }

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

    private onTap_startBtn():void{
        PanelCtrl.instance.btnDelay(this.startBtn);
        
        this.dostart();
    }

    //首页点击埋点
    private onTap_this():void{
    }

    private dostart(): void {
        Loading.instace.show();
        // if(DataManager.ins.ajaxElementDataNew.element.freeLimit < 1){
        //     PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'您的次数已不足！'});
        //     return;
        // }
        NetManager.ins.doJoinNew(function(success: boolean){
            if(success && DataManager.ins.doJoinData.code == '0000000000'){
                //二阳要求的延迟500s
                setTimeout(() => {
                    NetManager.ins.getNgameStartStatus(function(data){
                        if (data == 'pollingFaild' || !data) {
                            //此时不能中奖
                            PanelCtrl.instance.isLoseCoin = true;
                            // SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                            this.goGame();
                            return;
                        } else {
                            // SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                            this.goGame();
                        }
                    }.bind(this), DataManager.ins.doJoinData.orderId, () => {
                        return !(DataManager.ins.getNgameStartStatusData.code == '0000000000');
                    });
                }, 500);
            }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.MSG_PANEL, {type:0});
                }else if(DataManager.ins.doJoinData.code == 'E100201001' || DataManager.ins.doJoinData.code == 'E100201002'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'小主，您还未登录\n请登录后再玩吧~'});
                }else if(DataManager.ins.doJoinData.code == 'E100202002'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'活动不存在！'});
                }else if(DataManager.ins.doJoinData.code == 'E100201007'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'用户积分不足！'});
                }else{
                    //未中奖
                    PanelCtrl.instance.isLoseCoin = true;
                    // SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
                    this.goGame();
                }
                Loading.instace.hide();
            }
        }.bind(this));
    }

    //跳转游戏页
    private goGame(isdemo:boolean = false):void{
        const isfirst = GCache.readCache('showGuide');
        if (!isfirst) {
            GCache.writeCache('showGuide', 'true');
            PanelCtrl.instance.show(ModuleTypes.GUIDE_PANEL, isdemo);
        }else{
            if(isdemo){
                SceneCtrl.instance.change(ModuleTypes.GAME_SCENE, {isdemo:true});
            }else{
                SceneCtrl.instance.change(ModuleTypes.GAME_SCENE);
            }
        }
    }

    private onTap_prizeBtn():void{
        console.log('点击prizeBtn'); 
        PanelCtrl.instance.btnDelay(this.prizeBtn);
        window.location.href = this.gotoRecord();//window["recordUrl"];
    }

    //获取我的奖品
    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();
    }
    

}
