const defaultData = require('../script/defaultData');
import {
    asyncTweenTo,
    asyncShowNode,
    asyncHideNode,
    asyncDelay,
    asyncPlayDragonBoneAnimation,
    exchangeNodePos,
    addButtonListener,
    playEffect,
    stopEffect,
    loadImgByUrl,
    blinkNode,
    stopBlinkNode,
    asyncLoadImgByUrl,
    asyncPlayEffectByUrl,
    asyncLoadDragonBoneAnime,
} from '../script/utils';

cc.Class({
    extends: cc.Component,
    properties: {

    },

    ctor() {
        this._imageResList = [];
        this._audioResList = [];
        this._onLoadFinishFunc = null;
    },

    start() {
        cc.debug.setDisplayStats(false);
        this.data = defaultData;
        this.getData((data) => {
            if (data) {
                this.data = data;
            }
            this.preloadItem();
        });
    },

    getData(func) {
        if (window && window.courseware) {
            window.courseware.getData(func, 'Z_05_nxuan1');
        } else {
            func(defaultData);
        }
    },

    _imageResList: null,
    _audioResList: null,
    preloadItem() {
        this.addPreloadImage();
        this.addPreloadAudio();
        this.preload();
        this.onLoadFinish();
    },

    addPreloadImage() {
        // this._audioResList.push(this.data.tittleImg);
    },

    addPreloadAudio() { },

    preload() {
        const preloadArr = this._imageResList.concat(this._audioResList);
        cc.assetManager.loadAny(preloadArr, null, null, (err, data) => {
            this.hideAirClassLoading();
        });
        if (preloadArr.length == 0) {
            this.hideAirClassLoading();
        }
    },

    hideAirClassLoading() {
        if (window && window["air"]) {
            window["air"].hideAirClassLoading();
            console.log('hideAirClassLoading');
        }
    },

    onLoadFinish() {

        this.initStatus();

        this.initNodes();

        this.initListeners();

        this.updateBgSize();

        if (this._onLoadFinishFunc && typeof (this._onLoadFinishFunc) == 'function') {
            this._onLoadFinishFunc();
        }

        this.showQuestion();
    },

    initStatus() {
        this.status = {
            currentQuestionIdx: 0
        }
    },

    initNodes() {
        const tittleLabelNode = cc.find('Canvas/bgFrount/leef/TittleLabelNode');
        tittleLabelNode.getComponent(cc.Label).string = this.data.tittleTxt;
    },

    initListeners() {
        addButtonListener(cc.find('Canvas/BtnNode/BtnBefore'), () => {
            if (this.status.currentQuestionIdx <= 0) {
                return;
            }
            this.status.currentQuestionIdx--;
            this.showQuestion();
        });

        addButtonListener(cc.find('Canvas/BtnNode/BtnNext'), () => {
            if (this.status.currentQuestionIdx + 1 >= this.data.questionList.length) {
                return;
            }
            this.status.currentQuestionIdx++;
            this.showQuestion();
        });

        addButtonListener(cc.find('Canvas/BtnNode/BtnRefresh'), () => {
            this.showQuestion();
        });

        cc.find('Canvas/bgFrount/leef/TittleLabelNode').on('click', () => {
            this.playIncomeAudio();
        });

        cc.find('Canvas/QuestionLabelBg/QuestionLabelNode').on('click', () => {
            this.playQuestionAudio();
        });
    },

    updateBgSize() {

    },

    async showQuestion() {
        this.showOptions();
        this.playIncomeAudio();
        await this.questionBoardDown();
        this.playQuestionAudio();
    },

    playIncomeAudio() {
        asyncPlayEffectByUrl(this.data.tittleAudio);
    },

    playQuestionAudio() {
        const audioUrl = this.data.questionList[this.status.currentQuestionIdx].questionAudio;
        asyncPlayEffectByUrl(audioUrl);
    },

    showOptions() {
        for (let i = 0; i < 4; i++) {
            const optionNode = cc.find(`Canvas/optionNode_${i}`);
            if (optionNode) {
                optionNode.removeFromParent();
            }
        }
        const optionList = this.data.questionList[this.status.currentQuestionIdx].optionList;
        optionList.forEach(async (data, idx) => {
            const optionNode = cc.instantiate(cc.find(`OptionNodeBase_${optionList.length}`));
            optionNode.name = `optionNode_${idx}`;
            optionNode.parent = cc.find('Canvas');
            optionNode.addComponent(cc.Button);
            optionNode.canClick = true;
            optionNode.on('click', () => {
                this.onOptionClicked(optionNode, idx);
            });

            const posNode = cc.find(`Canvas/OptionPosListBase/Option_${optionList.length}_${idx}`)
            optionNode.x = posNode.x;
            optionNode.y = posNode.y;

            const animeNode = await asyncLoadDragonBoneAnime(cc.find('OptionDragonBoneBaseNode', optionNode), data.optionDragonBone);
            animeNode.scale = Math.min(260 / animeNode.width, 360 / animeNode.height, 1);
            animeNode.name = 'animeNode';
            animeNode.addComponent(cc.Button);
            animeNode.on('click', () => {
                this.onOptionClicked(optionNode, idx);
            });

            const btnFlower = cc.find('OptionSpeakerBtn/BtnFlower', optionNode);
            const btnFlowerP = cc.find('OptionSpeakerBtn/BtnFlower_P', optionNode);
            addButtonListener(cc.find('OptionSpeakerBtn', optionNode), async () => {
                blinkNode(optionNode, btnFlowerP, btnFlower);
                await asyncPlayEffectByUrl(data.optionAudio);
                // asyncPlayDragonBoneAnimation(animeNode, 'smoke', 1);
                asyncPlayDragonBoneAnimation(animeNode, 'normal', 1);

                stopBlinkNode(optionNode, btnFlowerP, btnFlower);
            });
        });
    },

    async onOptionClicked(optionNode, idx) {
        if (!optionNode.canClick) {
            return;
        }
        optionNode.canClick = false;
        if (this.data.questionList[this.status.currentQuestionIdx].rightOptionIdx == idx) {
            this.onOptionRight(optionNode, idx);
            return;
        }
        this.onOptionWrong(optionNode);
    },

    onOptionWrong(optionNode) {
        const animeNode = cc.find('OptionDragonBoneBaseNode/animeNode', optionNode);
        animeNode.color = cc.color(150, 150, 150, 255);
    },

    onOptionRight(optionNode, idx) {
        const optionList = this.data.questionList[this.status.currentQuestionIdx].optionList;
        const posNode = cc.find(`Canvas/OptionPosListBase/OptionTarget_${optionList.length}_${idx}`)

        cc.tween(optionNode)
            .to(1, { x: posNode.x }, { easing: 'quadIn' })
            .start();
        cc.tween(optionNode)
            .to(1, { y: posNode.y, scale: 0.3 })
            .to(0.5, { opacity: 0 })
            .start();
    },

    async questionBoardDown() {
        const questionLabel = cc.find('Canvas/QuestionLabelBg/QuestionLabelNode').getComponent(cc.Label);
        questionLabel.string = this.data.questionList[this.status.currentQuestionIdx].questionTxt;

        const labelBgNode = cc.find('Canvas/QuestionLabelBg');
        await asyncTweenTo(labelBgNode, 1, { y: 263 });
    },

    async questionBoardUp() {
        const labelBgNode = cc.find('Canvas/QuestionLabelBg');
        await asyncTweenTo(labelBgNode, 1, { y: 463 });
    },
});
