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

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    @property(cc.AudioClip)
    bgMusic1: cc.AudioClip = null;

    async getKidInfo() {
        const kidDataStr = await asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
            token: cc.sys.localStorage.getItem('token')
        });
        if (kidDataStr) {
            return JSON.parse(kidDataStr).data;
        }
        return null;
    }

    addPreloadImage() {
    }

    addPreloadAudio() {
    }

    addPreloadAnima() {

    }
    _cantouch = null;
    async onLoadEnd() {
        this._cantouch = true;
        this.initListener();

        // 浏览记录
        this.currentIndex = this.getStoreCurrentIndex();
        const node = cc.find(`Canvas/bg/L${this.currentIndex + 1}`);
        node.x = 0;

        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            cc.sys.localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NCwicGhvbmUiOiIxNTUwMDAwMDAwMSIsInNpZ24iOiI0OTliYjg5Yy1lYjI5LTQ2M2EtYjk5ZS0zNDg2NDUwMGEyOTkiLCJpYXQiOjE2NTQ2NzY4MzMsImV4cCI6MTY1NzI2ODgzM30.MacCd_XUhvpNrMukYu8YNRVSbc-hju_WBN_FeiRACuc');
        }
        const kidDataStr = await asyncCallNetworkApiGet('/api/oxford/v1/kid/info', {
            token: cc.sys.localStorage.getItem('token')
        });
        const kidData = JSON.parse(kidDataStr);
        if (!kidData.data || !kidData.data.id) {
            middleLayer.getComponent('middleLayer').showTips("用户登录失效，请重新登录");
            middleLayer.getComponent('middleLayer').loadOnlineBundle("NJ_login");
            return;
        }

        const btnReturn = cc.find('Canvas/bg/btn_return');
        buttonOnClick(btnReturn, () => {
            const middleLayer = cc.find('middleLayer');
            if (middleLayer) {
                middleLayer.getComponent('middleLayer').loadOnlineBundle('NJ_YouLeChang');
            }
        });
        const pid = middleLayer.getComponent('middleLayer').getData('NJ_YueDuJiaYouZhan');

        const classDataStr = await asyncCallNetworkApiGet('/api/syllabus/v1/tree', {
            pid: pid, deep: 2
        });
        const ballData = JSON.parse(classDataStr);

        ballData.forEach((data, idx) => {
            if (idx >= 5) {
                console.warn('idx >= 5');
                return;
            }
            const level = cc.find(`Canvas/bg/L${idx+1}`);
            data.children.forEach((book, i) => {
                if (i >= 3) {
                    console.warn('book >= 3');
                    return;
                }
                const bookNode = cc.find(`book${i+1}`, level);
                bookNode.attr({syllabus_id: book.id, pid: book.pid});

                buttonOnClick(bookNode, async () => {
                    const kidInfo = await this.getKidInfo();
                    const activeLevels = kidInfo ? kidInfo.active_levels : [];
                    const activeItem = activeLevels.find(item => item.syllabus_id == data.id);
                    if (middleLayer && !activeItem) {
                        // 弹出激活码
                        middleLayer.getComponent('middleLayer').showActiveWindow();
                        return;
                    }
                    if (middleLayer) {
                        const middleLayerComponent = middleLayer.getComponent('middleLayer');
                        const row = book.children.find(row => row.name == '索引页');
                        if (!row) {
                            middleLayerComponent.showTips("未配置‘索引页’");
                            return;
                        }
                        middleLayerComponent.setData('NJ_BookTable', {
                            folderId: book.id,
                            courseId: row.id,
                        });
                        jumpToCourseWare(row.id);
                    }
                });
            });
        });

        // 播放背景音乐
        cc.audioEngine.stopMusic();
        cc.audioEngine.playMusic(this.bgMusic1, true);
    }

    storeCurrentIndex() {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            return;
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        middleLayerComponent.setData('NJ_YueDuJiaYouZhan_select_idx', this.currentIndex);
    }

    getStoreCurrentIndex() {
        const middleLayer = cc.find('middleLayer');
        if (!middleLayer) {
            return 0;
        }
        const middleLayerComponent = middleLayer.getComponent('middleLayer');
        const index = middleLayerComponent.getData('NJ_YueDuJiaYouZhan_select_idx');
        return index || 0;
    }


    currentIndex = 0;
    leftMove() {
        const node = cc.find(`Canvas/bg/L${this.currentIndex + 1}`);
        const nextNode = cc.find(`Canvas/bg/L${this.currentIndex + 2}`);
        this._cantouch = false;
        cc.tween(node)
            .to(.3, { x: -4000 }, { easing: 'cubicInOut' })
            .call(() => {
                cc.tween(nextNode)
                    .to(.3, { x: 0 }, { easing: 'cubicInOut' })
                    .call(() => {
                        this.currentIndex++;
                        this.storeCurrentIndex();
                        cc.find(`Canvas/bg/right`).active = this.currentIndex < 4;
                        cc.find(`Canvas/bg/left`).active = this.currentIndex > 0;
                        this._cantouch = true;
                    })
                    .start();
            })
            .start();
    }

    rightMove() {
        const node = cc.find(`Canvas/bg/L${this.currentIndex + 1}`);
        const beforeNode = cc.find(`Canvas/bg/L${this.currentIndex}`);
        this._cantouch = false;
        cc.tween(node)
            .to(.3, { x: 4000 }, { easing: 'cubicInOut' })
            .call(() => {
                cc.tween(beforeNode)
                    .to(.3, { x: 0 }, { easing: 'cubicInOut' })
                    .call(() => {
                        this.currentIndex--;
                        this.storeCurrentIndex();
                        cc.find(`Canvas/bg/right`).active = this.currentIndex < 4;
                        cc.find(`Canvas/bg/left`).active = this.currentIndex > 0;
                        this._cantouch = true;
                    })
                    .start();
            })
            .start();
    }
    // update (dt) {},


    initListener() {
        this.node.on('touchstart', this.onEventStart, this);
        this.node.on('touchend', this.onEventEnd, this);
    }

    touchX;
    onEventStart(event) {
        const worldPoint = event.getLocation();
        this.touchX = worldPoint.x;
    }
    onEventEnd(event) {
        const worldPoint = event.getLocation();
        const x = worldPoint.x;
        if (x > this.touchX + 100) {
            if (this.currentIndex <= 0) {
                // 已经是第一个了
                return;
            }
            console.log("======向右滑动=======");
            this.rightMove();

        }
        if (x < this.touchX - 100) {
            if (this.currentIndex >= 4) {
                // 已经是最后一个了
                return;
            }
            console.log("======向左滑动=======");
            this.leftMove()
        }
    }

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