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 { NetName } from '../../libs/tw/enum/NetName';
import { NetBuried } from '../NetBuried';
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(){
        PanelCtrl.instance.btnDelay(this.shareBtn);
        setTimeout(()=>{
           // window.location.href=`http://www.abchina.com/luascript/shareOnClick/{"return":{"share_title":"老表！光棍节脱单有望啦！","share_text":"上农行APP玩口红机，女神喜欢的口红轻松赢到手！","share_url":"https://activity-2.m.duiba.com.cn/customShare/share?id=3641","share_img_url":"https://yun.duiba.com.cn/db_games/activity/kouhongji_jxnonghang/share_img.jpg"}}`
        },500)
        NetBuried.ins.clickLog(1)
    }
    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();
        }
        NetBuried.ins.showLog(1)
        NetBuried.ins.showLog(2)
    }

    private onLoad(): void {

        this.initUI();
        this.doUserLimit(false)
    }

    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);
        NetBuried.ins.clickLog(2)
        this.doUserLimit(true);
    }

    //首页点击埋点
    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;
    }

    doUserLimit(state){
       NetManager.ins.getPhoneStatus((success)=>{
            if(!success){
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg:'请刷新重试'});
                return false;
            }
            if(DataManager.ins.getData(NetName.GET_PHONE_STATUS).data==0){
                PanelCtrl.instance.show(ModuleTypes.INPUTPHONE_PANEL)
                return false;
            }else if(DataManager.ins.getData(NetName.GET_PHONE_STATUS).data==2){
                PanelCtrl.instance.show(ModuleTypes.SORRY_PANEL)
                return false;
            }
            if(state){
                this.dostart()
            }
            
       },window["CFG"].actId)
    }

    //循环播放动画
	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();
    }
    

}
