import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import { Cat } from "../script/Cat";
import { PicArea } from "../script/PicArea";
import { getLetterArr, Word, WordArea, WordArea2, WordGroup } from "../script/Entites";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    /**
     * 猫咪节点
     */
    cat: Cat;

    picArea: PicArea;

    //单词区域1
    wordArea: WordArea;

    /**单词区域*/
    wordArea2: WordArea2;

    //次数
    playTimes = 0;

    //最大次数
    readonly MAX_PLAY_TIMES = 2;

    /**是否结束 */
    _end = false;

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        if (this.data.pic && this.data.pic.picUrl) {
            this._imageResList.push({ url: this.data.pic.picUrl });
        }
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        const add = (item, key) => {

            if (!item) {
                return;
            }
            item[key] && this._audioResList.push({ url: item[key] });
        }

        const addWord = (arr) => {

            if (!arr) {
                return;
            }

            for (let word of arr) {
                add(word, 'audioUrl');
            }
        }


        add(this.data, 'guideAudioUrl1');
        add(this.data, 'guideAudioUrl2');
        add(this.data, 'guideAudioUrl3');

        if (this.data.exercises) {

            let exercises = this.data.exercises;

            addWord(exercises.wordArr);
            addWord(exercises.wordArr2);

            add(exercises, 'word');
            add(exercises, 'word2');
        }
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
    }

    protected onDestroy(): void {
        cc.Tween.stopAll();
    }

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = false;

        //将“=”右边的数据添加到数组中
        this.data.exercises.wordArr.push(this.data.exercises.word);

        //将组合后的单词添加到数组中
        this.data.exercises.wordArr2.push(this.data.exercises.word2);
    }

    initView() {
        this.initBg();

        this.initCat();

        this.initPicArea();

        this.initWordArea();

        this.beginGame();
    }

    initBg() {
        const bgNode = cc.find('Canvas/bg');
        bgNode.scale = this._mapScaleMax;

        const canvas = cc.find('Canvas');
        bgNode.scale = Math.max((canvas.width / bgNode.width), (canvas.height / bgNode.height));
    }

    private initCat() {
        this.cat = new Cat(this);
        this.cat.data = this.data;
        this.cat.init();
    }

    private initPicArea() {

        //图片区域
        this.picArea = new PicArea(this.cat);
        this.picArea.data = this.data.pic;
        this.picArea.node = cc.find("Canvas/center/pic_area");
        this.picArea.init();
        this.picArea.canTouch = true;

        this.picArea.node.addComponent(cc.Button);

        this.picArea.node.on('click', () => {

            if (!this._cantouch) {
                return;
            }

            //设置不可点击
            this._cantouch = false;

            this.picArea.click(() => {
                //设置可点击
                this._cantouch = true;
            });

        })

    }

    private initWordArea() {

        const getWord = (val, color, audioUrl) => {

            let word = new Word(this.cat);

            let valArr = getLetterArr(val);
            word.data = valArr;
            word.audioUrl = audioUrl;
            word.buildWordNode(color);
            word.node.addComponent(cc.Button);
            word.node.opacity = 0;

            return word;
        }

        this.wordArea = new WordArea();
        this.wordArea.node = cc.find("Canvas/center/row");
        this.wordArea.data = this.data.exercises;

        //单词数组
        let wordArr = this.wordArea.data.wordArr;

        for(let i = 0; i < wordArr.length; ++ i){
            let word = wordArr[i];
            const node = getWord(word.val, word.fontColor, word.audioUrl);
            this.wordArea.addWord(node);
        }

        this.wordArea2 = new WordArea2(this.cat, this.data.exercises.wordArr2);
        this.wordArea2.init();
    }


    playLocalAudio(audioName, callback = null) {
        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);

                callback && callback();
            });
        })
    }

    /**
      * 开始游戏
      */
    beginGame() {
        const play = () => {

            this.cat.playAni('normal', 0);

            this.cat.canTouch = true;


            //依次播放卡片
            this.play(this.wordArea, 0);
        }

        if (this.data.guideAudioUrl1) {

            //播放开始动画
            this.cat.playAni('begin', 0);

            //播放引导音频1
            this.playAudioByUrl(this.data.guideAudioUrl1, () => {

                play();
            });
        }
        else {

            play();
        }
    }


    /**
      * 播放卡片
      * @param wordArea 
      * @param index 
      */
    play(wordArea: WordArea, index = 0) {

        let word = wordArea.wordArr[index];

        let last = wordArea.wordArr.length - 1;

        if (index == 0) {
            wordArea.show();

            for(let i = 0 ; i < last; ++ i){
                cc.tween(wordArea.wordArr[i].node).to(0.1, { opacity: 255 }).start();
            }
        }

        if (index == last) {

            wordArea.equalNode.active = true;

            cc.tween(wordArea.wordArr[index].node).to(0.1, { opacity: 255 }).start();

        }

        word.click(() => {

            if (index == last) {
                this.playTimes++;

                if (this.playTimes == 1) {
                    this.play(this.wordArea, 0);
                }
                else if (this.playTimes >= this.MAX_PLAY_TIMES) {
                    //显示下一行
                    this.wordArea2.show(()=>{
                        this.wordArea2.click(()=>{
                            this.showEnd();
                        });
                    });
                    
                    
                }

            }
            else {
                this.play(wordArea, index + 1);

            }
        })
    }


    /**
     * 显示结束画
     */
    showEnd() {

        console.log("play end...");

        this._end = true;


        if (this.data.guideAudioUrl3) {

            //设置屏幕不可点击
            this._cantouch = false;

            const state = this.cat.playAni('begin', 0);

            this.playAudioByUrl(this.data.guideAudioUrl3, () => {

                //设置屏幕可点击
                this._cantouch = true;

                state.stop();
                this.cat.playAni('normal', 0);
                onHomeworkFinish();
            })
        } else {
            onHomeworkFinish();
        }

        //设置所有卡片可点击
        for (let i = 0; i < this.wordArea.wordArr.length; ++i) {

            let word = this.wordArea.wordArr[i];
            word.canTouch = true;

            //移除点击事件
            word.node.off('click');

            //绑定新事件
            word.node.on('click', () => {

                if (!this._cantouch) {
                    return;
                }
                this._cantouch = false;

                word.click(() => {
                    this._cantouch = true;
                });


            })
        }

        this.wordArea2.card.on('click', ()=>{
            if (!this._cantouch) {
                return;
            }
            this._cantouch = false;

            this.wordArea2.click(()=>{
                this._cantouch = true;
            })
        })
    }
}
