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() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.audio_url });
    }

    addPreloadAnima() {

    }
    private speed: number;
    private targetPosition: number;
    private touchNumber: number = -1;

    async onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData()
        this.initView()
        this.initEvent()
        this.nextQuestion()
    }
    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)
        })
    }
    initView() { }
    initEvent() {
        let btn_megaphone = pg.view.find(this, 'layer_game/btn_megaphone')
        // 底部海螺点击事件
        pg.view.touchOn(btn_megaphone, this.onTouchMegaphone, this)
    }
    private rightList: Array<any>;
    nextQuestion() {
        this.current++;// 自动切换下一题
        if (!this.currentQuestion) {
            this.gameOver();
            return;
        }
        this.speed = 30
        this.touchNumber = -1;
        this.rightList = [];
        console.log(this.data)
        let layer_paopao = pg.view.find(this, 'layer_game/layer_paopao')
        layer_paopao.removeAllChildren();
        // 底部海螺
        let btn_megaphone = pg.view.find(this, 'layer_game/btn_megaphone')
        // 开始海螺从底部升起
        let btn = cc.tween(btn_megaphone)
        btn.to(1.5, { y: -438 }).call(() => { }).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(btn_megaphone).then(() => {
                this.startCreate = true;
            })
        });
    }
    gameOver() {
        console.log("游戏结束");
    }
    private current: number;
    get currentQuestion() {
        return this.data.questions[this.current];
    }
    get currentRightList() {
        return this.currentQuestion.options.filter(op => op.right);
    }
    onTouchMegaphone() {
        if (!this.startCreate) return;
        //发音
        pg.event.emit('img_voice_play_voice_start')
        pg.audio.playAudioByUrl(this.currentQuestion.questionAudio, () => {
            pg.event.emit('img_voice_play_voice_end')
        });
    }
    onPlayMegaphone() {

    }
    update() {
        this.create_bubbles();
    }
    // 制造气泡
    private startCreate: boolean;
    private lastTime: number;
    create_bubbles() {
        if (!this.startCreate) return;
        let nowTime = new Date().getTime();
        if (!this.lastTime) {
            this.lastTime = nowTime;
        } else {
            if (nowTime - this.lastTime < 2 * 1000) return;
            this.lastTime = nowTime;
        }
        this.touchNumber++;
        let data = this.currentQuestion.options[this.touchNumber % 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;
        })
    }
    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 = Math.floor(Math.random() * 300)
            let positionX = this.getPositionX()
            let timeTo = 2 + Math.random() * 3;
            let timeUp = 5 + Math.random() * 5;
            this.targetPosition = positionY
            cc.tween(item).to(0.3, { scale: 0.3, opacity: 255 }).to(0.5, { scale: 1 }).start();
            cc.tween(item)
                .to(timeTo * 3, { 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()
        });
    }
    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: 150, h: 150 })
        } 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)
    }
    checkFinish() {
        if (this.rightList.length == this.currentRightList.length) {
            cc.Tween.stopAll();
            this.startCreate = false;
            this.scheduleOnce(() => {
                this.nextQuestion();
            }, 0.5)
        }
    }

    getPositionX() {
        if (Math.random() < 0.5) {
            return - Math.floor(Math.random() * 900)
        } else {
            return Math.floor(Math.random() * 900)
        }
    }
    // 点击泡泡
    touchPaoPao(e: any) {
        // 如果泡泡没有到指定位置不允许点击
        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")
            let img = bubble.getChildByName("img")
            let text = bubble.getChildByName("text")
            pg.view.visible(bubble, false)
            pg.view.visible(broken, true)
            // cc.tween(img).to(0.1, { opacity: 0 }).start();
            // cc.tween(text).to(0.1, { opacity: 0 }).start();
            this.scheduleOnce(() => {
                item.parent = null;
            }, 0.2);
            this.rightList.push(data);
            this.checkFinish();
        } else {
            pg.hw.playLocalAudio('error')

            // 失败  泡泡左右微晃两次
            cc.tween(pg.view.find(item, 'bubble'))
                .to(0.1, { x: -5 }).to(0.1, { x: 0 }).to(0.1, { x: 5 }).to(0.1, { x: 0 })
                .start()
        }
    }
}


