import { asyncCallNetworkApiGet, buttonOnClick, jumpToCourseWare } from "../script/util_NJ_YueDuJiaYouZhan";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_NJ_YueDuJiaYouZhan";

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;
        if (this.currentIndex !==0) {
            cc.find(`Canvas/bg/L1`).x = -4000;
        }
        cc.find(`Canvas/bg/right`).active = this.currentIndex < 4;
        cc.find(`Canvas/bg/left`).active = this.currentIndex > 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) {
            this.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/v3/tree', {
            pid: pid, deep: 2
        });
        const ballData = JSON.parse(classDataStr).rows;

        for (let _index=0; _index<5; _index++) {
            const data = ballData[_index];
            const idx = _index;
            const level = cc.find(`Canvas/bg/L${idx+1}`);
            if (!data) {
                buttonOnClick(cc.find(`book${1}`, level), ()=>{ this.showTips("精彩在路上~ 敬请期待！") });
                buttonOnClick(cc.find(`book${2}`, level), ()=>{ this.showTips("精彩在路上~ 敬请期待！") });
                buttonOnClick(cc.find(`book${3}`, level), ()=>{ this.showTips("精彩在路上~ 敬请期待！") });
                continue;
            }
            for (let j=0; j<3; j++) {
                const book = data.children[j];
                if (!book) {
                    buttonOnClick(cc.find(`book${j+1}`, level), ()=>{ this.showTips("内容未制作！") });
                    continue;
                }
                const bookNode = cc.find(`book${j+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) {
                            this.showTips("未配置‘索引页’");
                            return;
                        }
                        middleLayerComponent.setData('NJ_BookTable', {
                            levelId: book.pid,
                            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);

        const left = cc.find('Canvas/bg/left');
        buttonOnClick(left, () => {
            if (!this._cantouch) {
                return;
            }
            this.rightMove();
        });
        const right = cc.find('Canvas/bg/right');
        buttonOnClick(right, () => {
            if (!this._cantouch) {
                return;
            }
            this.leftMove();
        });
    }

    touchX;
    onEventStart(event) {
        const worldPoint = event.getLocation();
        this.touchX = worldPoint.x;
    }
    onEventEnd(event) {
        const worldPoint = event.getLocation();
        const x = worldPoint.x;
        if (!this._cantouch) {
            return;
        }
        if (x > this.touchX + 100) {
            if (this.currentIndex <= 0) {
                // 已经是第一个了
                return;
            }
            this.rightMove();

        }
        if (x < this.touchX - 100) {
            if (this.currentIndex >= 4) {
                // 已经是最后一个了
                return;
            }
            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);
            });
        })
    }

    showTips(tips) {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            middleLayer.getComponent('middleLayer').showTips(tips);    
        } else {
            console.log(tips);
        }
    }
}
