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.initSysteam();
        this.initData();
        this.initView();
        this.initListener();
        this.initGame();
        pg.event.on('npc_voice_play_voice_end', () => {
            // this.startGame();
        })
        pg.event.emit('npc_layer_back_init', this.data)
    }
    initSysteam() {
        console.log("调用竖版")
        if (cc.sys.isNative && cc.sys.os == cc.sys.OS_IOS) {
            courseware && courseware.onConfigurationPortrait()
        } else {
            courseware && courseware.onConfigurationPortrait()
        }
    }
    protected onDestroy(): void {
        pg.event.clear();
        courseware.onConfigurationLandscape()
    }

    _cantouch = null;
    //题目id
    private currentId: number
    //总时间时间
    private time: number
    //正确答题数
    private right: number
    //进度条成都
    private lengthProgress: number
    // 游戏页面
    private layer_game: cc.Node;
    // 准备开始
    private layout_begin: cc.Node;
    private layout_question: cc.Node;
    initData() {
        // 所有全局变量 默认都是null 
        this._cantouch = true;
        let data = this.data;
        this.data = this.data.questions[0]
    }
    initView() {
        // 取对象
        this.layer_game = pg.view.find(this, 'layer_game');
        this.layout_begin = pg.view.find(this.layer_game, 'layout_begin');
        this.layout_question = pg.view.find(this.layer_game, 'layout_question');
        pg.view.visible(pg.view.find(this.layer_game, 'countdown/countdown1'), true);
        pg.view.visible(pg.view.find(this.layer_game, 'countdown/countdown2'), false);
        let item_question = pg.view.find(this, 'layer_game/item_question');
        pg.view.visible(item_question, false);
    }

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

    }

    getCurrent() {
        return this.data.options[this.currentId];
    }
    getNext() {
        return this.data.options[this.currentId + 1];
    }
    async initGame() {
        this.showCamera();
        await this.showBegin()
        this.hideBegin();
        this.startQuestion();
    }

    gameOver() {
        this.state = State.Over;
        this.showAni().then(coin => {
            pg.event.once('layer_coin_show_coin_end', () => {
                pg.event.emit('layer_ending_show')
            })  // 动画回调
            pg.event.emit('layer_coin_show_coin', coin)   //1 2 3硬币数量
        })
    }
    showAni() {
        return new Promise((resolve, reject) => {
            let percent = this.right / this.data.options.length;
            if (percent < 0.3) {
                pg.event.once('layer_right_show_tryagain_end', () => {
                    resolve(1);
                })
                pg.event.emit('layer_right_show_tryagain')
            } else if (percent < 0.6) {
                pg.event.once('layer_right_show_good_end', () => {
                    resolve(2);
                })
                pg.event.emit('layer_right_show_good')
            } else {
                pg.event.once('layer_right_show_excellent_end', () => {
                    resolve(3);
                })
                pg.event.emit('layer_right_show_excellent')
            }
        });

    }
    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: -50 }).to(0.2, { y: 0 }).delay(0.3).call(() => {
                    ready.active = false;
                }).start();
                cc.tween(go).delay(1.3).to(1, { y: -50 }).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;
    private currentItemQuestion: cc.Node;
    private nextItemQuestion: cc.Node;
    startQuestion() {
        // 游戏所需的初始化数据
        this.currentId = 0
        this.time = this.data.options.length * 5
        this.currentTime = this.time * 1000;
        this.lengthProgress = 0
        this.right = 0
        this.gameStart = true;
        this.state = State.Recording;
        this.currentItemQuestion = this.createQuestionItem(cc.v2(0, 50));
        this.updateQuestion(this.currentItemQuestion, this.getCurrent());
        this.updateProgress();
    }

    createQuestionItem(pos) {
        let item_question = pg.view.find(this, 'layer_game/item_question');
        let clone_question = pg.view.clone(item_question);
        clone_question.active = true;
        clone_question.x = pos.x;
        clone_question.y = pos.y;
        this.layout_question.addChild(clone_question);
        return clone_question;
    }


    //题目
    updateQuestion(item, data) {
        pg.view.setNetImg(pg.view.find(item, "img"), data.image, { w: 700, h: 360 })
        pg.view.setString(pg.view.find(item, "text"), data.text)
    }
    nextQuestion() {
        this.currentId++;
        if (!this.getCurrent()) {
            this.gameOver();
            return;
        }
        this.hideAnswer();
        this.nextItemQuestion = this.createQuestionItem(cc.v2(2000, 50));
        this.updateQuestion(this.nextItemQuestion, this.getCurrent());
        pg.hw.playLocalAudio('showCard')
        cc.tween(this.currentItemQuestion).to(0.5, { x: -2000, y: 50 }).start();
        cc.tween(this.nextItemQuestion).to(0.5, { x: 0, y: 50 }).call(() => {
            this.currentItemQuestion.parent = null;
            this.currentItemQuestion = this.nextItemQuestion;
            this.nextItemQuestion = null;
        }).start();
    }
    //------------------------------Loop----------------------------------
    private gameStart: boolean;
    private state: number;
    private waitTime: number;
    update(dt) {
        if (this.gameStart) {
            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.updateState(subTime);
        }
    }
    updateState(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.getCurrent().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.nextQuestion()
                break;
        }
    }
    //------------------------------Answer----------------------------------

    //用户回答结果
    checkRight(score) {
        let isRight = score > 40;
        /* 
        * answer 获取的用户答案
        */
        //判断对错
        let currentItemQuestion = this.currentItemQuestion;
        let row = pg.view.find(currentItemQuestion, 'row');
        currentItemQuestion.children[2].active = true
        //正确
        if (isRight) {
            //正确后执行函数
            this.onAnswerRight(row)
        } else {
            this.onAnswerError(row)
        }
    }
    //回答正确后回调
    onAnswerRight(row) {
        //答对题目数
        pg.hw.playLocalAudio('right');
        this.right += 1
        row.children[0].active = true
        this.updateProgressPercent();
    }
    onAnswerError(row) {
        pg.hw.playLocalAudio('mistake');
        //错误音频
        pg.audio.playAudioByUrl(this.getCurrent().audio);
        //错误
        row.children[1].active = true
    }

    hideAnswer() {
        console.log("节点移出画面")
        let currentItemQuestion = this.currentItemQuestion;
        let row = pg.view.find(currentItemQuestion, 'row');
        let right = pg.view.find(row, 'right');
        let mistake = pg.view.find(row, 'mistake');
        right.active = false
        mistake.active = false
    }

    //------------------------------Record----------------------------------
    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.checkRight(score)
    }

    //------------------------------Progress----------------------------------

    // 倒计时完成
    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)
    }


    updateProgressPercent() {
        //获取layout_progress节点
        let layout_progress = pg.view.find(this, 'layer_game/layout_progress')
        var progressParent = layout_progress.children[0].getComponent(cc.ProgressBar)
        pg.view.setString(layout_progress.children[1].children[0], this.right)

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

    }


    //题目数分配
    updateProgress() {
        let layout_progress = pg.view.find(this, 'layer_game/layout_progress')
        var questionLenght = this.data.options.length
        //星星数
        for (let i = 1; i <= 3; i++) {
            layout_progress.children[2].children[5 + i].active = true
            pg.view.setString(layout_progress.children[2].children[5 + i], Math.round(questionLenght / 3 * i))
        }
    }

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




