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

import layers from "./views/layers";
import {getResPath, showShare} 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/NoRedMaplePanel';
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 Button = eui.Button;
import Image = eui.Image;
import TouchEvent = egret.TouchEvent;

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

        // 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.START_SCENE, StartScene1);


        // PanelCtrl.instance.registerPanelClass(ModuleTypes.RANK_PANEL, RankPanel);
        TopLayerCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GAMEOVER_PANEL, GameOverPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.EXCHANGESUC_PANEL, ExchangeSucPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.LOTBOX_PANEL, LotBoxPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.NOREDMAPLE_PANEL, NoRedMaplePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.OUTOFPRIZE_PANEL, OutOfPrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.PRIZE_PANEL, PrizePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SIGNSUC_PANEL, SignSucPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SPOTINTRO_PANEL, SpotIntroPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.EXMSG_PANEL, ExMsgPanel);


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

    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();
        NetManager.ins.getDomain((success) => {
            if (!success) {
                PanelCtrl.instance.show(ModuleTypes.EXMSG_PANEL);
                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.consumerData((success) => {
                if (!success) {
                    PanelCtrl.instance.show(ModuleTypes.EXMSG_PANEL);
                    Loading.instace.hide();
                    console.log('consumerData defaild')
                    return;
                }
                const data = DataManager.ins.getData(NetName.CONSUMER_DATA).data;
                DataManager.ins.getGameInfoData.totalAmount = DataManager.ins.getData(NetName.CONSUMER_DATA).data.totalAmount;
                //获取签到数据
                NetManager.ins.getSignData((success) => {
                    if (!success) {
                        PanelCtrl.instance.show(ModuleTypes.EXMSG_PANEL);
                        Loading.instace.hide();
                        console.log('getSignData defaild')
                        return;
                    }
                    const data = DataManager.ins.getData(NetName.SIGN_DATA).data;
                    DataManager.ins.getGameInfoData.cycleDays = data.cycleDays;
                    DataManager.ins.getGameInfoData.serialDays = data.serialDays;
                    DataManager.ins.getGameInfoData.todaySignFlag = data.todaySignFlag;
                    DataManager.ins.getGameInfoData.signPrizeAmountArr = data.signPrizeAmountArr;

                    // NetManager.ins.getTaskData((success)=>{
                    //     if(!success){
                    //         PanelCtrl.instance.show(ModuleTypes.EXMSG_PANEL);
                    //         Loading.instace.hide();
                    //         console.log('getTaskData defaild')
                    //         return;
                    //     }
                    //     const data = DataManager.ins.getData(NetName.GET_TASK_DATA).data;
                    //     DataManager.ins.getGameInfoData.smartparking = data.smartparking;
                    //     DataManager.ins.getGameInfoData.repayment = data.repayment;
                    //     DataManager.ins.getGameInfoData.finishCnt = data.finishCnt;
                    //     DataManager.ins.getGameInfoData.totalCnt = data.totalCnt;
                    //     DataManager.ins.getGameInfoData.payment = data.payment;

                    this.getGameRes(success);
                    // })
                })
            });

        })
    }

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

            window['resPath'] = '';
        }
        try {
            await RES.loadGroup('common');
            if (success) {// && DataManager.ins.ajaxElementDataNew.code == '0000000000'){
                Buried.init();
                try {
                    await RES.loadGroup('runani');
                    await RES.loadGroup('start_scene');
                    await RES.getResAsync('bg01_png');
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                } catch (err1) {
                    console.log('err1', err1);
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                }

                const shareBtn: Image = new Image('index分享_png');
                this.addChild(shareBtn);
                shareBtn.x = 630;
                shareBtn.y = 1200;

                shareBtn.addEventListener(TouchEvent.TOUCH_TAP, () => {
                    let startDpmOut = Buried.connectDpm(110, 18, 1); // 点击埋点
                    let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
                    let exposure = Buried.createExposure(startDpmOut, startDcmOut);
                    NetManager.ins.clickLog(exposure);

                    showShare(() => {
                    });
                }, this);
                let startDpmOut = Buried.connectDpm(110, 18, 1); // 点击埋点
                let startDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
                let exposure = Buried.createExposure(startDpmOut, startDcmOut);
                NetManager.ins.showLog(exposure);

            } else {
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '网络异常'});
            }
        } catch (err) {
            console.log('err', err);
            if (success) {// && DataManager.ins.ajaxElementDataNew.code == '0000000000'){
                Buried.init();
                try {
                    await RES.loadGroup('runani');
                    await RES.loadGroup('start_scene');
                    await RES.getResAsync('bg01_png');
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                } catch (err1) {
                    SceneCtrl.instance.change(ModuleTypes.START_SCENE);
                }
            } else {
                PanelCtrl.instance.show(ModuleTypes.TOAST_PANEL, {msg: '网络异常'});
            }
        }
        Loading.instace.hide();

        try {
            await RES.loadGroup('signsuc_panel');
            await RES.loadGroup('noredmaple_panel');
            await RES.loadGroup('spotintro_panel');
            await RES.loadGroup('gameover_panel');
        } catch (err2) {
            console.log('err2', err2);
        }

    }

}

window['Main'] = Main;