import { asyncDelay, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import Game, { GAME_STATE } from "./tool/Game";
import pg from "./tool/pg";
import Box2d from "./box2d";

const { ccclass, property } = cc._decorator;

let win: any = window;
let courseware = win.courseware;
@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() {

    }
    @property(cc.Node)
    layout_start: cc.Node = null;
    @property(cc.Node)
    layout_finish: cc.Node = null;
    @property(cc.Node)
    btn_laba: cc.Node = null;
    @property(cc.Node)
    btn_record: cc.Node = null;
    @property(cc.Node)
    img_laba: cc.Node = null;
    @property(cc.Node)
    img_record: cc.Node = null;
    @property(cc.Node)
    record_word: cc.Node = null;
    @property(cc.Node)
    question_word: cc.Node = null;
    @property(cc.Node)
    box2d: cc.Node = null;

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

    _cantouch = null;
    public isFinish: boolean;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        this.isFinish = false;
        Game.getIns().init(this.data);
        Game.getIns().reset();
    }
    initEvent() {
        let btn_again = cc.find("layout_finish/btn_again", this.node);
        let btn_next = cc.find("layout_finish/btn_next", this.node);
        btn_again.on(cc.Node.EventType.TOUCH_END, this.onAgain, this);
        btn_next.on(cc.Node.EventType.TOUCH_END, this.onNext, this);
        this.btn_record.on(cc.Node.EventType.TOUCH_END, this.onRecord, this);
        this.btn_laba.on(cc.Node.EventType.TOUCH_END, this.showLaba, this);
        this.img_record.on(cc.Node.EventType.TOUCH_END, this.onTouchRecordEnd, this);
        pg.event.on("game_start", () => {
            this.gameStart();
        });
        pg.event.on("check_next_question", () => {
            // this.checkRoundEnd();
        });
        pg.event.on("mouse_10_num_game_end", () => {
            this.checkRoundEnd();
        });
    }

    initView() {
        // 使用物理引擎
        this.initStart();
        this.gameStart(false);

    }
    gameStart(isPlayAudio = true) {
        Game.getIns().state = GAME_STATE.RUNNING;
        this.showQuestion();
        isPlayAudio && this.showLaba();
    }

    private onAgain() {
        this.layout_finish.active = false;
        this.playLocalAudio("again");
        this.initData();
        this.record_word.getComponent(cc.Label).string = "";
        this.question_word.getComponent(cc.Label).string = "";
        pg.event.emit("mouse_10_num", Game.getIns().total);
        this.gameStart();
    }
    private onNext() {

    }
    update(dt) {
        // let item = this.node.getChildByName("item");
        // item.y -= 5;
    }

    private showQuestion() {
        let question = Game.getIns().getCurrentPage();
        this.question_word.getComponent(cc.Label).string = question.text;

    }




    private showTip(show = true) {
        let tip_bg = cc.find("btn_record/tip_bg", this.node);
        tip_bg.y = -115;
        cc.Tween.stopAllByTarget(tip_bg);
        if (!show) {
            tip_bg.active = false;
            return;
        }
        tip_bg.active = true;
        cc.tween(tip_bg).to(0.5, { y: -125 }).to(0.5, { y: -115 })
            .to(0.5, { y: -125 }).to(0.5, { y: -115 })
            .to(0.5, { y: -125 }).to(0.5, { y: -115 })
            .call(() => {
                tip_bg.active = false;
            })
            .start();
    }

    private recordIntervalId;
    private showRecordAction() {
        this.btn_record.active = false;
        let btn_kaba2 = cc.find("btn_record2", this.img_record);
        let btn_kaba3 = cc.find("btn_record3", this.img_record);
        btn_kaba2.active = true;
        btn_kaba3.active = true;
        this.img_record.active = true;
        cc.audioEngine.stopAllEffects();
        let count = 0;
        if (this.recordIntervalId) clearInterval(this.recordIntervalId);
        let stop = false;
        this.recordIntervalId = setInterval(() => {
            count++;
            btn_kaba2.active = count % 3 < 3;
            btn_kaba3.active = count % 3 < 2;
            if (stop && count % 3 == 2) {
                this.btn_record.active = true;
                this.img_record.active = false;
                clearInterval(this.recordIntervalId);
            }
        }, 150);
        // this.showCountAction(3).then(() => {
        //     stop = true;
        //     this.onTouchRecordEnd();
        //     this.showMikeBgAction();
        // });
    }

    private labaIntervalId;
    private showLaba(show = false) {
        this.btn_laba.active = false;
        let btn_kaba2 = cc.find("btn_voice2", this.img_laba);
        let btn_kaba3 = cc.find("btn_voice3", this.img_laba);
        btn_kaba2.active = true;
        btn_kaba3.active = true;
        this.img_laba.active = true;
        cc.audioEngine.stopAllEffects();
        let count = 0;
        if (this.labaIntervalId) clearInterval(this.labaIntervalId);
        let stop = false;
        this.labaIntervalId = setInterval(() => {
            count++;
            btn_kaba2.active = count % 3 < 3;
            btn_kaba3.active = count % 3 < 2;
            if (stop && count % 3 == 2) {
                this.btn_laba.active = true;
                this.img_laba.active = false;
                clearInterval(this.labaIntervalId);
            }
        }, 150);
        let question = Game.getIns().getCurrentPage();
        pg.audio.playAudioByUrl(question.audio).then(() => {
            stop = true;
            show && this.showTip();
        });
        // this.showCountAction(3).then(() => {
        //     stop = true;
        //     this.onTouchRecordEnd();
        //     this.showMikeBgAction();
        // });
    }

    private async onTouchRecordEnd() {
        let testData = {
            "text": "oh no",
            "audio": "https://staging-teach.cdn.ireadabc.com/6ee3ccaa831a884f02c6a75c6f647cb5.wav"
        }
        if (!courseware) return this.recrodEnd(testData)
        courseware && courseware.stopRecord(0, (data) => {
            data = JSON.parse(data);
            this.log("data: " + JSON.stringify(data));
            this.recrodEnd(data);
        }); //结束录音

    }
    private recrodEnd(data) {
        if (this.recordIntervalId) clearInterval(this.recordIntervalId);
        this.btn_record.active = true;
        this.img_record.active = false;
        this.record_word.getComponent(cc.Label).string = data.text;
        if (data.text == Game.getIns().getCurrentPage().word) {
            this.playLocalAudio("right").then(() => {
                this.playLocalAudio("diaoluo");
            });
            this.box2d.getComponent(Box2d).jumpOrange();
            pg.event.emit("mouse_10_add");
        } else {
            this.playLocalAudio("error").then(() => {
                pg.event.emit("mouse_10_add_error");
            })
        }
    }




    private onRecord() {
        this.playLocalAudio("mkf");
        if (this.labaIntervalId) clearInterval(this.labaIntervalId);
        this.img_laba.active = false;
        this.btn_laba.active = true;
        this.showTip(false);
        this.showRecordAction();
    }

    initListener() {

    }



    private checkRoundEnd() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            // this.gameOver();
            let zjz_ske = cc.find("zjz_ske", this.node);
            zjz_ske.active = true;
            zjz_ske.getComponent(dragonBones.ArmatureDisplay).playAnimation("newAnimation", 1);
            zjz_ske.off(dragonBones.EventObject.COMPLETE);
            this.playLocalAudio("zhazhi");
            zjz_ske.getComponent(dragonBones.ArmatureDisplay).on(dragonBones.EventObject.COMPLETE, () => {
                zjz_ske.active = false;
                this.showFind();
            }, this);
        } else {
            this.playLocalAudio("next");
            this.record_word.getComponent(cc.Label).string = "";
            this.gameStart();
        }
    }



    private showFind() {
        if (this.isFinish) return;
        this.isFinish = true;
        this.playLocalAudio("finish");
        let layout_finish = cc.find("layout_finish", this.node);
        layout_finish.active = true;
        let finish_db = cc.find("finish_db", layout_finish);
        let btn_again = cc.find("btn_again", layout_finish);
        let btn_next = cc.find("btn_next", layout_finish);
        finish_db.active = true;
        btn_again.active = false;
        btn_next.active = false;
        finish_db.getComponent(dragonBones.ArmatureDisplay).playAnimation("newAnimation", 1);
        this.playLocalAudio("finish").then(() => {
            finish_db.active = false;
            btn_again.active = true;
            btn_next.active = true;
        });
    }

    private initStart() {
        this.layout_start.active = true;
        cc.find("layout_top/label_title", this.node).getComponent(cc.Label).string = Game.getIns().title;
        pg.event.emit("mouse_10_num", Game.getIns().total);
        let start_ske = cc.find("layout_start/start_ske", this.node);
        pg.load.loadDB(start_ske, { ske: Game.getIns().aniEnter.ske.url, tex: Game.getIns().aniEnter.tex.url, png: Game.getIns().aniEnter.png.url }).then((animationName) => {
            if (animationName && animationName != "") {
                let db = start_ske.getComponent(dragonBones.ArmatureDisplay);
                let anis = db.getAnimationNames(db.armatureName);
                db.playAnimation(anis[0], 0);
                cc.tween(start_ske).by(1, { x: -500 }).call(() => {
                    pg.audio.playAudioByUrl(Game.getIns().startAudio).then(() => {
                        cc.tween(start_ske).delay(1).by(1, { x: 500 }).call(() => {
                            this.layout_start.active = false;
                            this.showLaba(true);
                        }).start();
                    });
                }).start();
            } else {
                this.layout_start.active = false;
                this.showLaba(true);
            }
        })
    }








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