import { asyncDelay, onHomeworkFinish } from "../script/util_hy11_paopao";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy11_paopao";
import pg from "./pg_hy11_paopao";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push({ url: this.data.pic_url });
        this._imageResList.push({ url: this.data.pic_url_2 });
    }

    addPreloadAudio() {
        // let audios = [];
        // function checkAudio(obj) {
        //     for (let idx in obj) {
        //         if (typeof obj[idx] == "object") {
        //             checkAudio(obj[idx]);
        //         } else if (typeof obj[idx] == "string") {
        //             if (obj[idx].indexOf(".mp3") > -1) audios.push(obj[idx]);
        //         }
        //     }
        // }
        // checkAudio(this.data)
        this._audioResList = []//audios;
    }

    addPreloadAnima() {

    }
    protected onDestroy(): void {
        pg.event.clear();
    }
    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData()
        this.initView()
        this.initEvent()
        pg.event.once('npc_voice_play_voice_end', () => {
            this.initGame()
        })
        pg.event.emit('npc_layer_back_init', this.data)
    }
    initData() {
        this.current = -1;
        this.data.questions.forEach(question => {
            question.options.sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
                .sort((A, B) => Math.random() - 0.5)
        })
    }
    private btn_megaphone: cc.Node;
    initView() { }
    initEvent() {
        this.btn_megaphone = pg.view.find(this, 'layer_game/btn_megaphone')
        // 底部海螺点击事件
        pg.view.touchOn(this.btn_megaphone, this.onTouchMegaphone, this)
    }
    onTouchMegaphone() {
        if (this.gameOverEnd) return;
        if (!this.startCreate) return;
        //发音
        cc.audioEngine.stopAllEffects();
        pg.event.emit('img_voice_play_voice_start')
        pg.audio.playAudioByUrl(this.currentQuestion.questionAudio, () => {
            pg.event.emit('img_voice_play_voice_end')
        });
    }

    resetView() { };
    initGame() {
        this.btn_megaphone.y = -642;
        this.nextQuestion();
    }
    replay() {
        this.initData();
        this.resetView();
        this.initGame();
    }

    sendData(score) {
        return new Promise(res => {
            if (!cc.find('middleLayer')) return;
            let upData: any = {
                word_count: this.data.word_count || 0,
                sentence_count: this.data.sentence_count || 0,
                zi_count: this.data.zi_count || 0,
                score: score || 0,
            };
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.recordList = recordList
            }
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            console.log('upload->' + JSON.stringify(upData))
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }

    private gameOverEnd: boolean;
    gameOver() {
        this.touchForid = true;
        if (this.gameOverEnd) return;
        this.gameOverEnd = true;
        if (!cc.find('middleLayer')) return;
        this.sendData(this.data.questions.length * 3).then(() => {
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.saveGolds(this.data.questions.length * 3); // 保存金币数量；num 是获得金币的数量，数字类型；
            middleLayer.goNextPage();  // 跳转到下一页
        })
    }
    
    private rightList: Array<any>;
    private createCount: number;
    private startCreate: boolean;
    private lastTime: number;
    nextQuestion() {
        this.current++;// 自动切换下一题
        if (!this.currentQuestion) {
            this.gameOver();
            return;
        }
        this.currentQuestion.options = this.currentQuestion.options.map((op, i) => {
            op.id = i;
            return op;
        })
        this.startCreate = false;
        this.createCount = -1;
        this.lastTime = new Date().getTime();
        this.rightList = [];
        pg.view.find(this, 'layer_game/layer_paopao').removeAllChildren();
        this.startQuestion();
    }
    startQuestion() {
        // 开始海螺从底部升起
        cc.tween(this.btn_megaphone).to(1.5, { y: -438 }).start()
        // 播放音频
        pg.event.emit('img_voice_play_voice_start')
        pg.audio.playAudioByUrl(this.currentQuestion.questionAudio, () => {
            pg.event.emit('img_voice_play_voice_end')
            // 摇晃海螺
            this.aniShake(this.btn_megaphone).then(() => { this.startCreate = true; })
        });
    }
    private current: number;
    get currentQuestion() {
        return this.data.questions[this.current];
    }
    get currentRightList() {
        return this.currentQuestion.options.filter(op => op.right);
    }
    // 制造气泡
    update() {
        if (!this.startCreate) return;
        let nowTime = new Date().getTime();
        if (nowTime - this.lastTime < 2 / 3 * 1000) return;
        this.lastTime = nowTime;
        this.createCount++;
        let data = this.currentQuestion.options[this.createCount % this.currentQuestion.options.length]
        if (!data) return;
        if (this.rightList.some(dt => JSON.stringify(dt) == JSON.stringify(data))) return;
        let layer_paopao = pg.view.find(this, 'layer_game/layer_paopao')
        if (layer_paopao.children.some(child => JSON.stringify(child.data) == JSON.stringify(data))) return;
        let paoaoParent = pg.view.find(this, 'layer_game/paopao')
        // 创建泡泡
        let newPaoPao = cc.instantiate(paoaoParent)
        layer_paopao.addChild(newPaoPao)
        this.updatePaoPao(newPaoPao, data);
        // 做动画
        pg.hw.playLocalAudio('create')
        this.aniPaoPaoFly(newPaoPao).then(() => {
            // 泡泡自行销毁
            newPaoPao.parent = null;
        })
    }
    updatePaoPao(item, data) {
        let bubble = item.getChildByName("bubble")
        let broken = item.getChildByName("bubble_broken")
        let img = bubble.getChildByName("img")
        let text = bubble.getChildByName("text")
        pg.view.visible(broken, false)
        // 判断是显示图片还是文字
        if (data.type === 'img') {
            pg.view.visible(img, true)
            pg.view.visible(text, false)
            pg.view.setNetImg(img, data.image, { w: 180, h: 160 })
        } else {
            pg.view.visible(img, false)
            pg.view.visible(text, true)
            pg.view.setString(text, data.text)
        }
        // 点击泡泡
        item.data = data;
        pg.view.touchOn(item, this.touchPaoPao, this)
    }
    // 点击泡泡
    private touchForid: boolean;
    touchPaoPao(e: any) {
        console.log(this.gameOverEnd);
        if (this.gameOverEnd) return;
        if (this.touchForid) return;
        this.touchForid = true;
        // 如果泡泡没有到指定位置不允许点击
        let item = e.target;
        let data = e.target.data;
        if (data.right) {
            pg.hw.playLocalAudio('right')

            cc.Tween.stopAllByTarget(item)
            // 成功  泡泡破碎  里面的内容消失
            let bubble = e.target.getChildByName("bubble")
            let broken = e.target.getChildByName("bubble_broken")
            pg.view.visible(bubble, false)
            pg.view.visible(broken, true)
            this.scheduleOnce(() => {
                item.parent = null;
                this.touchForid = false;
            }, 0.5);
            this.rightList.push(data);

            if (this.rightList.length == this.currentRightList.length) {
                cc.Tween.stopAll();
                this.startCreate = false;

                pg.event.once('layer_coin_show_coin_end', () => {
                    this.nextQuestion();
                })
                // 动画回调
                pg.event.emit('layer_coin_show_coin', 3)   //1 2 3硬币数量
            }
        } else {
            pg.hw.playLocalAudio('error')
            // 失败  泡泡左右微晃两次
            cc.tween(pg.view.find(item, 'bubble'))
                .to(0.1, { x: -15 })
                .to(0.1, { x: 0 })
                .to(0.1, { x: 15 })
                .to(0.1, { x: 0 })
                .call(() => {
                    this.touchForid = false;
                })
                .start()
        }
    }


    //----------------------------动画相关---------------------------------------------
    aniPaoPaoFly(item) {
        return new Promise((resolve, reject) => {
            pg.view.visible(item, true)
            item.x = 135; item.y = -450; item.scale = 0; item.opacity = 0;
            let positionY = -300 + Math.floor(Math.random() * 300)
            let positionX = -800 + Math.floor(Math.random() * 1600)
            let sub = cc.v2(positionX, positionY).subSelf(cc.v2(item));
            let space = Math.abs(sub.x) + Math.abs(sub.y);
            let timeTo = space / 500;
            let timeUp = 2 + Math.random() * 3;
            cc.tween(item).to(0.3, { scale: 0.3, opacity: 255 }).to(0.5, { scale: 1 }).start();
            cc.tween(item)
                .to(timeTo, { x: positionX, y: positionY })
                .to(timeUp, { y: cc.winSize.height / 2 + 105 })
                .call(() => {
                    resolve('');
                }).start()
        });
    }
    aniShake(item) {
        return new Promise((resolve, reject) => {
            cc.tween(item)
                .to(0.1, { x: -5 }).to(0.1, { x: 0 }).to(0.1, { x: 5 }).to(0.1, { x: 0 })
                .to(0.1, { x: -5 }).to(0.1, { x: 0 }).to(0.1, { x: 5 }).to(0.1, { x: 0 })
                .call(() => {
                    resolve('');
                }).start()
        });
    }
}




