import { GCache } from './../libs/tc/util/GCache';
import { Buried } from './../libs/tw/util/Buried';

import layers from "./views/layers";
import { getResPath } from "./utils";
import AssetAdapter from "./AssetAdapter";
import ThemeAdapter from "./ThemeAdapter";
import { DataManager } from "../libs/tw/manager/DataManager";
import Loading from "./loading/Loading";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import { ModuleTypes,PopupType} from './types/sceneTypes';
import { NetManager } from '../libs/tw/manager/NetManager';
import MsgPanel from './msgPanel/MsgPanel';
import PrizePanel from './prizePanel/PrizePanel';
import RulePanel from './rulePanel/RulePanel';
import ToastPanel from './toastPanel/ToastPanel';
import StartScene1 from './startScene/StartScene';
import { MsgBoxType } from './types/sceneTypes';
import { MsgButtonType } from './types/sceneTypes';
import { NetName } from '../libs/tw/enum/NetName';


class Main extends eui.UILayer {
    protected createChildren(): void {
        super.createChildren();
        // alert(1)

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        //遇到输入框注释掉这个代码
        // egret.lifecycle.onPause = () => {
        //     egret.ticker.pause();
        // }

        // egret.lifecycle.onResume = () => {
        //     egret.ticker.resume();
        // }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());

        egret.ImageLoader.crossOrigin = "anonymous";

        // 老游戏
        // DataManager.ins.gameCfgData = window['CFG'];
        // DataManager.ins.gameCfgData.gameInfo.gameId = window['gameId'];

        //新游戏cfg
        DataManager.ins.customCfgData = window['CFG'];

        GCache.init([DataManager.ins.customCfgData.actId + '', DataManager.ins.customCfgData.consumerId + '']);

        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        // Buried.init();

        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;

        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene1);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        

        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        this.resErrorListener();
        // RES.loadGroup("msg", 10);
    }

    private resErrorListener(): void {
        //添加资源组加载失败事件
        // RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceError, this);
        // //添加资源加载失败事件
        // RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onResourceError, this);
    }

    private onResourceError(): void {
        let msg = '请刷新重试';
        // if(PanelCtrl.instance.isLoseCoin){
        //     msg = '请联系客服找回积分';
        // }else{
        //     msg = '请刷新重试';
        // }
        // console.log('isLoadedMsg' + PanelCtrl.instance.isLoadedMsg);

        if (PanelCtrl.instance.isLoadedMsg) {
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL,{msgType:PopupType.POPUPTYPE_ABNORMAL_1,
                content:["活动过于火爆，",'请稍后再试~']});
        } else {
            alert('网络开小差了\n' + msg);
        }
    }

    private async loadResource() {
        try {
            // const loadingView = new LoadingUI();
            // this.stage.addChild(loadingView);
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
            // await RES.loadGroup("msg", 10);
            // this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        //获取游戏信息
        Loading.instace.show();

        NetManager.ins.ajaxElementNew(function(success,result){
            //console.log(DataManager.ins.ajaxElementDataNew);
            this.getGameRes(success);
            
        }.bind(this));

    }

    //加载游戏中的资源
    private async getGameRes(success:boolean){
        //await RES.loadGroup('common');
        await RES.getResAsync('stratBg_jpg');

        if(success && DataManager.ins.ajaxElementDataNew.code == '0000000000'){
            Buried.init();
            await RES.loadGroup('start_scene');
            if(!this.activityTime())
            {
                return;
            }
            NetManager.ins.getRemainTimes(function(success,data){
                if(!data)
                {
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE,{refresh:'abnormal'});
                    return;
                }
                if(success){
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE,{refresh:false});
                }
                else{
                    switch (data.code) {
                        //用户被锁定
                        case '100197':
                            SceneCtrl.instance.change(ModuleTypes.START_SCENE,{refresh:'notime'});
                            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:
                            SceneCtrl.instance.change(ModuleTypes.START_SCENE,{refresh:'abnormal'});
                            break;
                    }
                    console.log('更新次数失败');
                    console.log('更新次数失败main code-',data.code);
                }
            }.bind(this));
           
        }else{
            SceneCtrl.instance.change(ModuleTypes.START_SCENE,{refresh:'abnormal'});
        }
        Loading.instace.hide();

    }
       //1586486292000  
       //1548832971636
    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;
    }

}

window['Main'] = Main;