import { asyncDelay, onHomeworkFinish } from "../script/util_hy08_caici";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy08_caici";
import pg from "./pg_hy08_caici";

const { ccclass, property } = cc._decorator;

let win: any = window;
let courseware = win.courseware;

enum State {
    Idle,
    Recording,
    RecordEnd,
    RecordShow,
    Over
}
@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() {

    }

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

    _cantouch = null;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        let data = this.data;
        this.data = this.data.questions[0]
    }
    private topQuestion: cc.Node
    //题目id
    private currentId: number
    //总时间时间
    private time: number
    //正确答题数
    private right: number
    //进度条成都
    private lengthProgress: number

    private layer_game: cc.Node;
    private layout_begin: cc.Node;
    initView() {
        // 取对象
        /*  this.topQuestion = pg.view.find(this, 'topQuestion'); */
        this.layer_game = pg.view.find(this, 'layer_game');
        this.layout_begin = pg.view.find(this.layer_game, 'layout_begin');
    }

    initListener() {
        //增加图片答案对象点击事件

    }

    async initGame() {
        this.showCamera();
        await this.showBegin()
        this.hideBegin();
        this.startQuestion();
    }

    showCamera() {
        courseware && courseware.openRecognitionCamera({
            x: 0,
            y: 0,
            width: 1,
            height: 1,
        })
    }
    //----------------------Ready Go------------------------------------
    showBegin() {
        return new Promise((resolve, reject) => {
            this.layout_begin.active = true;
            let bottom = pg.view.find(this.layout_begin, 'layout_bottom/bottom');
            let ready = pg.view.find(this.layout_begin, 'layout_middle/ready');
            let go = pg.view.find(this.layout_begin, 'layout_middle/go');
            // ready go
            ready.y = 2000;
            go.y = 2000;
            this.aniBottomEnter().then(() => {
                pg.hw.playAudio('readyGo', false, () => {
                });
                cc.tween(ready).to(1, { y: -20 }).to(0.2, { y: 0 }).delay(1).call(() => {
                    ready.active = false;
                }).start();
                cc.tween(go).delay(1).to(1, { y: -20 }).to(0.2, { y: 0 }).delay(0.5).call(() => {
                    go.active = false;
                    resolve('');
                }).start();
            })
        });
    }
    hideBegin() {
        this.layout_begin.active = false;
    }
    aniBottomEnter() {
        return new Promise((resolve, reject) => {
            let bottom = pg.view.find(this.layout_begin, 'layout_bottom/bottom');
            const bottomOrgPos = cc.v2(0, -736);
            bottom.active = true;
            bottom.y = bottomOrgPos.y - bottom.height;
            cc.tween(bottom).to(1, { y: bottomOrgPos.y }).start();
            pg.hw.playAudio('please5speak', false, () => {
                resolve('');
            });
        });
    }
    //----------------------Question------------------------------------
    private currentTime: number;
    startQuestion() {
        // 游戏所需的初始化数据
        this.currentId = 0
        this.time = this.data.options.length * 5
        this.currentTime = this.time * 1000;
        this.lengthProgress = 0
        this.right = 0
        //预加载第一题
        this.firstOptions()
        //题目数分配
        this.updateProgress()
    }
    //预加载第一题
    firstOptions() {
        let topQuestion = pg.view.find(this, 'layer_game/topQuestion');
        let countdown = pg.view.find(this, 'layer_game/countdown');
        let countdown1 = pg.view.find(countdown, 'countdown1');
        let countdown2 = pg.view.find(countdown, 'countdown2');
        countdown1.active = true
        countdown2.active = false
        this.startCountDown = true;
        this.state = State.Recording;
        this.updateTitleOptions();
    }
    gameOver() {
        this.state = State.Over;
    }
    private startCountDown: boolean;
    update(dt) {
        if (this.startCountDown) {
            var nowTime = Date.now();
            if (!this.lastTime) this.lastTime = nowTime;
            let subTime = nowTime - this.lastTime;
            this.currentTime -= subTime;
            this.lastTime = nowTime
            if (this.currentTime < 0) {
                this.currentTime = 0;
                // 游戏结束
            }
            this.updateClock(subTime);
            this.updateTime(subTime);

        }
    }
    private state: number;
    private waitTime: number;
    updateTime(dt) {
        this.waitTime -= dt;
        if (this.waitTime > 0) return;
        switch (this.state) {
            case State.Recording:
                this.state = State.RecordEnd;
                this.waitTime = 3 * 1000;//3秒录音
                this.startRecord(this.getCurrentOptions().text);
                break;
            case State.RecordEnd:
                this.state = State.RecordShow;
                this.waitTime = 2 * 1000;//1秒展示
                this.endRecord();
                break;
            case State.RecordShow:
                this.state = State.Recording;
                this.hideAnswer();
                this.currentId++;
                if (!this.getCurrentOptions()) {
                    this.gameOver();
                    return;
                }
                this.updateTitleOptions()
                break;
        }
    }

    getCurrentOptions() {
        return this.data.options[this.currentId];
    }
    hideAnswer() {
        let topQuestion = pg.view.find(this, 'layer_game/topQuestion');
        let row = pg.view.find(this, 'layer_game/row');
        let right = pg.view.find(row, 'right');
        let mistake = pg.view.find(row, 'mistake');
        let answer = pg.view.find(topQuestion, 'answer');
        right.active = false
        mistake.active = false
        answer.active = false
    }
    //题目
    updateTitleOptions() {
        let topQuestion = pg.view.find(this, 'layer_game/topQuestion');
        pg.view.setNetImg(topQuestion.children[1], this.getCurrentOptions().image, { w: 700, h: 360 })
        pg.view.setString(topQuestion.children[2], this.getCurrentOptions().text)
    }
    // 倒计时完成
    private lastTime: number;
    updateClock(dt) {
        let time = Math.floor(this.currentTime / 100);
        let n1 = Math.floor(time / 100) > 0 ? Math.floor(time / 100) : 0;
        time -= (n1 * 100);
        let n2 = Math.floor(time / 10) > 0 ? Math.floor(time / 10) : 0;
        time -= (n2 * 10);
        let n3 = Math.floor(time / 1) > 0 ? Math.floor(time / 1) : 0;
        let countStr = `${n1}${n2}.${n3}`;
        let countdown = pg.view.find(this, 'layer_game/countdown');
        let countdown1 = pg.view.find(countdown, 'countdown1');
        let countdown2 = pg.view.find(countdown, 'countdown2');
        //更换时间及闹钟图片
        countdown1.active = (Number(countStr) >= 10)
        countdown2.active = !(Number(countStr) >= 10)
        pg.view.setString(countdown1.children[0], countStr)
        pg.view.setString(countdown2.children[0], countStr)
    }

    //题目数分配
    updateProgress() {
        let ProgressBar = pg.view.find(this, 'layer_game/topProgressBar')
        var questionLenght = this.data.options.length
        //星星数
        for (let i = 1; i <= 3; i++) {
            ProgressBar.children[2].children[5 + i].active = true
            pg.view.setString(ProgressBar.children[2].children[5 + i], Math.round(questionLenght / 3 * i))
        }
        //题目少于三题星星数
        /* if (questionLenght >= 3) {
            for (let i = 1; i <= 3; i++) {
                ProgressBar.children[2].children[5 + i].active = true
                pg.view.setString(ProgressBar.children[2].children[5 + i], Math.round(questionLenght / 3 * i))
            }
        } else if (questionLenght == 2) {
            for (let i = 2; i <= 3; i++) {
                ProgressBar.children[2].children[5 + i].active = true
                pg.view.setString(ProgressBar.children[2].children[5 + i], Math.round(questionLenght / 2 * (-1)))
                ProgressBar.children[2].children[6].active = false
            }
        } else {
            ProgressBar.children[2].children[6].active = false
            ProgressBar.children[2].children[7].active = false
            pg.view.setString(ProgressBar.children[2].children[8], Math.round(questionLenght))
        } */
    }


    startRecord(letter) {
        courseware && courseware.startTest(letter); //开始录音
    }
    endRecord() {
        let testData = {
            "dtLastResponse": "2021-09-17 13:36:26:109",
            "refText": "I haven't found anything out about him yet.",
            "recordId": "6144295213f0a2200000ed93",
            "eof": 1,
            "result": {
                "pronunciation": 25,
                "resource_version": "3.1.0",
                "fluency": 60,
                "rhythm": 90,
                "kernel_version": "5.2.4",
                "overall": 74,//75
                "integrity": 100,
                "duration": "6.779",
                "rear_tone": "fall",
                "speed": 96,
            },
            "tokenId": "6144295408558b08dd000001",
            "applicationId": "154838659000009e"
        }
        if (!courseware) return this.recrodEnd(testData)
        courseware && courseware.stopTest((data) => {
            data = JSON.parse(data);
            this.recrodEnd(data);
        }); //结束录音
    }
    recrodEnd(data) {
        let score = data.result.overall;
        this.whetherAnswer(score > 40)
    }
    //用户回答结果
    whetherAnswer(answer) {
        let topQuestion = pg.view.find(this, 'layer_game/topQuestion');
        /* 
        * answer 获取的用户答案
        */
        //判断对错
        let row = pg.view.find(this, 'layer_game/row');
        topQuestion.children[2].active = true
        //正确
        if (answer) {
            //正确后执行函数
            this.rightQuestions(row)
        } else {
            //错误音频
            pg.audio.playAudioByUrl(this.getCurrentOptions().audio);
            //错误
            row.children[1].active = true
        }
    }
    //回答正确后回调
    rightQuestions(row) {
        //获取ProgressBar节点
        let ProgressBar = pg.view.find(this, 'layer_game/topProgressBar')
        var progressParent = ProgressBar.children[0].getComponent(cc.ProgressBar)
        //获取题目数量
        let lengthQ = this.data.options.length

        //答对题目数
        this.right += 1
        pg.view.setString(ProgressBar.children[1].children[0], this.right)

        //星星切换
        for (let i = 1; i <= 3; i++) {
            if (this.right == Math.round(lengthQ / 3 * i)) {
                ProgressBar.children[2].children[i - 1].active = false
                ProgressBar.children[2].children[i + 2].active = true
            }
            if (this.right == Math.round(lengthQ / 3 * 2)) ProgressBar.children[0].children[1].active = true
        }
        //进度条
        this.lengthProgress += 1 / (lengthQ)
        progressParent.progress = this.lengthProgress
        //彩色进度条同步进度条宽度
        ProgressBar.children[0].children[1].width = ProgressBar.children[0].children[0].width

        row.children[0].active = 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);
            });
        })
    }
}



