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

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)
    layout_pic: cc.Node = null;
    @property(cc.Node)
    layout_word: cc.Node = null;
    @property(cc.Node)
    box2d: cc.Node = null;
    @property(cc.Node)
    layout_img: cc.Node = null;

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
    }
    protected onDestroy(): void {
        pg.event.clear();
    }
    _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);
        cc.find("btn_close", this.layout_img).on(cc.Node.EventType.TOUCH_END, this.onCloseTips, 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);
        isPlayAudio && this.showLaba();
    }

    private onAgain() {
        this.layout_finish.active = false;
        let zjz_ske = cc.find("zjz_ske", this.node);
        zjz_ske.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);
        pg.event.emit('box2d_init', Game.getIns().getTotalPageNum());
        this.gameStart();
    }
    private onNext() {

    }
    update(dt) {
        // let item = this.node.getChildByName("item");
        // item.y -= 5;
    }
    private showQuestion(showImg = true) {
        let question = Game.getIns().getCurrentPage();
        if (question.type == "txt") {
            let question_word = cc.find("question_word", this.layout_word);
            question_word.getComponent(cc.Label).string = question.text;
            let record_word = cc.find("record_word", this.layout_word);
            record_word.getComponent(cc.Label).string = "";
            this.layout_word.active = true;
            this.layout_pic.active = false;
        } else {
            let question_word = cc.find("question_word", this.layout_pic);
            question_word.getComponent(cc.Label).string = question.text;
            let record_word = cc.find("record_word", this.layout_pic);
            record_word.getComponent(cc.Label).string = "";
            let pic = cc.find("pic", this.layout_pic);
            pg.view.setNetImg(pic, question.picUrl, { w: 242, h: 242 });
            this.layout_word.active = false;
            this.layout_pic.active = true;
            pic.on(cc.Node.EventType.TOUCH_END, this.showBigPic, this);
            showImg && this.showLayoutImg();
        }
    }

    private showRecordWord(word) {
        let question = Game.getIns().getCurrentPage();
        if (question.type == "txt") {
            let record_word = cc.find("record_word", this.layout_word);
            record_word.getComponent(cc.Label).string = word || "";

        } else {
            let record_word = cc.find("record_word", this.layout_pic);
            record_word.getComponent(cc.Label).string = word || "";
        }
    }
    private showLayoutImg(hide = true) {
        let question = Game.getIns().getCurrentPage();
        if (question.type != "img") return;
        let big_pic = cc.find("big_pic", this.layout_img);
        big_pic.setPosition(0, 0);
        big_pic.scale = 1;
        pg.view.setNetImg(big_pic, question.picUrl, { w: 720, h: 720 });
        this.layout_img.active = true;
        hide && this.tipsActionHide();
    }
    private tipsActionHide(isAction = true) {
        let big_pic = cc.find("big_pic", this.layout_img);
        let small_pic = cc.find("small_pic", this.layout_img);
        let scaleX = small_pic.width / big_pic.width;
        let scaleY = small_pic.height / big_pic.height;
        let t = isAction ? 4 : 0;
        let btn = cc.find("btn_close", this.layout_img);
        btn.active = false;
        cc.tween(big_pic).delay(t).to(0.3, { scaleX: scaleX, scaleY: scaleY, x: small_pic.x, y: small_pic.y })
            .call(() => {
                this.layout_img.active = false;
            })
            .start();
    }
    private showBigPic() {
        let big_pic = cc.find("big_pic", this.layout_img);
        let small_pic = cc.find("small_pic", this.layout_img);
        let scaleX = small_pic.width / big_pic.width;
        let scaleY = small_pic.height / big_pic.height;
        big_pic.x = small_pic.x;
        big_pic.y = small_pic.y;
        small_pic.scaleX = scaleX;
        small_pic.scaleY = scaleY;
        this.layout_img.active = true;
        let btn = cc.find("btn_close", this.layout_img);
        cc.tween(big_pic).to(0.3, { scaleX: 1, scaleY: 1, x: 0, y: 0 })
            .call(() => {
                btn.active = true;
            })
            .start();
    }
    private onCloseTips() {
        this.tipsActionHide(false);
    }

    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);
        let record_count = cc.find("record_count", this.img_record).getComponent(cc.Sprite);
        record_count.fillRange = 0;
        cc.Tween.stopAllByTarget(record_count);
        let question = Game.getIns().getCurrentPage();
        cc.tween(record_count).to(question.duration, { fillRange: -1 })
            .call(() => {
                this.onTouchRecordEnd();
            }).start();
    }

    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 record_count = cc.find("record_count", this.img_record).getComponent(cc.Sprite);
        record_count.fillRange = 0;
        cc.Tween.stopAllByTarget(record_count);
        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.showRecordWord(data.text)
        if (data.text == Game.getIns().getCurrentPage().word) {
            this.playLocalAudio("right").then(() => {
                this.playLocalAudio("diaoluo");
            });
            pg.event.emit("box2d_next")
            pg.event.emit("mouse_10_add");
            Game.getIns().player.addRight();
        } else {
            this.playLocalAudio("error").then(() => {
                pg.event.emit("mouse_10_add_error");
            })
            Game.getIns().player.addError();
        }
    }




    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();
        courseware && courseware.startRecord(1); //开始录音
    }

    initListener() {

    }



    private checkRoundEnd() {
        Game.getIns().addPage();
        if (!Game.getIns().getCurrentPage()) {
            if (Game.getIns().player.right > 0) {
                pg.event.on("box2d_roll_successed", () => {
                    pg.event.emit("box2d_hide")
                    // 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, () => {
                        this.scheduleOnce(() => {
                            // zjz_ske.active = false;
                            this.showFind();
                        }, 1.5);
                    }, this);
                })
            } else {
                this.scheduleOnce(() => {
                    // zjz_ske.active = false;
                    this.showFind();
                }, 1.5);
            }

            pg.event.emit("box2d_roll")
        } else {
            this.playLocalAudio("next");
            this.showRecordWord("")
            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() {
        //生成橘子
        pg.event.emit('box2d_init', Game.getIns().getTotalPageNum());
        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(0.5, { x: -500 }).call(() => {
                    pg.audio.playAudioByUrl(Game.getIns().startAudio).then(() => {
                        cc.tween(start_ske).delay(1).by(0.5, { x: 500 }).call(() => {
                            this.layout_start.active = false;
                            this.showLaba(true);
                            this.showLayoutImg();
                        }).start();
                    });
                }).start();
            } else {
                this.layout_start.active = false;
                this.showLaba(true);
                this.showLayoutImg();
            }
        })
    }








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