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 } from './types/sceneTypes';
import { NetManager } from '../libs/tw/manager/NetManager';
import ToastPanel from './toastPanel/ToastPanel';
import StartScene1 from './startScene/StartScene';
import TopLayerCtrl from './ctrls/topLayerCtrl';
import { NetName } from '../libs/tw/enum/NetName';
import GameScene from './gameScene/GameScene';
import GuidePanel from './guidePanel/GuidePanel';
import RulePanel from './rulePanel/RulePanel';
import PrizePanel from './prizePanel/PrizePanel';
import MsgPanel from './msgPanel/MsgPanel';

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.getGameInfoData = {};
        window['CFG'] = {};
        if(window['isdebug']) {
            window['CFG'].projectId = '/projectx';// + '/' + window.location.pathname.split('/')[2];
        } else {
            window['CFG'].projectId = '/projectx' + '/' + window.location.pathname.split('/')[2];
        }

        window['space'] = 100;

        if(decodeURIComponent(this.getQueryString('str')) == 'app') {
            window['isresult'] = false;
        } else if(decodeURIComponent(this.getQueryString('str')) == 'weixin') {
            window['isresult'] = true;
        } else {
            window['isresult'] = false;
        }
        // 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);
        TopLayerCtrl.instance.init(layers.topLayer);
        Buried.init();
        Buried.appId = window['appid'] ? window['appid'] : 70398;
        Buried.oaId = window.location.pathname.split('/')[2];

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

        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene1);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.GAME_SCENE, GameScene);


        TopLayerCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.GUIDE_PANEL, GuidePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        var param = {
            "callback": 'modelRe'
        }
        // if(window['ThirdApp']){
        //     window['ThirdApp'].getNewDeviceInfo(param);
        // }

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

    // private modelRe(rpdata) {
    //     if(rpdata){
    //      window['isapp'] = true //端内
    //    }
    // }
    //获取Cookie信息
    private getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if(arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }

    /**
     * 获取url后面的参数值
     * name ：参数键值
     */
    private getQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if(r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    private async runGame() {

        console.log('this.stage.innerHeight', window.innerHeight);
        console.log('this.stage.stageWidth', window.innerWidth);

        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.showMsg('okBtn', 4, null, null, msg);

        } 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();
        //进度条
        // SceneCtrl.instance.change(ModuleTypes.LOADIND_SCENE);
        NetManager.ins.getHomeInfo((success1) => {
            // this.getGameRes(success1);
            if(success1) {
                this.getGameRes(success1);
            } else {
                let data = DataManager.ins.getData(NetName.GET_HOME_INFO);
                if(data && data.code == '100002'){
                    this.getGameRes(true);
                    // TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '活动未开始'});
                }else if(data && data.code == '100001'){//未登录
                    TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '未登录，请登录再来~'});
                }else{
                    TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '网络异常，请稍后再试~'});
                }
            }

        });

        // NetManager.ins.getWechatInfo((success) => {
        //     if(success) {
        //         NetManager.ins.getHomeInfo((success1) => {
        //             if(success1) {
        //                 this.getGameRes(success1);
        //             } else {
        //                 let data = DataManager.ins.getData(NetName.GET_HOME_INFO)
        //                 if(data && data.code == '100001'){//未登录
        //                     TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '未登录，请登录再来~'});
        //                 }else{
        //                     TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '网络异常，请稍后再试~'});
        //                 }
        //             }

        //         });
        //     } else {

        //         TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '网络异常，请稍后再试~'});
        //     }


        //     let data = DataManager.ins.getData(NetName.GET_WECHAT_INFO);
        //     console.log('getWechatInfo', data);
        //     if(data.success) {
        //         if(window['wx'] && window['wx'].config){
        //             window['wx'].config({
        //                 debug: false,
        //                 appId: data.wxappid,
        //                 timestamp: data.wxtimestamp,
        //                 nonceStr: data.wxnonceStr,
        //                 signature: data.wxsignature,
        //                 jsApiList: ['checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage']
        //             });
        //             window['wx'].ready(function() {
        //                 window['invokeWX']();
        //             });
        //         }
                
        //     }

        // });
    }

    //加载游戏中的资源
    private async getGameRes(success: boolean) {
        if(window['isdebug']) {

            window['resPath'] = '';
        }

        // if(success) {
        //     Buried.init();
        //     // SceneCtrl.instance.change(ModuleTypes.START_SCENE);return;
        //     await this.preload();
        // } else {
        //     PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '网络异常'});
        // }

        await this.preload();
        Loading.instace.hide();
        await this.delayload();

    }

    private async preload() {
        try {
            await RES.loadGroup('common');
            await RES.loadGroup('start_scene');
            await RES.getResAsync('startBg_jpg');
            await RES.loadGroup('guide_panel');
            await RES.getResAsync('guideBg_jpg');
            await RES.loadGroup('game_scene');
            await RES.getResAsync('gameBg_jpg');
            // await RES.getResAsync('startBtnSound_mp3');
            // GDispatcher.dispatchEvent("PROGRESS", 80);

            // await RES.loadGroup('prize_panel');

            SceneCtrl.instance.change(ModuleTypes.START_SCENE);
        } catch(error) {
            console.log('err3', error);
            SceneCtrl.instance.change(ModuleTypes.START_SCENE);
            // GDispatcher.dispatchEvent("PROGRESS", 100);
            await this.delayload();
            return;
        }
        await this.delayload();

        return new Promise((resolve) => {
            resolve();
        });
    }

    private async delayload() {
        await RES.loadGroup('rule_panel');
        await RES.loadGroup('prize_panel');

        await RES.loadGroup('msg_panel');

        return new Promise((resolve) => {
            resolve();
        });
    }

}

window['Main'] = Main;