import { getSkinPath } from "../Global/GUtils";
import ToastPanel from "./MToastPanel";

export default class ComponentBase extends eui.Component {
    protected data: any;
    constructor(data?: any) {
        super();
        this.data = data;
        this.initComponet();
        this.horizontalCenter = 0;
    }

    private async initComponet() {
        await this.preLoadRes();
        if (!window['development'] && this.groupName) {
            RES.getResByUrl(`${this.groupName}_json`, (sheet: egret.SpriteSheet) => {
                console.log('界面大图加载完');
                this.setSkinName();
            }, this, RES.ResourceItem.TYPE_SHEET);
        } else {
            this.setSkinName();
        }
    }

    /**
     * 是否有要提前加载的资源
     */
    preLoadRes() {
        return new Promise(async (resolve, reject) => {
            let name: string = this.skinKey;
            if (name) {
                //把skinKey转换为groupName
                let isFirst = true;
                let result: string[] = [];
                for (let char of name) {
                    if (char.isUpperCase()) {
                        if (isFirst) {
                            isFirst = false;
                        } else {
                            result.push("_");
                        }
                    }
                    result.push(char.toLowerCase());
                }

                await RES.loadGroup(result.join("")).catch((reason) => {
                    console.error("load group fail:" + reason);
                    ToastPanel.show("网络连接失败");
                    reject();
                });
                resolve();
            } else
                resolve();
        });
    }

    protected removeEvents() { }

    //设置皮肤
    public setSkinName(): void {
        console.log('this.skinKey=' + this.skinKey);
        this.addEventListener(egret.Event.COMPLETE, this.onSkinComplete, this);
        this.skinName = getSkinPath(this.skinKey);
    }

    public get skinKey(): string { return this["className"] }

    //获取资源组名字
    private get groupName(): string { return null }

    protected onSkinComplete() {
        console.log(`${this.skinKey} loaded`);

        if (this["decoratorCallback"]) {
            Object.keys(this["decoratorCallback"]).forEach(e => {
                this["decoratorCallback"][e](this);
            });
        }
    }
}