import Loading from "../libs/new_wx/components/Loading";
import { DataManager } from "../libs/tw/manager/DataManager";
import RulePanel from "./panels/RulePanel";
import PassPanel from "./panels/PassPanel";
import ReFusePanel from "./panels/RefusePanel";
import SuccessPanel from "./panels/SuccessPanel";
import AdminPanel from "./panels/AdminPanel";
import CostPanel from "./panels/CostPanel";
import ShareDreamScene from "./ShareDreamScene";
import HisDreamScene, { HisDreamType } from "./HisDreamScene";
import MainScene from "./MainScene";
import IntroScene from "./IntroScene";
import DreamScene from "./DreamScene";
import DreamAdminScene from "./DreamAdminScene";
import AdminScene from "./AdminScene";
import ListScene from "./ListScene";
import MyDreamScene from "./MyDreamScene";
import PanelCtrl from "../libs/new_wx/ctrls/panelCtrl";
import SceneCtrl from "../libs/new_wx/ctrls/sceneCtrl";
import AssetAdapter from "../libs/new_wx/adapter/AssetAdapter";
import ThemeAdapter from "../libs/new_wx/adapter/ThemeAdapter";
import layers from "../libs/new_wx/views/layers";
import getResPath from "../libs/new_tc/getResPath";
import { NetManager } from "../libs/tw/manager/NetManager";
import getcredits, { updateCredits } from "./getcredits";
import AdminPanel2 from "./panels/AdminPanel2";
import Utils from "./Utils";
import join_1_index from "./interfaces/join_1_index";
const onTap_detail = (id) => {
    // console.log('点击查看详情');
    NetManager.ins.yyh_credits(()=>{
        const credits = getcredits();
        NetManager.ins.yyh_join1_dreamDetail(() => {
            const join_1_index: join_1_index = DataManager.ins.getData('yyh_join1_index');
            const detail = DataManager.ins.getData('yyh_join1_dreamDetail').data;
            if (new Date().getTime() > join_1_index.data.assistDeadline)
                SceneCtrl.instance.change('HisDreamScene', HisDreamType.TIMES_OUT);
            else if (detail.assist) { //主力了
                SceneCtrl.instance.change('HisDreamScene', HisDreamType.HELP_DONE);
            } else {
                if (join_1_index.data.doAssistCount >= join_1_index.data.doAssistLimit) {//次数限制
                    SceneCtrl.instance.change('HisDreamScene', HisDreamType.TIMES_LIMIT);
                } else if (credits <= 0) {
                    SceneCtrl.instance.change('HisDreamScene', HisDreamType.MONEY_NOT_ENOUPH);
                } else {
                    SceneCtrl.instance.change('HisDreamScene', HisDreamType.ENOUPH_TIMES);
                }
            }
        }, false, id);
    });
    
}

export default class MainBase extends eui.UILayer {
    constructor() {
        super();
        Loading.instace.loadImage();
        DataManager.ins.customCfgData = window['CFG'];
        this.getData();
    }

    protected registerModules() {
        const panels = [
            ['RulePanel', { cls: RulePanel }],
            ['PassPanel', { cls: PassPanel }],
            ['ReFusePanel', { cls: ReFusePanel }],
            ['SuccessPanel', { cls: SuccessPanel }],
            ['AdminPanel', { cls: AdminPanel }],
            ['AdminPanel2', { cls: AdminPanel2 }],
            ['CostPanel', { cls: CostPanel }],
        ];

        const scenes = [
            ['ShareDreamScene', { cls: ShareDreamScene }],
            ['HisDreamScene', { cls: HisDreamScene }],
            ['MainScene', { cls: MainScene }],
            ['IntroScene', { cls: IntroScene }],
            ['DreamScene', { cls: DreamScene }],
            ['DreamAdminScene', { cls: DreamAdminScene }],
            ['AdminScene', { cls: AdminScene }],
            ['ListScene', { cls: ListScene }],
            ['MyDreamScene', { cls: MyDreamScene }]
        ];

        panels.forEach(item => PanelCtrl.instance.registerPanel(item[0], item[1]));
        scenes.forEach(item => SceneCtrl.instance.registerScene(item[0], item[1]));

        // NetManager.ins.onNotSuccess = (msg) => {
        //    s
        // }
    }

    protected getData() {

    }

    static onPause_mainscene;
    static onResume_mainscene;
    protected createChildren(): void {
        super.createChildren();
        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            // egret.ticker.pause();
            // console.log('pause')
            MainBase.onPause_mainscene && MainBase.onPause_mainscene();
        }

        egret.lifecycle.onResume = () => {
            // egret.ticker.resume();
            // console.log('onResume')
            MainBase.onResume_mainscene && MainBase.onResume_mainscene();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        const assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());

        egret.ImageLoader.crossOrigin = "anonymous";

        layers.init(this);
        Loading.init(layers.topLayer);
        // Loading.instace.show();

        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);

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

        this.registerModules();

        // Loading.instace.show();

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

    private async runGame() {
        await this.loadResource()

        if (!window['development'])//正式环境
            RES.getResAsync(`common_json`);//弱网下需要toast资源的缓存
        else {
            RES.getResAsync('main_star_png')
            RES.getResAsync('toast_png')
        }

        this.createGameScene();
    }

    private async loadResource() {
        try {
            await RES.loadConfig("default.res.json", getResPath() + "resource/");
            await this.loadTheme();
        }
        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.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            const theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);
        })
    }

    protected async  createGameScene() {
        if (window['firstScene'] == 'invite') {
            SceneCtrl.instance.change('ShareDreamScene');
        } else if (window['firstScene'] == 'admin') {
            SceneCtrl.instance.change('AdminScene');
        } else {
            await this.getIndex();
            if (Utils.getRequestByKey('id')) {
                onTap_detail(Utils.getRequestByKey('id'));
            } else
                SceneCtrl.instance.change('MainScene');
        }

        updateCredits();
    }


    getProjectUserInfo() {
        return new Promise((r) => {
            NetManager.ins.getProjectUserInfo(async () => {

                r();
            });
        })
    }

    getIndex() {
        return new Promise((r) => {
            NetManager.ins.yyh_join1_index(async (success) => {
                r();
            });
        })
    }
}