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 MsgPanel from './msgPanel/MsgPanel';
import GameScene from './gameScene/GameScene';
import PrizePanel from './prizePanel/PrizePanel';
import GuidePanel from './guidePanel/GuidePanel';
import GameOverPanel from './gameOverPanel/GameOverPanel';
import SharePanel from './sharePanel/SharePanel';
import WarningPanel from './warningPanel/WarningPanel';
import StartScene from './startScene/StartScene';
import RulePanel from './rulePanel/RulePanel';
import TaskPanel from './taskPanel/TaskPanel';
import DressPanel from './dressPanel/DressPanel';
import RankPanel from './rankPanel/RankPanel';
import WaitingRankPanel from './waitingrankPanel/WaitingRankPanel';
import ToastPanel from './toastPanel/ToastPanel';
import TipsPanel from './tipsPanel/TipsPanel';
import OverPageScene from './overPageScene/OverPageScene';
import ResultScene from './resultScene/ResultScene';
import ResultPanel from './resultPanel/ResultPanel';
import DescribePanel from './describePanel/DescribePanel';
import TimesTipsPanel from './timesTipsPanel/TimesTipsPanel';
import { NetNameNew } from '../libs/tw/enum/NetName';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import LoadingScene from "./loadingScene/LoadingScene";
import SvgaCtrl from "./ctrls/svgaCtrl";
import GuideScene from './guideScene/GuideScene';
import ExchangePanel from './exchangePanel/ExchangePanel';
import FriendKitchenPanel from './friendKitchenPanel/FriendKitchenPanel';
import FriendKitchenScene from './friendKitchenScene/FriendKitchenScene';
import AssistancePanel from './assistancePanel/AssistancePanel';
import InvitationPanel from './invitationPanel/InvitationPanel';


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'];

        //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();
        DataManager.ins.getGameInfoData = {};
        window['CFG'] = {};
        if (window['debug']) {
            window['CFG'].projectId = '/projectx';
        } else {
            window['CFG'].projectId = '/projectx' + '/' + window.location.pathname.split('/')[2];
        }
     
        Buried.init();
        Buried.appId = window['appid'] ? window['appid'] : 67503;
        Buried.oaId = window.location.pathname.split('/')[2];

        this.stage.scaleMode = egret.StageScaleMode.FIXED_WIDTH;
        SceneCtrl.instance.registerSceneClass(ModuleTypes.GAME_SCENE, GameScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.LOADING_SCENE, LoadingScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.GUIDE_SCENE, GuideScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.FRIEDN_KITCHEN_SCENE, FriendKitchenScene);

        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GAMEOVER_PANEL, GameOverPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHARE_PANEL, SharePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TIME_TIPS_PANEL, TimesTipsPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.TASK_PANEL, TaskPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.DRESS_PANEL, DressPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.EXCHANGE_PANLE, ExchangePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.FRIEDN_KITCHEN_PANEL,FriendKitchenPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.ASSISTANCE_PANEL,AssistancePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.INVITATION_PANEL,InvitationPanel);
  

        this.runGame().catch(e => {
            console.log(e);
        })
    }
    private inApp(){
        
        var ua = window.navigator.userAgent;
        return ua.toLowerCase().indexOf('bestpay') > -1 ? true : false;
    }
   /**
     * 获取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() {
        await this.loadResource()
        this.createGameScene();
        // 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) => {
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);
        })
    }

    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        if(!this.inApp() && this.getQueryString('shareCode'))
        {
            
            PanelCtrl.instance.show(ModuleTypes.ASSISTANCE_PANEL);
            return;
        }
        //获取游戏信息
        Loading.instace.show();

        // NetManager.ins.ajaxElementNew(function(success){
        //     //console.log(DataManager.ins.ajaxElementDataNew);
        //     this.getGameRes(success);
            
        // }.bind(this));
        NetManager.ins.getDomain((success,data) => {
            if(!data)
            {
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                return;
            }
            if(!success)
            {
                if(!data.code){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                    return;
                }else if(data.code == '100001'){
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'请先登录'});
                    return;
                }else{
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                    return;
                }
            }

            window['CFG'].domainUrl = DataManager.ins.getData('getDomain').data.activityDomain;
            if (!window['isdebug1']) {
                window['CFG'].projectId = window['CFG'].domainUrl + window['CFG'].projectId;
            }

            NetManager.ins.getInformation((success,result) => {
                console.log('首页信息',result);
                if(!result)
                {
                    PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                    return;
                }
                if(!success)
                {
                    if(!result.code){
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                        return;
                    }else if(result.code == '100001'){
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'请先登录'});
                        return;
                    }else{
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                        return;
                    }
                }
                NetManager.ins.genInvite((success,result)=>{
                    if(!result)
                    {
                        PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                        return;
                    }
                    if(!success)
                    {
                        if(!result.code){
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                            return;
                        }else if(result.code == '100001'){
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'请先登录'});
                            return;
                        }else{
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                            return;
                        }
                    }
                    window['shareUrl'] = this.setShareCode(window['shareUrl'],'shareCode',result.data);
                    NetManager.ins.getProjectUserInfo((success,resultInfo)=>{
                        if(!resultInfo)
                        {
                            PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                            return;
                        }
                        if(!success)
                        {
                            if(!resultInfo.code){
                                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                                return;
                            }else if(resultInfo.code == '100001'){
                                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'请先登录'});
                                return;
                            }else{
                                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL,{msg:'网络开小差了，请稍后重试~'});
                                return;
                            }
                        }
                        console.log('uid',resultInfo.data.partnerUserId);
                        window['shareUrl'] = this.setShareCode(window['shareUrl'],'uid',resultInfo.data.partnerUserId);
                    })
                    
                })

                window['newUserGuide'] = DataManager.ins.getData('getIndex').data.newUserGuide;
                // let dailyAwardType = DataManager.ins.getData('getIndex').data.dailyAwardType;
                // let dailyAward = DataManager.ins.getData('getIndex').data.dailyAward;
                // let remainDays = DataManager.ins.getData('getIndex').data.remainDays;
                // window['dailyAwardType'] = dailyAwardType;
                // window['dailyAward'] = dailyAward;
                // window['remainDays'] = remainDays;

                // let helpReceive = DataManager.ins.getData('getIndex').data.helpReceive;
                // let helpNickname = DataManager.ins.getData('getIndex').data.helpNickname;
                // let helpReceiveTime = DataManager.ins.getData('getIndex').data.helpReceiveTime;
                // let needHelpReceivePopup = DataManager.ins.getData('getIndex').data.needHelpReceivePopup;
                // window['helpReceive'] = helpReceive;
                // window['helpNickname'] = helpNickname;
                // window['helpReceiveTime'] = helpReceiveTime;
                // window['needHelpReceivePopup'] = needHelpReceivePopup;
          
                this.getGameRes();
            })
      
        })
    }
    private setShareCode(url, arg, arg_val){
        let pattern = arg + '=([^&]*)';
        let replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            let tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
    }
    /**
     * 创建场景界面
     * Create scene interface
     */
    private async getGameRes(){
        try{
            await RES.loadGroup('loading_scene');
            await RES.getResAsync('loadSceneBg_jpg');
            await SvgaCtrl.instance.getSvga('resource/assets/svga/loading.svga') as SVGA.EgretMovieClip;
            SceneCtrl.instance.change(ModuleTypes.LOADING_SCENE);
        }catch(err){
           console.log('err', err);
           SceneCtrl.instance.change(ModuleTypes.LOADING_SCENE);
        }
        try{
            GDispatcher.dispatchEvent('progress',[5]);
            await RES.loadGroup('common');
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateDozeGreen.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateDozeRed.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateDozeViolet.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateMakeGreen.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateMakeRed.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateMakeViolet.svga') as SVGA.EgretMovieClip;
            GDispatcher.dispatchEvent('progress',[10]);
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateNormalGreen.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateNormalRed.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateNormalViolet.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateStudyGreen.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateStudyRed.svga') as SVGA.EgretMovieClip;
            await SvgaCtrl.instance.getSvga('resource/assets/svga/stateStudyViolet.svga') as SVGA.EgretMovieClip;
            GDispatcher.dispatchEvent('progress',[15]);
            await RES.loadGroup('start_scene');
            await RES.getResAsync('stratBg1_jpg');
            await RES.getResAsync('stratBg2_jpg');
            GDispatcher.dispatchEvent('progress',[30]);
            await RES.loadGroup('change_panel');
            await RES.getResAsync('changeBg_jpg');
            await RES.getResAsync('changeSureBg_jpg');
            GDispatcher.dispatchEvent('progress',[35]);
            await RES.loadGroup('dress_panel');
            await RES.getResAsync('dressPanelBg_jpg');
            GDispatcher.dispatchEvent('progress',[45]);
            // await RES.loadGroup('friendkitchen_panel');
            // await RES.getResAsync('friendKitchenBg_jpg');
            // GDispatcher.dispatchEvent('progress',[50]);
            // await RES.loadGroup('friendkitchen_scene');
            // GDispatcher.dispatchEvent('progress',[60]);
            await RES.loadGroup('guide_scene');
            await RES.getResAsync('guideBg_jpg');
            GDispatcher.dispatchEvent('progress',[75]);
            await RES.loadGroup('invitation_panel');
            await RES.getResAsync('invitationBg_jpg');
            await RES.getResAsync('friendListBg_jpg');
            GDispatcher.dispatchEvent('progress',[80]);
            await RES.loadGroup('msg_panel');
            await RES.getResAsync('msgBg_jpg');
            GDispatcher.dispatchEvent('progress',[85]);
            // await RES.loadGroup('rule_panel');
            // await RES.getResAsync('ruleBg_jpg');
            // GDispatcher.dispatchEvent('progress',[90]);
            await RES.loadGroup('task_panel');
            await RES.getResAsync('taskBg_jpg');
            GDispatcher.dispatchEvent('progress',[100]);
        }catch(err){
            console.log('err1', err);
            GDispatcher.dispatchEvent('progress',[100]);
        }
    }
}
window['Main'] = Main;