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 RulePanel from './panels/RulePanel';
import PrizePanel from './panels/PrizePanel';
import { NetName } from '../libs/tw/enum/NetName';
import GameOverPanel from './panels/GameOverPanel';
import LoadingScene from './loadingScene/LoadingScene';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import GameScene from './gameScene/GameScene';
import ShowImgPanel from './panels/RankPanel';
import RankPanel from './panels/RankPanel';

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'] : 64513;
        Buried.oaId = window.location.pathname.split('/')[2];

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

        // SceneCtrl.instance.registerSceneClass(ModuleTypes.LOADIND_SCENE, LoadingScene);
        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.GAMEOVER_PANEL, GameOverPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RANK_PANEL, RankPanel);
        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("loading")
            // 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.getWechatInfo((success) => {
            if(success){
                NetManager.ins.baseInfo((success1)=>{
                    if(success1){
                        NetManager.ins.getProjectUserInfo((success2)=>{
                            if(success2){
                                this.getGameRes(success2);
                            }else{
                                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) {
                window['wx'] &&
                    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.GAME_SCENE);return;
            await this.preload();
        } else {
            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: '网络异常' });
        }

        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 PanelCtrl.instance.getSvga('resource/assets/svga/start/rankBtnSvg.svga');
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/startBgSvg.svga');
            // GDispatcher.dispatchEvent("PROGRESS", 60);
            await RES.loadGroup('game_scene');
            await RES.getResAsync('gameBg_jpg');
            await RES.getResAsync('startBtnSound_mp3');

            await PanelCtrl.instance.getSvga('resource/assets/svga/game/catAct0.svga')
            await PanelCtrl.instance.getSvga('resource/assets/svga/game/catAct1.svga')
            await PanelCtrl.instance.getSvga('resource/assets/svga/game/diaoluo0.svga')
            await PanelCtrl.instance.getSvga('resource/assets/svga/game/diaoluo1.svga')
            await PanelCtrl.instance.getSvga('resource/assets/svga/game/timeDownSvg.svga')
            await PanelCtrl.instance.getSvga('resource/assets/svga/game/upStrag.svga');

            await RES.loadGroup('prize_panel');
            
            SceneCtrl.instance.change(ModuleTypes.START_SCENE);

        } catch (error) {
            console.log('err3', error);
            SceneCtrl.instance.change(ModuleTypes.START_SCENE);
            await this.delayload();
            return;
        }
        await this.delayload();

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

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

        await PanelCtrl.instance.getSvga('resource/assets/svga/prize/newRecord.svga');
        await PanelCtrl.instance.getSvga('resource/assets/svga/prize/prizeAct0.svga');

        await RES.loadGroup('gameover_panel');

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

}



window['Main'] = Main;