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 ExchangeSucPanel from './panels/ExchangeSucPanel';
import LotBoxPanel from './panels/LotBoxPanel';
import NoRedMaplePanel from './panels/ShowImgPanel';
import OutOfPrizePanel from './panels/OutOfPrizePanel';
import SignSucPanel from './panels/SignSucPanel';
import SpotIntroPanel from './panels/SpotIntroPanel';
import ExMsgPanel from './panels/ExMsgPanel';
import { NetName } from '../libs/tw/enum/NetName';
import GameOverPanel from './panels/GameOverPanel';
import ShareSucPanel from './panels/ShowImgPanel';
import BagPanel from './panels/BagPanel';
import PrizePanel2 from './panels/PrizePanel2';
import LoadingScene from './loadingScene/LoadingScene';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import GameScene from './gameScene/GameScene';
import ShowImgPanel from './panels/ShowImgPanel';

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'] : 62244;
        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.SHOW_IMG_PANEL, ShowImgPanel);
        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);
        // let per = 0;
        // let idx = setInterval(()=>{
        //     let rom = 2 + Math.floor(30 * Math.random());
        //     per += rom;
        //     let endPer = per;
        //     if(endPer >= 100){
        //         clearInterval(idx);
        //         endPer = 100;
        //     }
            
        //     GDispatcher.dispatchEvent("PROGRESS", endPer);
            
        // }, 200);

        // NetManager.ins.getDomain((success) => {
        //     if (!success) {
        //         TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: '活动太火爆了，请稍后重试~' });
        //         Loading.instace.hide();
        //         return;
        //     }
        //     window['CFG'].domainUrl = DataManager.ins.getData(NetName.GET_DOMAIN).data.activityDomain;
        //     if (!window['isdebug']) {
        //         window['CFG'].projectId = window['CFG'].domainUrl + window['CFG'].projectId;
        //     }

        // })


        NetManager.ins.getWechatInfo((success) => {
            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']();
                });
            }

            this.getGameRes(true);
        });
    }

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

            window['resPath'] = '';
        }

        if (success) {
            Buried.init();
            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');
            GDispatcher.dispatchEvent("PROGRESS", 30);
            await RES.getResAsync('startBg_jpg');
            await RES.getResAsync('ptImg0_jpg');
            await RES.getResAsync('ptImg1_jpg');
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/birdfly.svga') as SVGA.EgretMovieClip;
            GDispatcher.dispatchEvent("PROGRESS", 50);
            await RES.getResAsync('ptImg2_jpg');
            await RES.getResAsync('ptImg3_jpg');
            await RES.getResAsync('ptImg4_jpg');
            await PanelCtrl.instance.getSvga('resource/assets/svga/start/startBtn.svga') as SVGA.EgretMovieClip;
            GDispatcher.dispatchEvent("PROGRESS", 60);
            await RES.loadGroup('game_scene');
            await RES.getResAsync('shareImg0_png');
            await RES.getResAsync('shareImg1_png');
            await RES.getResAsync('shareImg2_png');
            await RES.getResAsync('bgSound1_mp3');
            
            GDispatcher.dispatchEvent("PROGRESS", 80);
            await RES.getResAsync('gameBg_jpg');
            await RES.getResAsync('shareImg3_png');
            await RES.getResAsync('shareImg4_png');
            await RES.getResAsync('dragSound_mp3');
            await RES.getResAsync('startBtnSound_mp3');
            GDispatcher.dispatchEvent("PROGRESS", 100);

        } catch (error) {
            console.log('err3', error);
            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 PanelCtrl.instance.getSvga('resource/assets/svga/prize/prizeAct0.svga') as SVGA.EgretMovieClip;
        await PanelCtrl.instance.getSvga('resource/assets/svga/prize/prizeAct1.svga') as SVGA.EgretMovieClip;

        await RES.loadGroup('gameover_panel');

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

}



window['Main'] = Main;