import { asyncDelay, onHomeworkFinish } from "../script/util_hy06_danxuan";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy06_danxuan";
import pg from "./pg_hy06_danxuan";

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() {

    }

    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 startTime: number
    //倒计时时间
    private countdownTime: string
    //正确答题数
    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() {
        await this.showBegin()
        this.hideBegin();
        this.nextQuestion();
    }

    showCamera() {
        // cw.openRecognitionCamera({
        //     x: 0,
        //     y: 0,
        //     width: 1,
        //     height: 1,
        // })
    }
    startRecord() {
        courseware && courseware.startTest(''); //开始录音
    }
    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": 25,//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;

    }
    //----------------------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------------------------------------
    nextQuestion() {
        // 游戏所需的初始化数据
        this.currentId = 0
        this.time = this.data.options.length * 5
        console.log(this.time, '456')
        this.startTime = this.time * 1000 + Date.now()
        this.countdownTime = "60.00"
        this.lengthProgress = 0
        this.right = 0
        //预加载第一题
        this.firstOptions()
        //题目数分配
        this.questionNuber()
    }
    //预加载第一题
    firstOptions() {
        var options = this.data.options

        let topQuestion = pg.view.find(this, 'layer_game/topQuestion');

        pg.view.setNetImg(topQuestion.children[1], options[this.currentId].image, { w: 700, h: 360 })
        pg.view.setString(topQuestion.children[2], options[this.currentId].text)

        //倒计时
        this.countdownQuestion(topQuestion)
    }
    //倒计时
    countdownQuestion(topQuestion) {
        let countdown = pg.view.find(this, 'layer_game/countdown');
        var chil = countdown.children
        var b = this.time - 5
        chil[0].active = true
        chil[1].active = false
        var timer = setInterval(() => {
            var currentTime = Date.now();
            var timePassed = this.startTime - currentTime;
            this.countdownTime = String(timePassed / 1000)
            //更换时间及闹钟图片
            if (Number(this.countdownTime) >= 10) {
                chil[0].active = true
                pg.view.setString(chil[0].children[0], this.countdownTime)
            } else {
                chil[0].active = false
                chil[1].active = true
                pg.view.setString(chil[1].children[0], this.countdownTime)
            }
            //每隔五秒
            if (Number(this.countdownTime) - b <= 0) {
                console.log(Number(this.countdownTime) - b)

                //等待用户回答问题
                this.whetherQuestions(topQuestion)
                b -= 5
                //下一题
                setTimeout(() => {
                    this.titleOptions(topQuestion)
                    //动画时间
                    this.startTime += 1000
                }, 700);
            }
            //倒计时结束
            if (Number(this.countdownTime) <= 0) {
                clearInterval(timer)
                this.countdownTime = "00.000"
                pg.view.setString(chil[1].children[0], this.countdownTime)
            }
        }, 100);
    }
    //题目
    titleOptions(topQuestion) {
        var options = this.data.options
        pg.view.setNetImg(topQuestion.children[1], options[this.currentId].image, { w: 700, h: 360 })
        pg.view.setString(topQuestion.children[2], options[this.currentId].text)
    }
    //题目数分配
    questionNuber() {
        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))
        } */
    }
    //用户回答问题
    whetherQuestions(topQuestion) {
        var answer = this.currentId > 0
        this.whetherAnswer(topQuestion, answer)
    }
    //用户回答结果
    whetherAnswer(topQuestion, answer) {
        /* 
        * answer 获取的用户答案
        */
        //判断对错
        let row = pg.view.find(this, 'layer_game/row');
        topQuestion.children[2].active = true
        //正确
        if (answer) {
            //正确后执行函数
            this.rightQuestions(row)
        } else {
            //错误音频
            pg.audio.playAudioByUrl("http://staging-teach.cdn.ireadabc.com/cb76dbc838567b58e2af36e2d2faa923_l.mp3")
            //错误
            row.children[1].active = true
        }
        //添加动画
        this.addAnimation(row, topQuestion)
    }
    //回答正确后回调
    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
    }
    addAnimation(row, topQuestion) {
        if (this.currentId < (this.time / 5) - 1) {
            //初始化
            setTimeout(() => {
                row.children[0].active = false
                row.children[1].active = false
                topQuestion.children[2].active = false
                this.currentId++
            }, 700);
        } else {
            console.log('回答完毕')
        }
    }
    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);
            });
        })
    }
}


