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

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
    }

    addPreloadAudio() {
    }

    addPreloadAnima() {

    }

    async onLoadEnd() {
        this.initBg();
        await this.initView();
        this.initListener();
        this.randomPop();
    }

    rows: any;
    level: any;
    async initView() {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            const levelNode = cc.find(`Canvas/L1`);
            levelNode.active = true;
            this.level = 'L1';

            // 本地测试用
            // const resStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
            //     pid: 23665
            // });
            // const res = JSON.parse(resStr);
            // this.rows = res.rows;
    
            // for (let i=1; i<=5; i++) {
            //     const row = this.rows[i-1];
            //     if (!row) {
            //         continue;
            //     }
            //     const item = cc.find(`item${i}`, levelNode);
            //     item.attr({syllabusId: row.id});
            //     if (row.cover) {
            //         const coverFrame: any = await asyncGetSpriteFrimeByUrl(row.cover);
            //         cc.find(`cover`, item).getComponent(cc.Sprite).spriteFrame = coverFrame;
            //     }
            // }

            return;
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        const folderId = middleLayerComponent.getData('NJ_MoreGames_CourseList').folderId;
        console.log('folderId = ' + folderId);
        const level = middleLayerComponent.getData('NJ_MoreGames').Level || 'L1';
        this.level = level;

        const levelNode = cc.find(`Canvas/${level}`);
        levelNode.active = true;

        const resStr = await asyncCallNetworkApiGet('/api/syllabus/v1/list', {
            pid: folderId
        });
        const res = JSON.parse(resStr);
        this.rows = res.rows;

        for (let i=1; i<=5; i++) {
            const row = this.rows[i-1];
            if (!row) {
                continue;
            }
            const item = cc.find(`item${i}`, levelNode);
            item.attr({syllabusId: row.id});
            if (row.cover) {
                const coverFrame: any = await asyncGetSpriteFrimeByUrl(row.cover);
                cc.find(`cover`, item).getComponent(cc.Sprite).spriteFrame = coverFrame;
            }
        }
    }

    initBg() {
        const bg1 = cc.find('Canvas/L1/bg');
        bg1.scale = this._mapScaleMax;
        const bg2 = cc.find('Canvas/L2/bg');
        bg2.scale = this._mapScaleMax;
        const bg3 = cc.find('Canvas/L3/bg');
        bg3.scale = this._mapScaleMax;
        const bg4 = cc.find('Canvas/L4/bg');
        bg4.scale = this._mapScaleMax;
        const bg5 = cc.find('Canvas/L5/bg');
        bg5.scale = this._mapScaleMax;
    }

    initListener() {
        const btnReturn = cc.find('Canvas/btn_return');
        buttonOnClick(btnReturn, () => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                middleLayer.getComponent('middleLayer').loadOnlineBundle("NJ_MoreGames");
            }
        }, 0.6);

        const levelNode = cc.find(`Canvas/${this.level}`);
        for (let i = 1; i <= 5; i++) {
            const item = cc.find(`item${i}`, levelNode);
            buttonOnClick(item, () => {
                const syllabusId = item["syllabusId"];
                const middleLayer = cc.find('middleLayer');
                if (!middleLayer) {
                    return;
                }
                const middleLayerComponent = middleLayer.getComponent('middleLayer');
                if (!syllabusId) {
                    middleLayerComponent.showTips("未解锁 [101]");
                    return;
                }
                if (i>2 && middleLayerComponent.isLogin == false) {
                    // 游客可以玩前两个游戏
                    middleLayerComponent.showConfirm("需要登录后才能使用，去登录吗？", ()=>{
                        middleLayerComponent.loadOnlineBundle('NJ_login');
                    });
                    return;
                }
                middleLayerComponent.setData('NJ_MoreGames_CourseList', {
                    syllabusId,
                });
                jumpToCourseWare(syllabusId);
            }, item.scale);
        }
    }

    async randomPop() {
        const popTemplate = cc.find('Canvas/random_pop');
        const newPop = cc.instantiate(popTemplate);
        const time1 = Math.ceil(Math.random() * 5) / 5 + 10;
        const x = Math.ceil(Math.random() * this.node.width) - this.node.width / 2;
        const y = this.node.height / 2 + newPop.height / 2;

        newPop.setPosition(x, -y);
        newPop.scale = this.getRandomNum(0.4, 1);
		newPop.opacity = this.getRandomNum(80, 200);
        newPop.active = true;
        newPop.parent = this.node;

        cc.tween(newPop)
            .to(time1, {y: y})
            .call(() => {
                newPop.removeFromParent();
                newPop.destroy();
            })
            .start()

        const time2 = this.getRandomNum(3, 5);
		const moveLength = this.getRandomNum(10, 50);
		cc.tween(newPop)
			.by(time2, {x: -moveLength}, {easing:"sineInOut"})
			.by(time2, {x: moveLength}, {easing:"sineInOut"})
			.union()
			.repeatForever()
			.start();

        await asyncDelay(1.2)
        if (this.isDestroy) {
            return;
        }
        this.randomPop();
    }

    getRandomNum(startNum, endNum) {
		return startNum + Math.random() * (endNum - startNum);
	}

    isDestroy: boolean = false;
    protected onDestroy(): void {
        this.isDestroy = true;
    }
}
