import { asyncDelay, onHomeworkFinish } from "../script/util_hy17_hds";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent_hy17_hds";
import pg from "./pg_hy17_hds";

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();
        pg.event.once('npc_voice_play_voice_end', () => {
            this.initGame();
        })
        pg.event.emit('npc_layer_back_init', this.data)
    }

    private sentence_list: Array<{ time, content }>;
    private current: number


    private score;
    private scoreList;
    private tempCount;
    initData() {
        let data = this.data;
        this.sentence_list = data.questions.map(question => {
            return {
                time: question.time,
                content: question.text
            }
        })
        this.sentence_list.sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5);
        this.tempCount = 0;
        this.score = 0;
        this.scoreList = this.sentence_list.map(() => 3);
    }

    private layer_bg: cc.Node;
    private layer_game: cc.Node;
    private res: cc.Node;

    private sentence_box: cc.Node;
    private time_area: cc.Node;
    private time: cc.Node;

    private microphone_area: cc.Node;

    initView() {
        this.layer_bg = pg.view.find(this, "layer_bg")
        this.layer_game = pg.view.find(this, "layer_game")
        this.res = pg.view.find(this, "res")

        this.sentence_box = pg.view.find(this.layer_game, "sentence_box")
        this.microphone_area = pg.view.find(this.sentence_box, "microphone_area");
        this.time_area = pg.view.find(this.microphone_area, "time_area")
        this.time = pg.view.find(this.time_area, "time")
    }

    initListener() {
        pg.view.touchOn(this.microphone_area, this.onTouchRecordEnd, this);
        pg.event.on('layer_ending_touch_replay', () => {
            this.onTouchReplay();
        })
        pg.event.on('layer_ending_touch_next', () => {
            this.onTouchNext();
        })
    }
    initGame() {
        this.current = -1;
        this.sentence_list.sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5)
            .sort((A, B) => Math.random() - 0.5);
        this.initSentence();
    }
    get currentQuestion() {
        return this.sentence_list[this.current];
    }
    initSentence() {
        if (!this.sentence_box) return
        this.tempCount = 0;
        pg.view.visible(this.sentence_box, true)
        this.current++;
        if (!this.currentQuestion) {
            this.gameOver();
            return;
        }
        this.recordAudio = '';
        let sentence = pg.view.find(this.sentence_box, 'sentence');
        pg.view.setString(sentence, this.currentQuestion.content)
        this.sentence_box.y = -cc.winSize.height / 2 - this.sentence_box.height / 2;

        pg.hw.playLocalAudio('show')
        cc.tween(this.sentence_box).by(1, { y: this.sentence_box.height }).start();

        this.letter = this.currentQuestion.content;
        this.targetTime = this.currentQuestion.time;
        this.scheduleOnce(() => {
            this.onTouchRecord();
        }, 1)
    }

    update(dt) {
        this.updateCountdown(dt);
        this.showTimeUpdate();
    }
    updateCountdown(dt) {
        // pg.view.visible(this.time_area, true)
        // pg.view.setString(this.time, `${time}`)
        // time === 5 && this.microphoneAreaChange()

        // this.microphoneAreaRecover();
        // this.playBgAnimation()

        // this.stopBgAnimation()
        // this.coinShow()
    }

    onTouchReplay() {
        this.playBtnAudio()
        this.initGame()
    }

    onTouchNext() {

    }
    playBtnAudio() {
        let btn_audio = pg.view.find(this.res, "audio/btn")
        pg.audio.playLocalAudio(btn_audio)
    }

    //--------------------------------Record-----------------------------
    private letter: string;
    private targetTime: number;
    private recordAudio: string;
    private startTime: number;
    private recording: boolean;
    private microPhoneChange: boolean;

    showTimeStart() {
        if (!this.targetTime) return;
        let nowTime = new Date().getTime();
        this.startTime = nowTime;


    }
    showTimeUpdate() {
        if (!this.startTime) return;
        let nowTime = new Date().getTime();
        let subTime = this.targetTime - (nowTime - this.startTime) / 1000 + 1;
        if (subTime < 0) subTime = 0;

        pg.view.visible(this.time_area, true)
        pg.view.setString(this.time, `${Math.floor(subTime)}`)
        if (subTime <= 6) {
            this.microphoneAreaChange();
        }
        if (subTime == 0) {
            this.onTouchRecordEnd();
        }
    }
    showTimeEnd() {
        this.startTime = null;
    }
    showVoiceFlash() {
        let icon_recording = pg.view.find(this.microphone_area, 'icon_recording');
        pg.view.visible(icon_recording, true)
        cc.Tween.stopAllByTarget(icon_recording);
        cc.tween(icon_recording).to(0.5, { opacity: 0 }).to(0.3, { opacity: 255 }).union().repeatForever().start();
    }
    hideVoiceFlash() {
        let icon_recording = pg.view.find(this.microphone_area, 'icon_recording');
        pg.view.visible(icon_recording, false)
    }
    microphoneAreaChange() {
        if (this.microPhoneChange) return;
        this.microPhoneChange = true;
        pg.view.setColor(this.time, "#FFE298")
        cc.tween(this.microphone_area).to(0.25, { angle: 15 }).to(0.5, { angle: -15 }).to(0.25, { angle: 0 }).union().repeatForever().start();
    }
    microphoneAreaRecover() {
        cc.Tween.stopAllByTarget(this.microphone_area);
        pg.view.setColor(this.time, "#FFFFFF")
        this.microPhoneChange = false;
        this.microphone_area.angle = 0;
        this.time_area.active = false;
    }

    log(str) {
        const node = cc.find('middleLayer');
        if (node) {
            node.getComponent('middleLayer').log(str);
        } else {
            console.log(str);
        }
    }

    //按钮触发，使用的方法
    async onTouchRecord() {
        if (this.recording) return;
        if (this.recordAudio) return;
        this.recording = true;
        this.recordAudio = '';
        this.showTimeStart();
        this.showVoiceFlash();
        this.microphoneAreaRecover();

        this.log("-----------------------startTestConvert")
        cc.audioEngine.stopAllEffects();
        courseware && courseware.startTestConvert(this.letter); //开始录音
        // (<any>window).courseware.startTestConvert('My name is Lucy');
        // (<any>window).courseware.stopTestConvert(res => {
        //     // 录音评测返回结果, 与stopTest方法返回结果一致
        // }, covert => {
        //     // 变声返回结果，结构为 {convertUrl: ‘http://jliasldfjsdfi.mp3'}
        // });
    }
    async onTouchRecordEnd() {
        if (!this.recording) return;
        this.showTimeEnd();
        this.hideVoiceFlash();
        this.microphoneAreaRecover();
        let testData = {
            "dtLastResponse": "2021-09-17 13:36:26:109",
            "refText": "I haven't found anything out about him yet.",
            "recordId": "6144295213f0a2200000ed93",
            "eof": 1,
            audioUrl: 'http://staging-teach.cdn.ireadabc.com/43839adb578c7e01456748b8a176a0c3_l.mp3',
            "result": {
                "pronunciation": 25,
                "resource_version": "3.1.0",
                "fluency": 60,
                "rhythm": 90,
                "kernel_version": "5.2.4",
                "overall": 8,//75
                "integrity": 100,
                "duration": "6.779",
                "rear_tone": "fall",
                "speed": 96,
            },
            "tokenId": "6144295408558b08dd000001",
            "applicationId": "154838659000009e"
        }
        if (!courseware) {
            this.recordAudio = testData.audioUrl;
            return this.recrodEnd(testData)
        }
        this.log("---------------courseware.stopTestConvert:")
        courseware && courseware.stopTestConvert((res) => {
            this.log("---------------stopTestConvert:" + res)
            res = JSON.parse(res);
            this.tempRes = res
            this.recordCheck();
        }, covert => {
            this.log("----------------convertUrl:" + covert)
            covert = JSON.parse(covert);
            this.recordAudio = covert.convertUrl;
            this.recordCheck();
            // 变声返回结果，结构为 {convertUrl: ‘http://jliasldfjsdfi.mp3'}
        });//结束录音
    }
    private tempRes: any;
    recordCheck() {
        this.log("---------------recordCheck:" + this.recordAudio + "|" + this.tempRes)
        if (this.recordAudio && this.tempRes) {
            this.recrodEnd(this.tempRes);
        }
    }
    async recrodEnd(data?: any) {
        pg.hw.addRecord(data)
        this.hideVoiceFlash();
        let score = data.result.overall;
        pg.event.emit('layer_record_score', score);
        this.recording = false;
        this.startPlay(score);
    }
    startPlay(score) {
        //动画效果
        this.playBgAnimation();
        this.playVoice().then(() => {
            this.stopBgAnimation();
            this.playTips(score).then(() => {
                this.hideCoin();
            })
        });
    }
    hideCoin() {
        this.scheduleOnce(() => {
            pg.view.visible(this.time_area, false)
            this.initSentence();
        }, 0.5)
    }
    addScore(num) {
        if (num >= 3 && this.scoreList[this.current] >= 3) {
            this.score += 3;
            this.scoreList[this.current] -= 3;
        } else if (num >= 2 && this.scoreList[this.current] >= 2) {
            this.score += 2;
            this.scoreList[this.current] -= 2;
        } else if (num >= 1 && this.scoreList[this.current] >= 1) {
            this.score += 1;
            this.scoreList[this.current] -= 1;
        }
    }
    playTips(score) {
        return new Promise((resolve, reject) => {
            if (score < 10) {
                pg.event.once('layer_right_show_tryagain_end', () => {
                    this.tempCount += 1;
                    if (this.tempCount == 2) {
                        this.addScore(1);
                        pg.event.once('layer_coin_show_coin_end', () => {
                            resolve('');
                        })  // 动画回调
                        pg.event.emit('layer_coin_show_coin', 1)   //1 2 3硬币数量
                    } else {
                        this.recordAudio = '';
                        let sentence = pg.view.find(this.sentence_box, 'sentence');
                        pg.view.setString(sentence, this.currentQuestion.content)
                        this.sentence_box.y = -cc.winSize.height / 2 - this.sentence_box.height / 2;

                        pg.hw.playLocalAudio('show')
                        cc.tween(this.sentence_box).by(1, { y: this.sentence_box.height }).start();

                        this.letter = this.currentQuestion.content;
                        this.targetTime = this.currentQuestion.time;
                        this.scheduleOnce(() => {
                            this.onTouchRecord();
                        }, 1)
                        // if (this.recordFlag) {
                        //     pg.event.emit('layer_record_open', {
                        //         letter: this.CurrentData.content,
                        //         targetTime: this.CurrentData.duration
                        //     })
                        // }
                    }
                })
                pg.event.emit('layer_right_show_tryagain')
            } else if (score < 60) {
                pg.event.once('layer_right_show_good_end', () => {
                    this.addScore(2);
                    pg.event.once('layer_coin_show_coin_end', () => {
                        resolve('');
                    })  // 动画回调
                    pg.event.emit('layer_coin_show_coin', 1)   //1 2 3硬币数量
                })
                pg.event.emit('layer_right_show_good')
            } else {
                pg.event.once('layer_right_show_excellent_end', () => {
                    this.addScore(3);
                    pg.event.once('layer_coin_show_coin_end', () => {
                        resolve('');
                    })  // 动画回调
                    pg.event.emit('layer_coin_show_coin', 3)   //1 2 3硬币数量
                })
                pg.event.emit('layer_right_show_excellent')
            }
        });
    }
    playVoice() {
        return new Promise((resolve, reject) => {
            // setTimeout(() => {
            //     resolve('');
            // }, 3 * 1000);
            // return;
            // 播放三遍音效
            pg.audio.playAudioByUrlVolume(this.recordAudio, 0.8, () => {
                pg.audio.playAudioByUrlVolume(this.recordAudio, 0.5, () => {
                    pg.audio.playAudioByUrlVolume(this.recordAudio, 0.2, () => {
                        resolve('');
                    })
                })
            })
        });
    }

    playBgAnimation() {
        let bg_tween = pg.view.find(this.layer_bg, "tween");
        bg_tween.active = true;
        let bg_static = pg.view.find(this.layer_bg, "static");
        bg_static.active = false;
        let icon_mountain = pg.view.find(bg_tween, "icon_mountain");
        pg.view.visible(icon_mountain, true)
        cc.tween(icon_mountain).to(0.5, { opacity: 0 }).to(0.3, { opacity: 255 }).union().repeatForever().start();
    }

    stopBgAnimation() {
        let bg_tween = pg.view.find(this.layer_bg, "tween");
        bg_tween.active = false;
        let bg_static = pg.view.find(this.layer_bg, "static");
        bg_static.active = true;
        let icon_mountain = pg.view.find(bg_tween, "icon_mountain");
        cc.Tween.stopAllByTarget(icon_mountain);
        pg.view.visible(icon_mountain, false)
    }
    sendData() {
        return new Promise(res => {
            let upData: any = {
                word_count: this.data.word_count || 0,
                sentence_count: this.data.sentence_count || 0,
                zi_count: this.data.zi_count || 0,
                score: this.score || 0,
            };
            let recordList = pg.hw.getRecord();
            if (recordList && recordList.length > 0) {
                upData.recordList = recordList
            }
            console.log('upload->' + JSON.stringify(upData))
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.onHomeworkFinish(upData, () => {
                res('');
            })
        })
    }
    gameOver() {
        this.sendData().then(() => {
            pg.event.clear();
            pg.view.visible(this.sentence_box, false)
            // 下一页
            const middleLayer = cc.find('middleLayer').getComponent('middleLayer');
            middleLayer.saveGolds(this.score); // 保存金币数量；num 是获得金币的数量，数字类型；
            middleLayer.goNextPage();  // 跳转到下一页 
        })
    }
}





