import { asyncDelay, playAudioByUrl, asyncGetSpriteFrimeByUrl, buttonOnClick, jumpToCourseWare, asyncCallNetworkApiGet } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        this._imageResList.push({ url: this.data.bookImg });
    }

    addPreloadAudio() {
        this._audioResList.push({ url: this.data.questionTextAudio });
        this._audioResList.push({ url: this.data.bookAudio });
    }

    addPreloadAnima() {

    }

    async onLoadEnd() {
        await this.initView();
        this.initListener();
        playAudioByUrl(this.data.questionTextAudio);
    }

    rows = [];
    async initView() {
        const levelNode = cc.find(`Canvas/bg/L${this.data.choseLevel}`);
        if (!levelNode) {
            return;
        }
        levelNode.active = true;
        cc.find(`box/title`, levelNode).getComponent(cc.Label).string = this.data.title;

        try {
            const bookImgFrame: any = await asyncGetSpriteFrimeByUrl(this.data.bookImg);
            cc.find(`Canvas/bg/bookImg/img`).getComponent(cc.Sprite).spriteFrame = bookImgFrame;
        } catch (error) {
            console.error(error);
        }

        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            return;
        }
        const tableData = middleLayer.getComponent('middleLayer').getData("NJ_BookTable");
        if (tableData && tableData.folderId) {
            const resStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
                pid: tableData.folderId
            });
            console.log('resStr = ' + resStr);
            const res = JSON.parse(resStr);
            this.rows = res.rows.filter(row => row.name != '索引页');
        }
    }


    initListener() {
        const bgButton = cc.find(`Canvas/bg/bookImg`);
        bgButton.on('click', () => {
            playAudioByUrl(this.data.bookAudio);
        });

        const levelNode = cc.find(`Canvas/bg/L${this.data.choseLevel}`);
        if (!levelNode) {
            return;
        }
        const levelButton = cc.find(`box`, levelNode);
        levelButton.on('click', () => {
            if (levelButton['cantClick']) {
                return;
            }
            levelButton['cantClick'] = true;
            // TODO 播放骨骼动画
            playAudioByUrl(this.data.questionTextAudio, () => {
                // TODO 更新骨骼动画状态
                levelButton['cantClick'] = false;
            });
        })

        buttonOnClick(cc.find(`kdh`, levelNode), () => {
            jumpToCourseWare(this.rows[0].id);
        });
        buttonOnClick(cc.find(`dgs`, levelNode), () => {
            jumpToCourseWare(this.rows[1].id);
        });
        buttonOnClick(cc.find(`qpy`, levelNode), () => {
            jumpToCourseWare(this.rows[2].id);
        });
    }


}
