const defaultData = require('../script/defaultData');
import {
    asyncTweenTo,
    asyncShowNode,
    asyncHideNode,
    asyncDelay,
    asyncPlayDragonBoneAnimation,
    exchangeNodePos,
    addButtonListener,
    playEffect,
    stopEffect,
    loadImgByUrl,
    jelly,
    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, 'scene');
            return;
        }

        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            middleLayerComponent.getData(func);
            return;
        }

        func(this.getDefaultData());
    },

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

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

    addPreloadAudio() {
        this._audioResList.push({ url: this.data.tittleAudio });
    },

    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.updateButtons();

        this.updateBgSize();

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

        this.showQuestion(true);
    },

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

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

        const canvas = cc.find('Canvas');
        const optionPosListBase = cc.find('Canvas/OptionPosListBase');

        optionPosListBase.scaleX = canvas.width / optionPosListBase.width;
        optionPosListBase.scaleY = canvas.height / optionPosListBase.height;
    },

    updateButtons() {
        const btnBefore = cc.find('Canvas/BtnNode/BtnBefore');
        btnBefore.color = cc.color(255, 255, 255);
        if (this.status.currentQuestionIdx <= 0) {
            btnBefore.color = cc.color(150, 150, 150);
        }

        const btnNext = cc.find('Canvas/BtnNode/BtnNext');
        btnNext.color = cc.color(255, 255, 255);
        if (this.status.currentQuestionIdx + 1 >= this.data.questionList.length) {
            btnNext.color = cc.color(150, 150, 150);
        }
    },

    initListeners() {
        this.node.on('scale-changed', () => {
            console.log('scale-changed');
            this.initNodes();
            this.showQuestion();
            this.updateButtons();
        });

        this.node.on('size-changed', () => {
            console.log('size-changed');
            this.initNodes();
            this.showQuestion();
            this.updateButtons();
        });

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

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

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

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

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

    updateBgSize() {

    },

    async showQuestion(isFirstIncome = false) {
        this.resetQuestionBoard();
        this.showOptions();
        this.questionBoardDown();
        if (isFirstIncome) {
            await this.playIncomeAudio();
            await asyncDelay(1);
        }
        this.playQuestionAudio();
    },

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

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

    showOptions() {
        for (let i = 0; i < 4; i++) {
            const optionNode = cc.find(`Canvas/OptionPosListBase/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/OptionPosListBase');
            optionNode.addComponent(cc.Button);
            optionNode.canClick = true;
            optionNode.on('click', () => {
                this.onOptionClicked(optionNode, idx);
            });

            const optionPosListBase = cc.find('Canvas/OptionPosListBase');
            optionNode.scaleX = Math.min(1, optionPosListBase.scaleX, optionPosListBase.scaleY) / optionPosListBase.scaleX;
            optionNode.scaleY = Math.min(1, optionPosListBase.scaleX, optionPosListBase.scaleY) / optionPosListBase.scaleY;

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

            const btnFlower = cc.find('OptionSpeakerBtn/BtnFlower', optionNode);
            const btnFlowerP = cc.find('OptionSpeakerBtn/BtnFlower_P', optionNode);
            const optionSpeakerBtn = cc.find('OptionSpeakerBtn', optionNode);
            optionSpeakerBtn.on('click', async () => {
                if (!optionNode.canClick) {
                    return;
                }
                if (optionSpeakerBtn.canNotClick) {
                    return;
                }
                optionSpeakerBtn.canNotClick = true;
                playEffect('按钮');
                await jelly(optionSpeakerBtn);

                blinkNode(optionNode, btnFlowerP, btnFlower);
                await asyncPlayEffectByUrl(data.optionAudio);

                const animeNode = await asyncLoadDragonBoneAnime(cc.find('OptionDragonBoneBaseNode', optionNode), data.optionDragonBone);
                if (animeNode) {
                    asyncPlayDragonBoneAnimation(animeNode, 'normal', 1);
                }
                stopBlinkNode(optionNode, btnFlowerP, btnFlower);

                optionSpeakerBtn.canNotClick = false;
            });

            const animeNode = await asyncLoadDragonBoneAnime(cc.find('OptionDragonBoneBaseNode', optionNode), data.optionDragonBone);
            if (!animeNode) {
                return;
            }
            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);
            });
        });
    },

    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);
        if (animeNode) {
            animeNode.color = cc.color(150, 150, 150, 255);
        }
        playEffect('wrong');
    },

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

        playEffect('right');

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

        optionList.forEach(async (data, idx) => {
            const option = cc.find(`Canvas/OptionPosListBase/optionNode_${idx}`);
            option.canClick = false;

            if (option != optionNode) {
                // const animeNode = cc.find('OptionDragonBoneBaseNode/animeNode', option);
                const animeNode = await asyncLoadDragonBoneAnime(cc.find('OptionDragonBoneBaseNode', option), data.optionDragonBone);
                if (animeNode) {
                    animeNode.color = cc.color(255, 255, 255, 255);
                    asyncPlayDragonBoneAnimation(animeNode, 'normal', -1);
                }
            }
        });
    },

    resetQuestionBoard() {
        const labelBgNode = cc.find('Canvas/QuestionLabelBg');
        labelBgNode.stopAllActions();
        labelBgNode.y = 463;
    },

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

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

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