// pg.event.emit('layer_record_open', {
//     letter: 'test',
//     targetTime: 10
// })

import pg from "../../scene/pg_hy01_danci";


const { ccclass, property } = cc._decorator;

let win: any = window;
let courseware = win.courseware;
@ccclass
export default class LayerRecord extends cc.Component {
    private layout_record: cc.Node;
    onLoad() {
        this.layout_record = pg.view.find(this, 'layout_record')
        let AniNode = pg.view.find(this.layout_record, 'AniNode');
        AniNode.active = false;
        let btn_play = pg.view.find(this.layout_record, 'btn_play');
        btn_play.active = false;
        this.initEvent();
        this.showVoiceWhite();
    }
    private letter: string;
    private targetTime: number;
    private recordAudio: string;
    initEvent() {
        pg.event.on('layer_record_open', (data) => {
            this.layout_record.active = true;
            this.letter = data.letter
            this.targetTime = data.targetTime
        })
        let btn_record = pg.view.find(this.layout_record, 'btn_record');
        let btn_play = pg.view.find(this.layout_record, 'btn_play');
        btn_record.on(cc.Node.EventType.TOUCH_START, this.onTouchRecord, this);
        btn_record.on(cc.Node.EventType.TOUCH_END, this.onTouchRecordEnd, this);
        btn_play.on(cc.Node.EventType.TOUCH_END, this.onTouchPlayRecord, this);
    }

    showVoiceWhite() {
        let voice_white = pg.view.find(this.layout_record, 'voice_white');
        cc.tween(voice_white).set({ scale: 1, opacity: 255 }).to(1, { scale: 1.5, opacity: 0 }).delay(0.5).union().repeatForever().start();
    }
    private startTime: number;
    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 = (nowTime - this.startTime) / 1000;
        let percent = 1 - (subTime / this.targetTime);
        percent = Math.max(percent, 0)
        let record_time = pg.view.find(this.layout_record, 'record_time');
        record_time.getComponent(cc.Sprite).fillRange = percent;
        if (percent == 0) {
            this.showTimeEnd();
        }
    }
    showTimeEnd() {
        this.startTime = null;
        let record_time = pg.view.find(this.layout_record, 'record_time');
        record_time.getComponent(cc.Sprite).fillRange = 0;
    }
    showPlay() {
        let btn_play = pg.view.find(this.layout_record, 'btn_play')
        btn_play.active = !!this.recordAudio
        let p0 = pg.view.find(btn_play, 'p0')
        let p1 = pg.view.find(btn_play, 'p1')
        let p2 = pg.view.find(btn_play, 'p2')
        let p3 = pg.view.find(btn_play, 'p3')
        p0.active = true;
        p1.active = false;
        p2.active = false;
        p3.active = false;
    }
    private recordAudioId;
    onTouchPlayRecord() {
        if (!this.recordAudio) return;
        if (this.playVoiceCount && this.playVoiceCount > -1) {
            if (this.recordAudioId) {
                cc.audioEngine.stopEffect(this.recordAudioId)
            }
            this.playVoiceEnd();
        } else {
            this.playVoiceStart();
            pg.audio.playAudioByUrl(this.recordAudio, () => {
                this.recordAudioId = null;
                this.playVoiceEnd();
            }, (audioId) => {
                this.recordAudioId = audioId;
            });
        }
    }

    private playVoiceCount: number;
    playVoiceStart() {
        if (this.playVoiceCount > 0) return;
        this.playVoiceCount = 0;
        this.schedule(this.playVoiceRunning, 0.3)
    }
    playVoiceRunning() {
        this.playVoiceCount++;
        let btn_play = pg.view.find(this.layout_record, 'btn_play');
        let p0 = btn_play.getChildByName('p0')
        let p1 = btn_play.getChildByName('p1')
        let p2 = btn_play.getChildByName('p2')
        let p3 = btn_play.getChildByName('p3')
        p0.active = false;
        p1.active = this.playVoiceCount % 3 == 0;
        p2.active = this.playVoiceCount % 3 == 1;
        p3.active = this.playVoiceCount % 3 == 2;
    }
    playVoiceEnd() {
        let btn_play = pg.view.find(this.layout_record, 'btn_play');
        this.unschedule(this.playVoiceRunning)
        this.playVoiceCount = 0;
        let p0 = btn_play.getChildByName('p0')
        let p1 = btn_play.getChildByName('p1')
        let p2 = btn_play.getChildByName('p2')
        let p3 = btn_play.getChildByName('p3')
        p0.active = true;
        p1.active = false;
        p2.active = false;
        p3.active = false;
    }


    protected update(dt: number): void {
        this.showTimeUpdate();
    }
    //按钮触发，使用的方法
    async onTouchRecord() {
        this.recordAudio = '';
        this.showPlay();
        let AniNode = pg.view.find(this.layout_record, 'AniNode');
        AniNode.active = true;
        this.showTimeStart();

        cc.audioEngine.stopAllEffects();
        courseware && courseware.startTest(this.letter); //开始录音
    }
    async onTouchRecordEnd() {
        let AniNode = pg.view.find(this.layout_record, 'AniNode');
        AniNode.active = false;
        this.showTimeEnd();
        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) {
            return this.recrodEnd(testData)
        }
        courseware && courseware.stopTest((res) => {
            res = JSON.parse(res);
            this.recrodEnd(res);
        }); //结束录音
    }
    async recrodEnd(data) {
        this.recordAudio = data.audioUrl;
        this.showPlay();
        let score = data.result.overall;
        this.layout_record.active = false;
        pg.event.emit('layer_record_score', score);
    }
}

