import { asyncDelay, asyncCallNetworkApiGet, asyncGetSpriteFrimeByUrl, buttonOnClick,
    showLoading, hideLoading, loadOnlineCourseWare } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
    }

    addPreloadAnima() {

    }

    rows = null;
    orgId = 515;

    async onLoadEnd() {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            this.orgId = middleLayerComponent.ORG_ID;
        }

        await this.initData();
        await this.initView();
        this.initListener();
    }

    async loadData(pid = null) {
        const query = { orgid: this.orgId };
        if (pid) {
            query["pid"] = pid;
        }
		const res: any = await asyncCallNetworkApiGet("/api/syllabus/v1/list", query);
        let rows = JSON.parse(res).rows;

        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const syllabuses = cc.sys.localStorage.getItem('activeSyllabuses') || '';
            rows = rows.filter(item => syllabuses.split(",").includes(item.id));
        }
        
		return rows;
	}

    async initData() {
        const route = this.popRouter();
        if (route) {
            this.rows = await this.loadData(route.id);
        } else {
            this.rows = await this.loadData();
        }
    }

    mockRouter = [];
    pushRouter (item) {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            this.mockRouter.push(item);
            return;
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        middleLayerComponent.routers.push(item);
    }

    popRouter () {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            return this.mockRouter.pop();
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        const item = middleLayerComponent.routers.pop();
        return item;
    }

    getRouters () {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            return this.mockRouter;
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        return middleLayerComponent.routers;
    }

    async drawPage() {

        const contentNode = cc.find("Canvas/pages/view/content");
        const item = cc.find("item", contentNode);
        // 清理原来的数据
		item.parent = this.node;
		contentNode.removeAllChildren();
        item.parent = contentNode;
        item.active = false;
        
        // 绘制
        for (let i = 0; i < this.rows.length; i++) {
            const row = this.rows[i];
            const itemClone = cc.instantiate(item);
			itemClone.parent = contentNode;
			itemClone.active = true;
			itemClone.attr({item_id: row.id, item_name: row.name});
            cc.find(`text`, itemClone).getComponent(cc.Label).string = row.name;
            if (row.cover) {
                const spriteFrame:any = await asyncGetSpriteFrimeByUrl(row.cover);
                const coverNode = cc.find(`cover`, itemClone);
                coverNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
                const sx = 70 / coverNode.width;
                const sy = 80 / coverNode.height;
                coverNode.scale = Math.min(sx, sy);
            }

            buttonOnClick(itemClone, async () => {
                if (row.has_courseware) {
                    // 打开课件
                    showLoading();
                    loadOnlineCourseWare(row.id);
                } else {
                    // 打开文件夹
                    this.pushRouter(row);
                    showLoading();
                    this.rows = await this.loadData(row.id);
                    await this.drawPage();
                    cc.find(`Canvas/lefttop/bg_title/title`).getComponent(cc.Label).string = row.name;
                    cc.find(`Canvas/lefttop`).active = true;
                    hideLoading();
                }
            });
        }

    }

    async initView() {
        this.initBg();
        await this.drawPage();
    }

    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;
    }

    initListener() {
        const back = cc.find(`Canvas/lefttop/back`);
        buttonOnClick(back, async () => {
            showLoading();
            const item = this.popRouter();
            this.rows = await this.loadData(item.pid);
            await this.drawPage();
            hideLoading();

            const routers = this.getRouters();
            if (routers.length === 0) {
                cc.find(`Canvas/lefttop`).active = false;
            }
        });
    }

    playLocalAudio(audioName) {
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        return new Promise((resolve, reject) => {
            const id = cc.audioEngine.playEffect(audio.clip, false);
            cc.audioEngine.setFinishCallback(id, () => {
                resolve(id);
            });
        })
    }
}
