import { asyncDelay, onHomeworkFinish } from "../script/util_sn05_night";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_sn05_night";
import pg from "./pg_sn05_night";

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()
        this.initGame()
    }
    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() {
    }

    resetView() { };
    initGame() {
        this.nextQuestion();
    }
    replay() {
        this.initData();
        this.resetView();
        this.initGame();
    }

    sendData(score) {
        return new Promise(res => {
            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('');
            })
        })
    }

    gameOver() {
        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 startCreate: boolean;
    private lastTime: number;
    nextQuestion() {
        if (this.loopId) cc.audioEngine.stopEffect(this.loopId);
        this.loopId = null;
        this.current++;// 自动切换下一题
        if (!this.currentQuestion) {
            this.gameOver();
            return;
        }

        //TODO: 需要增加总倒计时
        this.totalTime = Number(this.currentQuestion.duration) || 10;//异常只给10秒duration
        this.time = this.totalTime
        this.currentQuestion.options = this.currentQuestion.options.map((op, i) => {
            op.id = i;
            return op;
        })
        this.lastTime = new Date().getTime();
        this.rightList = [];


        pg.view.find(this, 'layer_game/layer_paopao').removeAllChildren();
        this.startQuestion();

        pg.audio.playAudioByUrl(this.currentQuestion.questionAudio).then(() => {
            this.startCreate = true;
            pg.hw.playLocalAudio('countdown', true).then((id) => {
                this.loopId = id;
            })
        })
    }
    private loopId: any;
    // 制造气泡
    private canTouch: boolean;
    startQuestion() {
        let layer_paopao = pg.view.find(this, 'layer_game/layer_paopao')
        let paoaoParent = pg.view.find(this, 'layer_game/paopao')
        let list = this.currentQuestion.options;
        let posList = [
            [
                cc.v2(-13, -76)
                , cc.v2(-240, 290)
                , cc.v2(250, 250)
                , cc.v2(300, -310)
                , cc.v2(-340, -300)
                , cc.v2(-655, 300)
                , cc.v2(-670, -90)
                , cc.v2(630, 330)
                , cc.v2(600, -40)
            ],
        ]
        let posArr = posList[0];
        for (let i = 0; i < list.length; i++) {
            let data = list[i]
            let item = cc.instantiate(paoaoParent)
            let pos = posArr[i];
            layer_paopao.addChild(item)
            this.updatePaoPao(item, data, pos);
        }
        pg.hw.playLocalAudio('fly')
        this.scheduleOnce(() => {
            this.canTouch = true;
        }, 2)
    }
    private current: number;
    get currentQuestion() {
        return this.data.questions[this.current];
    }
    get currentRightList() {
        return this.currentQuestion.options.filter(op => op.right);
    }

    updatePaoPao(item, data, pos) {
        let bubble = item.getChildByName("bubble")
        let broken = item.getChildByName("bubble_broken")
        let img = bubble.getChildByName("img")
        let text = bubble.getChildByName("text")
        let img_broken = broken.getChildByName("img")
        let text_broken = broken.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 })
            pg.view.visible(img_broken, true)
            pg.view.visible(text_broken, false)
            pg.view.setNetImg(img_broken, data.image, { w: 180, h: 160 })
        } else {
            pg.view.visible(img, false)
            pg.view.visible(text, true)
            pg.view.setString(text, data.text)
            pg.view.visible(img_broken, false)
            pg.view.visible(text_broken, true)
            pg.view.setString(text_broken, data.text)
        }
        // 点击泡泡
        item.data = data;
        pg.view.touchOn(item, this.touchPaoPao, this)
        pg.view.visible(item, true)

        item.x = pos.x;
        item.y = pos.y - 1000
        cc.tween(item).to(2, { y: pos.y }).call(() => { }).start();
    }
    // 点击泡泡
    touchPaoPao(e: any) {
        // 如果泡泡没有到指定位置不允许点击
        let item = e.target;
        let data = e.target.data;
        if (data.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)
            cc.tween(item).delay(0.5).call(() => {
                pg.hw.playLocalAudio('right')
            }).by(0.5, { y: 1500 }).start();
            this.rightList.push(data);
            // 处理剩余的节点
            if (this.rightList.length == this.currentRightList.length) {
                let layer_paopao = pg.view.find(this, 'layer_game/layer_paopao')
                let children = layer_paopao.children;
                children.forEach(node => {
                    if (this.rightList.some(dt => node.data.id == dt.id)) return;
                    cc.tween(node).by(0.5, { y: -1500 }).start();
                })
            }
            this.scheduleOnce(() => {
                item.parent = null;
                if (this.rightList.length == this.currentRightList.length) {
                    cc.Tween.stopAll();
                    this.startCreate = false;
                    this.nextQuestion();
                }
            }, 1);
        } 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 })
                .start()
        }
    }


    private totalTime;
    private time;
    updateTime() {
        let layer_countdown = pg.view.find(this, 'layer_game/layer_countdown')
        let progress = pg.view.find(layer_countdown, 'progress')
        progress.getComponent(cc.ProgressBar).progress = this.time / this.totalTime;
    }

    update(dt) {
        if (!this.currentQuestion) return;
        if (!this.startCreate) return;
        this.time -= dt;
        if (this.time <= 0) {
            console.log("游戏结束部分")
            this.nextQuestion();
            // return;
        }
        this.updateTime();
    }

    //----------------------------动画相关---------------------------------------------
    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()
        });
    }
}


