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

const { ccclass, property } = cc._decorator;

export function getDegree(p1, p2) {
    let vector = p2.sub(p1);
    let degree = Math.atan(vector.y / vector.x) / Math.PI * 180;
    if (vector.x >= 0) {
        if (vector.y < 0) {
            degree += 360;
        }
    } else {
        if (vector.y > 0) {
            degree += 180;
        } else {
            degree = 180 + degree;
        }
    }
    return -(-degree + 90);//角度计算方法
}
let win: any = window;
let courseware = win.courseware;
enum GUN_STATE {
    WAIT = 1,
    SHUT_MIDDLE,
    SHUT_LEFT,
    SHUT_RIGHT
}
enum FISH_STATE {
    NORMAL = 1,
    BREAK,
    FALL,
}
enum TIPS_STATE {
    GOOD = 1,
    TRY,
    COM,
}
@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

    addPreloadImage() {
        // TODO 根据自己的配置预加载图片资源
        this._imageResList.push(...this.data.questions.map(question => {
            return { url: question.image };
        }));
    }

    addPreloadAudio() {
        // TODO 根据自己的配置预加载音频资源
        this._audioResList.push({ url: this.data.questionTextAudio });
        this._audioResList.push({ url: this.data.bgAudio });
        this._audioResList.push(...this.data.questions.map(question => {
            return { url: question.audio };
        }));
    }

    addPreloadAnima() {

    }

    onLoadEnd() {
        // TODO 加载完成后的逻辑写在这里, 下面的代码仅供参考
        this.initData();
        this.initView();
        this.initEvent();
        this.startTime();
        this.updateTop();
    }
    protected onDestroy(): void {
        pg.event.clear();
    }

    @property(cc.Node)
    layout_game: cc.Node = null;
    @property(cc.Node)
    layout_tip: cc.Node = null;
    @property(cc.Node)
    btn_laba: cc.Node = null;
    @property(cc.Node)
    player_node: cc.Node = null;
    @property(cc.Node)
    star_node: cc.Node = null;
    @property(cc.Node)
    btn_record: cc.Node = null;
    @property(cc.Node)
    btn_recording: cc.Node = null;
    @property(cc.Node)
    label_time: cc.Node = null;
    @property(cc.Node)
    layout_final: cc.Node = null;

    private starData: Option;
    private tryData: Array<Option>;
    private countDown: number = 999999;
    private timeCount: number;
    private startCount = 15;
    private timeSecond;
    private assessCount;
    initData() {
        Game.getIns().init(this.data);
        Game.getIns().reset();
        this.tryData = [];
        this.starData = null;
        // 所有全局变量 默认都是null 
        this.starData = Game.getIns().getCardInfo();
        this.startSecond = false;
        this.timeSecond = 0;
        this.assessCount = 0;
    }
    private layout_start: cc.Node;
    private audioId: any;

    async initView() {
        this.player_node.x = -1500;
        cc.audioEngine.stopAllEffects();
        this.layout_start = pg.view.find(this, "layout_start");

        this.layout_start.active = true;

        if (Game.getIns().title) {
            cc.find("layout_info/label_title", this.node).getComponent(cc.Label).string = Game.getIns().title;
        }
    }

    initBg() {
        // 处理背景及自动的动画


    }



    initEvent() {
        this.btn_laba.on(cc.Node.EventType.TOUCH_END, this.playLaba, this);
        this.btn_record.on(cc.Node.EventType.TOUCH_END, this.onTouchRecord, this);
        this.btn_recording.on(cc.Node.EventType.TOUCH_END, this.onTouchRecordEnd, this);
        cc.find("btn_close", this.layout_final).on(cc.Node.EventType.TOUCH_END, this.onCloseFinal, this);
        cc.find("btn_restart", this.layout_final).on(cc.Node.EventType.TOUCH_END, this.onRestart, this);
        pg.event.on("game_start", () => {
            this.gameStart();
        });
        // pg.event.on("game_time_over", () => {
        //     // alert("game_time_over")
        //     //这里的事件会发送的很早。但是我们需要等待动画执行完了之后再开始后续的内容
        //     Game.getIns().addPage();
        //     if (!Game.getIns().isOver) return pg.event.emit("game_start");
        //     //发送给上端最后的数据
        //     // alert("game_finish")
        //     // int  total  
        //     // int  right
        //     // int[]  scores   
        //     // let player = { right: Game.getIns().player.score, error: Game.getIns().player.error }

        // })
    }
    private onRestart() {
        this.playLocalAudio("btn");
        this.initPendantPos();
        this.layout_final.active = false;
        this.label_time.getComponent(cc.Label).string = "00:00";
        this.onLoadEnd();
    }
    private onCloseFinal() {
        this.playLocalAudio("btn");
        this.layout_final.active = false;
    }
    private pendantMove() {
        let could = cc.find("bg/could", this.node);
        let seabed = cc.find("bg/seabed", this.node);
        cc.tween(seabed).by(1.5, { x: -150 }).start();
        cc.tween(could).by(1.5, { x: -150 }).start();
    }
    private playerEnter() {
        this.player_node.x = -1500;
        cc.tween(this.player_node).to(1.5, { x: -550 }).call(() => {
            this.showStar();
        }).start();
    }


    private intervalId;
    private playLaba() {
        let btn_kaba2 = this.btn_laba.getChildByName("btn_laba2");
        btn_kaba2.active = true;
        cc.audioEngine.stopAllEffects();
        let count = 0;
        if (this.intervalId) clearInterval(this.intervalId);
        let stop = false;
        this.intervalId = setInterval(() => {
            count++;
            btn_kaba2.active = count % 2 == 0;
            if (stop && count % 2 == 1) {
                clearInterval(this.intervalId);
                btn_kaba2.active = false;
            } else {

            }
        }, 150)

        pg.audio.playAudioByUrl(this.starData.audioUrl, (() => {
            stop = true;
        }))
    }

    private gameOver() {
        Game.getIns().state = GAME_STATE.OVER;
        let data: any = {};
        data.total = Game.getIns().total;
        data.right = Game.getIns().player.right;
        data.scores = Game.getIns().player.voices;
        data.stone = Math.floor(10 * data.right / data.total);
        this.log("total: " + data.total + "      right: " + data.right + "   stone: " + data.stone);
        onHomeworkFinish(data)
    }

    gameStart(isRight = true) {
        Game.getIns().state = GAME_STATE.RUNNING;
        this.startSecond = true;
        this.layout_start.active = false;
        if (isRight) {
            this.pendantMove();
            this.playerEnter();
        } else {
            this.showStar();
        }
        this.playLaba();
        this.btn_record.active = true;
        this.updateTop();
    }
    private showStar() {
        let word = cc.find("word", this.star_node);
        word.getComponent(cc.Label).string = this.starData.txt;
        this.star_node.on(cc.Node.EventType.TOUCH_END, () => {
            this.playLaba();
        })
    }

    //按钮触发，使用的方法
    private onTouchRecord() {
        this.btn_record.active = false;
        this.btn_recording.active = true;
        cc.audioEngine.stopAllEffects();
        this.countDown = this.startCount;
        this.countDown = this.starData.time || this.startCount; //this.startCount;
        let bg_record = cc.find("bg_record", this.btn_recording).getComponent(cc.Sprite);
        bg_record.fillRange = 0
        cc.tween(bg_record).to(this.countDown, { fillRange: -1 }).call(() => { bg_record.fillRange = 0; this.onTouchRecordEnd(); }).start();


        courseware && courseware.startTest(this.starData.txt); //开始录音
    }
    private onTouchRecordEnd() {
        let bg_record = cc.find("bg_record", this.btn_recording).getComponent(cc.Sprite);
        cc.Tween.stopAllByTarget(bg_record);
        this.btn_record.active = false;
        this.btn_recording.active = false;
        this.countDown = 999999;

        let testData = {
            "audioUrl": "https://staging-teach.cdn.ireadabc.com/a8ea7bb153a46941e6f28b7d0dda49f4.mp3",
            "eof": 1,
            "file": "/storage/emulated/0/Android/data/com.example.oxford/cache/shengtong/gradeVoice.mp3",
            "result": {
                "duration": "2.630",
                "fluency": 84,
                "integrity": 100,
                "kernel_version": "3.7.1",
                "overall": 80,
                "pronunciation": 88,
                "resource_version": "2.3.11",
                "rhythm": 46,
                "sentences": [
                    {
                        "beginIndex": 0,
                        "details": [
                            {
                                "charType": 0,
                                "end": 0,
                                "overall": 69,
                                "prominence": 0,
                                "start": 0,
                                "word": "day"
                            },
                            {
                                "charType": 0,
                                "end": 0,
                                "overall": 100,
                                "prominence": 0,
                                "start": 0,
                                "word": "day"
                            },
                            {
                                "charType": 0,
                                "end": 0,
                                "overall": 100,
                                "prominence": 0,
                                "start": 0,
                                "word": "up"
                            },
                            {
                                "charType": 0,
                                "end": 0,
                                "overall": 100,
                                "prominence": 0,
                                "start": 0,
                                "word": "day"
                            },
                            {
                                "charType": 0,
                                "end": 0,
                                "overall": 100,
                                "prominence": 0,
                                "start": 0,
                                "word": "up"
                            }
                        ],
                        "end": 0,
                        "endIndex": 0,
                        "overall": 88,
                        "sentence": "day day up day up",
                        "start": 0
                    }
                ],
                "speed": 170
            },
            "tokenId": "632be7a73327935c2b000005"
        }
        if (!courseware) return this.recrodEnd(testData)
        // await pg.time.delay(5);
        courseware && courseware.stopTest((data) => {
            data = JSON.parse(data);
            this.recrodEnd(data);
        }); //结束录音
    }
    private tryAgain: boolean = false;
    private touching: boolean = false;
    private async recrodEnd(data) {
        this.assessCount++;
        this.log("recrodEnd!!!!!")
        Game.getIns().player.addVoice(data);
        let score = data.result.overall;
        this.log("score: " + score);
        let isSuccess = this.checkWords(data);
        this.log("data: " + JSON.stringify(data));
        if (score >= 60 && isSuccess) {
            this.touching = false;
            this.player_node.getComponent(dragonBones.ArmatureDisplay).playAnimation("right", 0);
            this.playerAni("right");
            //提示成功
            this.updateTips(TIPS_STATE.GOOD);
            Game.getIns().player.addRight();
            await pg.time.delay(2);
            this.updateTips(null);
            this.tryAgain = false;
            this.playerLevel();
            return;
        } else {
            this.starData.count++;
            this.playerAni("wrong");
            this.updateTips(TIPS_STATE.TRY);
            //提示失败
            if (this.starData.count >= 3) {
                if (this.tryAgain) {
                    this.tryAgain = false;
                    await pg.time.delay(2);
                    this.updateTips(null);
                    this.touching = false;
                    this.nextstar(false);
                    return;
                }
            } else {
                if (!this.tryData.some(td => td.id == this.starData.id)) this.tryData.push(this.starData);
                this.tryAgain = true;
            }
        }
        await pg.time.delay(2);
        this.updateTips(null);
        this.playerAni();
        if (this.tryAgain) {
            this.updateLayoutSpeak();
        } else {
            this.updateLayoutSpeak(true);
            this.touching = false;
        }
    }
    private playerAni(aniName = "normal") {
        this.player_node.getComponent(dragonBones.ArmatureDisplay).playAnimation(aniName, 0);
    }

    private updateLayoutSpeak(hide?: boolean) {
        this.btn_record.active = true;
        this.btn_recording.active = false;
    }

    private updateTips(state?: TIPS_STATE) {
        if (!state) {
            this.layout_tip.active = false;
            return;
        }
        this.layout_tip.active = true;
        let img_co = pg.view.find(this.layout_tip, 'img_co');
        let img_gj = pg.view.find(this.layout_tip, 'img_gj');
        let img_ta = pg.view.find(this.layout_tip, 'img_ta');
        img_co.active = false;
        img_gj.active = false;
        img_ta.active = false;
        let img = null;
        switch (state) {
            case TIPS_STATE.COM:
                img = img_co;
                // this.playLocalAudio("co");
                break;
            case TIPS_STATE.GOOD:
                img = img_gj;
                this.playLocalAudio("excellent");

                break;
            case TIPS_STATE.TRY:
                img = img_ta;
                this.playLocalAudio("tryagain");
                break;
        }
        img.scale = 1;
        img.active = true;
        // cc.tween(img).to(0.5, { scale: 1 }).delay(2).call(() => {
        //     this.layout_tip.active = false;
        // }).start();
    }

    private playerLevel() {
        this.playLocalAudio("jiasu");
        let word = cc.find("word", this.star_node);
        word.getComponent(cc.Label).string = "";
        let star = cc.instantiate(this.star_node);
        this.star_node.active = false;
        star.parent = this.layout_game;
        let dis = star.x - this.player_node.x;
        dis += star.x;
        let width = this.player_node.width / 2;
        cc.tween(this.player_node).to(1.5, { x: star.x - width }).call(() => {
            cc.tween(star).to(2, { x: dis + width }).call(() => { star.parent = null; star.destroy(); }).start();
        }).to(2, { x: dis }).call(() => { this.nextstar(true) }).start();

    }

    private nextstar(isRight = true) {
        this.playerAni();
        this.starData = Game.getIns().getCardInfo();
        if (this.starData) {
            this.initPendantPos();
            this.star_node.active = true;
            this.gameStart(isRight)
        } else {
            this.startSecond = false;
            this.gameOver();
            this.showFind();
        }
    }
    private initPendantPos() {
        let could = cc.find("bg/could", this.node);
        let seabed = cc.find("bg/seabed", this.node);
        could.x = 0;
        seabed.x = 0;
    }

    private checkWords(data) {
        const sentences = data.result.sentences;
        for (let i = 0; i < sentences.length; i++) {
            const details = sentences[i].details;
            const isSuccess = details.some(item => item.overall <= 40);
            if (isSuccess) {
                return false;
            }
        }
        return true;
    }





    private updateTop() {
        let round = cc.find("layout_info/bg_number/round", this.node);
        round.getComponent(cc.Label).string = `${this.starData.id}/${Game.getIns().total}`;
    }
    private startSecond: boolean;

    update(dt) {
        if (Game.getIns().state != GAME_STATE.RUNNING) return;
        if (!this.startSecond) return;
        this.timeSecond = this.timeSecond + dt;
        let count = Math.ceil(this.timeSecond);
        let str = this.formatSeconds(count);
        this.label_time.getComponent(cc.Label).string = str;
    }
    private formatSeconds(value) {
        var secondTime = parseInt(value);// 秒
        var minuteTime = 0;// 分
        var hourTime = 0;// 小时
        if (secondTime > 59) {//如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = Math.floor(secondTime / 60);
            //获取秒数，秒数取佘，得到整数秒数
            secondTime = Math.floor(secondTime % 60);
            //如果分钟大于60，将分钟转换成小时
            // if (minuteTime > 60) {
            //     //获取小时，获取分钟除以60，得到整数小时
            //     hourTime = minuteTime / 60;
            //     //获取小时后取佘的分，获取分钟除以60取佘的分
            //     minuteTime = minuteTime % 60;
            // }
        }
        var result = (secondTime < 10 ? "0" + secondTime : secondTime) + "";

        if (minuteTime > 0) {
            result = "" + (minuteTime < 10 ? "0" + minuteTime : minuteTime) + ":" + result;
        } else {
            result = "00:" + result
        }
        // if (hourTime > 0) {
        //     result = "" + hourTime + "小时" + result;
        // }
        return result;
    }


    private async startTime() {
        for (let i = 3; i >= 0; i--) {
            let target = cc.find("layout_start/text_" + i, this.node);
            if (i == 0) this.playLocalAudio("go")
            else this.playLocalAudio("count")
            await this.startTextAction(target);
        }
        this.gameStart();
    }
    private startTextAction(target) {
        return new Promise((resolve, reject) => {
            target.scale = 1;
            target.active = true;
            target.opacity = 255;
            cc.tween(target).to(1, { scale: 0.5, opacity: 0 }).call(() => { target.active = false; return resolve("") }).start();
        })
    }
    private showFind() {
        this.playerAni("complete");
        this.layout_final.scale = 0.3;
        this.layout_final.active = true;
        let count = cc.find("count", this.layout_final);
        let time = cc.find("time", this.layout_final);
        time.getComponent(cc.Label).string = this.formatSeconds(this.timeSecond);
        count.getComponent(cc.Label).string = "" + this.assessCount;
        cc.tween(this.layout_final).to(0.3, { scale: 1 }).start();
    }







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



    async showOneFirework(pos, parentNode, nodeList) {

        for (let i = 0; i < 3; i++) {
            this.showFirework(pos, parentNode, nodeList, 200, 200, 25);
            await asyncDelay(0.1);
        }
    }

    showFirework(pos, parentNode, nodeList, width = 200, height = 500, number = 30) {
        for (let i = 0; i < number; i++) {
            const quad = this.createQuads(pos, parentNode, nodeList);
            const targetX = RandomInt(width / 2, -width / 2);
            const targetY = RandomInt(height);

            cc.tween(quad)
                .by(0.5, { x: targetX })
                .by(3, { x: targetX * 2 })
                .start();

            cc.tween(quad)
                .by(0.5, { y: targetY }, { easing: 'quadOut' })
                .to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
                .removeSelf()
                .start();

            cc.tween(quad)
                .delay(1)
                .to(0.5 + 1 * Math.random(), { opacity: 0 })
                .start();
        }
    }

    createQuads(pos, parentNode, nodeList) {
        const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
        // console.log('nodeList', nodeList);
        // console.log('quadBase', quadBase);
        quadBase.x = pos.x;
        quadBase.y = pos.y + 30;
        quadBase.z = pos.z;
        quadBase.angle = RandomInt(180);
        quadBase.parent = parentNode;

        const quad = quadBase.getChildByName('quad');
        quad.x = 0;
        quad.y = 0;
        quad.angle = RandomInt(180);

        const paper = quad.getChildByName('paper');
        paper.scaleX = Math.random() * 0.8 + 0.2;
        paper.scaleY = Math.random() * 0.8 + 0.2;

        quadBase.scaleX = Math.random();
        cc.tween(quadBase)
            .to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
            .call(() => {
                const time = Math.random() * 0.2;
                cc.tween(quadBase)
                    .to(0.1 + time, { scaleX: -1 })
                    .to(0.1 + time, { scaleX: 1 })
                    .union()
                    .repeatForever()
                    .start();
            })
            .start();


        return quadBase;
    }
}


