import { asyncDelay, onHomeworkFinish } from "../script/util_sn09_xuanze";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_sn09_xuanze";
import pg from "./pg_sn09_xuanze";
import ImgVoice from "./ImgVoice2_sn09_xuanze";

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() {
        pg.view.touchOn(this.btn_voice, this.onTouchVoice, this);
    }
    private audioId: any;
    onTouchVoice() {
        if (!this.canTouch) return;
        if (this.audioId) {
            cc.audioEngine.stopEffect(this.audioId);
            this.btn_voice.getComponent(ImgVoice).playVoiceEnd();
        }
        this.btn_voice.getComponent(ImgVoice).playVoiceStart();
        pg.audio.playAudioByUrl(this.currentQuestion.questionAudio, () => {
            this.audioId = null;
            this.btn_voice.getComponent(ImgVoice).playVoiceEnd();
            this.startCreate = true;
        }, audioId => {
            this.audioId = audioId;
        })
    }

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

        this.btn_voice.getComponent(ImgVoice).playVoiceStart();
        pg.audio.playAudioByUrl(this.currentQuestion.questionAudio).then(() => {
            this.btn_voice.getComponent(ImgVoice).playVoiceEnd();
            this.startCreate = true;
            // pg.hw.playLocalAudio('countdown', true).then((id) => {
            //     this.loopId = id;
            // })
        })
    }
    @property(cc.Node)
    private btn_voice: cc.Node = null;
    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(-300, 0)
                , cc.v2(300, 0)
            ], [
                cc.v2(-600, 0)
                , cc.v2(0, 0)
                , cc.v2(600, 0)
            ],
        ]
        let posArr = posList[list.length - 2];
        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, i);
        }
        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, i) {
        let bubble = item.getChildByName("bubble")
        let bg_img_0 = bubble.getChildByName('bg_img_0')
        let bg_img_1 = bubble.getChildByName('bg_img_1')
        let bg_img_2 = bubble.getChildByName('bg_img_2')
        bg_img_0.active = i == 0;
        bg_img_1.active = i == 1;
        bg_img_2.active = i == 2;
        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: 270, h: 270 })
        } 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)
        pg.view.visible(item, true)

        item.x = pos.x;
        item.y = pos.y - 1000
        let time = i == 1 ? 1.3 : i == 2 ? 1.6 : 2;// 
        cc.tween(item)
            .to(time, { y: pos.y })
            .to(0.3, { scaleY: 1.1, y: pos.y + 50 })
            .to(0.3, { scaleY: 1, y: pos.y })
            .call(() => {

            }).start();
    }
    // 点击泡泡
    touchPaoPao(e: any) {
        if (!this.canTouch) return;
        // 如果泡泡没有到指定位置不允许点击
        let item = e.target;
        let data = e.target.data;
        // 成功  泡泡破碎  里面的内容消失
        let bubble = e.target.getChildByName("bubble")
        let broken = e.target.getChildByName("bubble_broken")
        let right = e.target.getChildByName("bubble_right")
        if (data.right) {
            this.rightList.push(data);
            cc.Tween.stopAllByTarget(item)
            pg.view.visible(right, true)


            pg.hw.playLocalAudio('right')
            pg.view.playDBAnimation(right, "newAnimation", 1)

            cc.tween(item).delay(0.5).call(() => {
                // 处理剩余的节点
                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, i) => {
                        if (this.rightList.some(dt => node.data.id == dt.id)) return;
                        cc.tween(node).by(0.5 + (i / children.length) * 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);
            }).by(0.5, { y: 1500 }).start();
        } else {
            pg.view.visible(bubble, false)
            pg.view.visible(broken, true)
            // 处理闪电效果
            broken.getComponent(ImgVoice).playVoiceStart();
            pg.hw.playLocalAudio('error').then(() => {
                broken.getComponent(ImgVoice).playVoiceEnd();
                pg.view.visible(bubble, true)
                pg.view.visible(broken, false)
            })
        }
    }


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



