import { DataManager } from "../libs/tw/manager/DataManager";
import { NetManager } from "../libs/tw/manager/NetManager";
import AssetAdapter from "./AssetAdapter";
import PanelCtrl from "./ctrls/panelCtrl";
import SceneCtrl from "./ctrls/sceneCtrl";
import Loading from "./loading/Loading";
import RulePanel from "./rulePanel/RulePanel";
import ThemeAdapter from "./ThemeAdapter";
import { ModuleTypes } from "./types/sceneTypes";
import { getResPath } from "./utils";
import layers from "./views/layers";
import MainScene from './mainScene/MainScene';
import { PetIndexData } from "../libs/tw/data/pet/PetIndexData";
import MsgPanel from "./msgPanel/MsgPanel";
import SharePanel from './sharePanel/SharePanel';
import { Buried } from '../libs/tw/util/Buried';
import LoadingScene from './loadingScene/loadingScene';
import { GDispatcher } from '../libs/tc/util/GDispatcher';
import StartScene1 from './startScene/StartScene';
import DogShowPanel from './dogShowPanel/DogShowPanel';
import ShopPanel from './shopPanel/ShopPanel';
import TeamScene from './teamScene/TeamScene';
import TopLayerCtrl from './ctrls/topLayerCtrl';
import ToastPanel from './toastPanel/ToastPanel';
import { NetName } from "../libs/tw/enum/NetName";
import JoinPanel from "./joinPanel/JoinPanel";
import Share2Panel from "./share2Panel/Share2Panel";
import QuestListPanel from "./QuestListPanel/QuestListPanel";
import StartScene_xcj from "./startScene/StartScene_xcj";
import RewardPanel from "./RewardPanel/RewardPanel";
import FavoriteMusicItem from "./item/FavoriteMusicItem";
import FavoriteMusicPanel from "./MusicPanel/FavoriteMusicPanel";
import ListenMusicPanel from "./MusicPanel/ListenMusicPanel";
import ScoreItem from "./item/ScoreItem";
import ScorePanel from "./MusicPanel/ScorePanel";
import AchievementPanel from "./panel/AchievementPanel";
import ViewAchievementPanel from "./panel/ViewAchievementPanel";
import UpgradeRewardPanel1 from "./panel/UpgradeRewardPanel1";
import UpgradeRewardPanel2 from "./panel/UpgradeRewardPanel2";
import GetRedPacketPanel from "./panel/GetRedPacketPanel";
import GetTicketPanel from "./panel/GetTicketPanel";
import LearnedMusicPanel from "./panel/LearnedMusicPanel";
import { ABNetManager } from "../libs/tc/manager/ABNetManager";
import Alert from "./alert/Alert";

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.petIndexData = new PetIndexData();
        DataManager.ins.petIndexData.update(window['CFG']);
        DataManager.ins.customCfgData = window['CFG'];

        // NetManager.ins.getCredits(()=>{});

        layers.init(this);
        Loading.init(layers.topLayer);
        PanelCtrl.instance.init(layers.popupLayer);
        SceneCtrl.instance.init(layers.sceneLayer);
        TopLayerCtrl.instance.init(layers.topLayer);

        Buried.init();

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

        PanelCtrl.instance.registerPanelClass(ModuleTypes.MSG_PANEL, MsgPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.ALERT_PANEL, Alert);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.RULE_PANEL, RulePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.DOG_SHOW_PANEL, DogShowPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHOP_PANEL, ShopPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHARE_PANEL, SharePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.JOIN_PANEL, JoinPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SHARE2_PANEL, Share2Panel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.QUEST_LIST_PANEL, QuestListPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.REWARD_PANEL, RewardPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.FAVORITE_MUSIC_PANEL, FavoriteMusicPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.LISTEN_MUSIC_PANEL, ListenMusicPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.SCORE_PANEL, ScorePanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.ACHIEVEMENT_PANEL, AchievementPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.VIEW_ACHIEVEMENT_PANEL, ViewAchievementPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.UPGRADE_REWARD_PANEL1, UpgradeRewardPanel1);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.UPGRADE_REWARD_PANEL2, UpgradeRewardPanel2);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GET_RED_PACKET_PANEL, GetRedPacketPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.GET_TICKET_PANEL, GetTicketPanel);
        PanelCtrl.instance.registerPanelClass(ModuleTypes.LEARNED_MUSIC_PANEL, LearnedMusicPanel);

        SceneCtrl.instance.registerSceneClass(ModuleTypes.LOADING_SCENE, LoadingScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.MAIN_SCENE, MainScene);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.START_SCENE, StartScene1);
        SceneCtrl.instance.registerSceneClass(ModuleTypes.TEAM_SCENE, TeamScene);


        TopLayerCtrl.instance.registerPanelClass(ModuleTypes.TOAST_PANEL, ToastPanel);
        this.runGame().catch(e => {
            console.log(e);
        })
    }
    private onError(net: any, desc: any, result): void {
       /*  console.log(desc);
        console.log(result); */
        var msg: string;
        var msgArr: any = window['errorMessage'];
        if (!isNaN(desc)) {
            msg = msgArr[desc] ? msgArr[desc] : '活动太火爆了，请稍后再来～';
        } else {
            msg = desc;
        }

        console.log("net")
        console.log(net)

        var code;
        if(result){
            code = result.code;
        }
        if (code == -1001) {
            this.showToast("登录验证失败");
        } else if (code == -1002) {
            this.showToast("接口繁忙，稍等片刻重试~");
        } else if (code == -1003) {
            PanelCtrl.instance.show(ModuleTypes.ALERT_PANEL,{message:"同一设备只能关联一个账号参与，\n请重新登录您之前的账号～感谢理解！"})
        } else if (code == -1004||code == -1006||code == -1007||code == -1008||code == -1009||code=="600032") {
           // this.showToast("接口繁忙，稍等片刻重试~");
        } else if (code == "0800101") {
            this.showToast("网络异常");
        } else if (code == "2002007013"||code == "600033") {
          //  this.showToast("网络异常");
            GDispatcher.dispatchEvent("updatePetText",code)
        } else if(net){
            this.showToast("糟糕…本次学习没有带回歌曲，\n继续加油哦～ ")
        }else {
            if(msg){
                this.showToast(msg);
            }else{
                this.showToast("活动太火爆了，请稍后再来～");
            }
        }
    }

    showToast(val) {
        //console.log(val)
        TopLayerCtrl.instance.show(ModuleTypes.TOAST_PANEL, { msg: val });
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        // RES.loadGroup("msg", 10);
    }

    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);

        })
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {
        Buried.init();
        //获取签到信息
     //   NetManager.ins.getShareCode(() => {
            this.getGameRes();
           // this.doShare()
     //   }, window["CFG"].activityId, "hdtool")
    }

    doShare() {
        var shareData = {
            title: '飞船登陆汪星球！超多萌宠可爱来袭！',//标题
            desc: '谁家汪更可爱？',//描述
            link: `https://activity-6.m.duiba.com.cn/customShare/share?id=2921&ShareCode=${DataManager.ins.getData(NetName.GET_SHARECODE).shareCode}`,//链接
            imgUrl: 'https://yun.duiba.com.cn/db_games/activity/yjyc/share.jpg',//图片
        }
        window["invokeWX"](shareData)
    }

    //加载游戏中的资源
    private async getGameRes() {
        //还没有宠物，先播放介绍文字
        // if (!DataManager.ins.petHomeInfoData.petId) {
        //     await RES.loadGroup('adopte_panel');
        //    // await RES.getResAsync('adopteBg_jpg');
        //     PanelCtrl.instance.show(ModuleTypes.ADOPTE_PANEL);
        //     await RES.loadGroup('guide_component');
        // } else {//已经有宠物了，进入游戏场景
        //     await RES.loadGroup('main_scene');
        //    // await RES.getResAsync('bgday_jpg');
        //     SceneCtrl.instance.change(ModuleTypes.MAIN_SCENE);
        // }

        await RES.loadGroup('loading_scene');
        await RES.getResAsync('lodingBg_jpg');
        SceneCtrl.instance.change(ModuleTypes.LOADING_SCENE);

        GDispatcher.dispatchEvent('progress', [5]);
        await RES.loadGroup('common');
        await RES.getResAsync('startBg_jpg');
        GDispatcher.dispatchEvent('progress', [10]);
        await RES.loadGroup('start_scene');
        GDispatcher.dispatchEvent('progress', [15]);
        GDispatcher.dispatchEvent('progress', [35]);
        //await RES.loadGroup('shengji');
        await RES.getResAsync('shengjiAn_json');
        await RES.getResAsync('shengjiAn_png');
       
        GDispatcher.dispatchEvent('progress', [65]);
        await RES.loadGroup('quest_list');
        GDispatcher.dispatchEvent('progress', [85]);
        await RES.loadGroup('reward_panel');
        GDispatcher.dispatchEvent('progress', [100]);

        //延时加载
        await RES.loadGroup('favorite_music_panel');
     
        // await RES.getResAsync('dShowBg_png');
        await RES.loadGroup('listen_music_panel');
        await RES.loadGroup('score_panel');

        await RES.loadGroup('achievement_panel');

        GDispatcher.addEvent(ABNetManager.ERROR, this.onError, this);

        //加载组
        // await RES.loadGroup('signIn_prize_panel');
        // await RES.loadGroup('signIn_panel');
        // await RES.loadGroup('extra_prize_panel');
        // await RES.loadGroup('upPrize_panel');
        // await RES.loadGroup('upNoPrize_panel');
        // await RES.loadGroup('earnGold_panel');
        // await RES.loadGroup('guide_panel');
        // //加载图片
        // await RES.getResAsync('gamerule_jpg');
        // await RES.getResAsync('guideBg_jpg');

    }
}

window['Main'] = Main;