/*
 * @Author: ls
 * @Date: 2022-05-15 18:22:18
 * @LastEditTime: 2022-06-13 13:02:23
 * @LastEditors: ls
 * @Description:
 * @FilePath: \ls_gramophone\assets\ls_gramophone\scene\ls_gramophone.ts
 */

import Item from '../script/Item';
import { MyCocosSceneComponent } from '../script/MyCocosSceneComponent';
import { onHomeworkFinish } from '../script/util';

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {
	@property(cc.Node)
	item: cc.Node = null;

	@property(cc.Node)
	content: cc.Node = null;

	@property(cc.Node)
	tip: cc.Node = null;

	// 录音中
	_recording = false;
	// 录音音频
	_records = [];
	// 倒计时
	_countdown = 30;

	// 当前
	_curIndex = -1;

	addPreloadImage() {
		// TODO 根据自己的配置预加载图片资源
		this._imageResList.push({ url: this.data.pageImage });
	}

	addPreloadAudio() {
		// TODO 根据自己的配置预加载音频资源
		this._audioResList.push({ url: this.data.questionTextAudio });
		this._audioResList.push({ url: this.data.pageAudio });

		for (let index = 0; index < this.data.sentences.length; index++) {
			this._audioResList.push({ url: this.data.sentences[index].audio });
		}
	}

	addPreloadAnima() {}

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

	initData() {
		this._recording = false;

		this._records.length = 0;
		this.data.sentences.forEach((element) => {
			this._records.push(null);
		});
	}

	initView() {
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;

		cc.find('Canvas/bg_title/label').getComponent(cc.Label).string = this.data.title;

		this.getSpriteFrimeByUrl(this.data.pageImage + '?x-oss-process=image/resize,m_fill,h_520,w_560', (sp) => {
			// this.getSpriteFrimeByUrl(this.data.pageImage, (sp) => {
			cc.find('Canvas/bg_img/img').getComponent(cc.Sprite).spriteFrame = sp;

			cc.find('Canvas/bg_img/img').scale = Math.max(520 / cc.find('Canvas/bg_img/img').width, 560 / cc.find('Canvas/bg_img/img').height);
		});

		let play = cc.find('Canvas/btn_play');
		let stop = cc.find('Canvas/btn_stop');
		play.active = false;
		stop.active = true;
		play.off('click');
		stop.off('click');
		play.on('click', () => {
			cc.audioEngine.stopAll();

			play.active = false;
			stop.active = true;
		});
		stop.on('click', () => {
			this.resetText();
			this.resetRecord();
			cc.audioEngine.stopAll();

			play.active = true;
			stop.active = false;

			this.playAudioByUrl(this.data.pageAudio, () => {
				play.active = false;
				stop.active = true;
			});
		});

		for (let index = 0; index < this.data.sentences.length; index++) {
			let item = cc.instantiate(this.item);
			item.active = true;
			item.name = '' + index;
			item.parent = this.content;
		}

		for (let index = 0; index < this.content.childrenCount; index++) {
			const element = this.content.children[index];
			element.getComponent(Item).init(this.data.sentences[index].text);

			// 播放当前句子
			element.off('click');
			element.on('click', () => {
				this.resetText();
				this.resetRecord();
				cc.audioEngine.stopAll();
				play.active = false;
				stop.active = true;

				element.getComponent(Item).playing();
				this.playAudioByUrl(this.data.sentences[index].audio, () => {
					element.getComponent(Item).stop();
				});
			});

			element.getComponent(Item).recorded();

			let record = cc.find('btn_record', element);
			record.off('click');
			record.on('click', () => {
				if (this._recording) return;

				this.resetText();
				this.resetRecord();
				cc.audioEngine.stopAll();
				play.active = false;
				stop.active = true;

				this.playLocalAudio('btn');
				element.getComponent(Item).recording();

				// 显示录音界面
				mask.active = true;
				record_start.active = true;
				record_stop.active = false;

				this._curIndex = index;
			});

			element.getComponent(Item).hideRecord();

			let myrecord = cc.find('btn_myrecord', element);
			let myrecord_play = cc.find('btn_myrecord_play', element);
			myrecord.off('click');
			myrecord_play.off('click');
			myrecord.on('click', () => {
				this.resetText();
				this.resetRecord();
				cc.audioEngine.stopAll();
				element.getComponent(Item).playRecord();
				//
				if (this._records[index] != null) {
					this.playAudioByUrl(this._records[index], () => {
						element.getComponent(Item).stopRecord();
					}); // 播放音效
				}
			});
			myrecord_play.on('click', () => {
				cc.audioEngine.stopAll();
				element.getComponent(Item).stopRecord();
			});
		}

		// 录音界面
		let mask = cc.find('Canvas/mask');
		mask.active = false;

		let icon_record = cc.find('Canvas/mask/icon_record');
		// icon_record.getComponent(dragonBones.ArmatureDisplay).timeScale = 0;

		let record_start = cc.find('Canvas/btn_record_start');
		let record_stop = cc.find('Canvas/btn_record_stop');
		let countdown = cc.find('Canvas/bg_countdown');
		record_start.active = false;
		record_stop.active = false;
		countdown.active = false;
		record_start.off('click');
		record_stop.off('click');
		record_start.on('click', () => {
			this.playLocalAudio('btn');

			mask.active = true;
			// icon_record.getComponent(dragonBones.ArmatureDisplay).timeScale = 1;

			record_start.active = false;
			record_stop.active = true;
			countdown.active = true;

			let cd = 10;
			if (this._curIndex !== -1) {
				cd = this.data.sentences[this._curIndex].countdown;
			}
			this.unschedule(this.onCountdown);
			this._countdown = cd + 1;
			this.onCountdown();
			this.schedule(this.onCountdown, 1);

			this._recording = true;

			let idx = -1; // 获取当前录制下标
			for (let index = 0; index < this.content.childrenCount; index++) {
				const element = this.content.children[index];
				// 正在录制中
				if (element.getComponent(Item).getRecording()) {
					idx = index;
					break;
				}
			}

			if (window['courseware']) {
				if (idx !== -1) {
					window['courseware'].startTest(this.data.sentences[idx].text);
				}
			}
		});
		record_stop.on('click', () => {
			this.playLocalAudio('btn');

			mask.active = false;
			// icon_record.getComponent(dragonBones.ArmatureDisplay).timeScale = 0;

			record_start.active = false;
			record_stop.active = false;
			countdown.active = false;

			this.unschedule(this.onCountdown);
			this._curIndex = -1;

			this._recording = false;

			let idx = -1; // 获取当前录制下标
			for (let index = 0; index < this.content.childrenCount; index++) {
				const element = this.content.children[index];
				// 正在录制中
				if (element.getComponent(Item).getRecording()) {
					idx = index;
					break;
				}
			}

			if (window['courseware']) {
				window['courseware'].stopTest((res) => {
					this.log('--------录音返回结果 stopTest ------------');
					this.log('res' + res);
					res = JSON.parse(res);
					this.log('json res.result' + JSON.stringify(res.result));
					this.log('json res.result.sentences' + JSON.stringify(res.result.sentences));

					if (idx !== -1) {
						let it = this.content.children[idx].getComponent(Item);
						it.recorded();

						let arr = [];
						for (let index = 0; index < res.result.sentences.length; index++) {
							let e = res.result.sentences[index];
							arr = arr.concat(e.details);
						}

						let arrOne = [];
						for (let index = 0; index < arr.length; index++) {
							let e = arr[index];

							arrOne.push({ key: e.word, value: 1 });

							let result = {};
							arrOne.forEach((item) => {
								if (result[item.key]) {
									result[item.key] += item.value;
								} else {
									result[item.key] = item.value;
								}
							});

							for (let k in result) {
								if (k === e.word) {
									if (e.overall < 40) {
										it.setLow(e.word, result[k]);
									}
								}
							}
						}
					}

					if (res && res.audioUrl) {
						if (idx !== -1) {
							this._records[idx] = res.audioUrl;
							onHomeworkFinish(res);
						}
					}
				});
			} else {
				if (idx !== -1) {
					this.content.children[idx].getComponent(Item).recorded();
				}

				// 模拟测试
				// this._records[idx] = 'http://staging-teach.cdn.ireadabc.com/92ddbc65e9af775f7a8450a5bef1a732.mp3';
			}

			this.resetRecord();
		});
	}

	/**
	 * 重置文字
	 */
	resetText() {
		for (let index = 0; index < this.content.childrenCount; index++) {
			const element = this.content.children[index];
			element.getComponent(Item).stop();
		}
	}

	/**
	 * 重置录制音频
	 */
	resetRecord() {
		for (let index = 0; index < this.content.childrenCount; index++) {
			const element = this.content.children[index];
			if (this._records[index] === null) {
				element.getComponent(Item).hideRecord();
			} else {
				element.getComponent(Item).stopRecord();
			}
		}
	}

	/**
	 * 显示提示
	 * @param first
	 */
	showTip(first: boolean = true) {
		this.tip.active = true;

		cc.find('start', this.tip).active = first;
		cc.find('restart', this.tip).active = !first;

		// 提示
		let tip = cc.find('bg', this.tip);
		tip.off('click');
		tip.on('click', () => {
			cc.audioEngine.stopAll();
			this.playAudioByUrl(this.data.questionTextAudio, () => {}); // 播放提示音效
		});
		// 提示内容
		let tip_label = cc.find('label', this.tip).getComponent(cc.Label);
		tip_label.string = this.data.questionText;
		this.playAudioByUrl(this.data.questionTextAudio, () => {}); // 播放提示音效
	}

	/**
	 * 隐藏提示
	 */
	hideTip() {
		this.tip.active = false;
	}

	/**
	 * 倒计时回调
	 */
	onCountdown() {
		this._countdown--;
		if (this._countdown <= 0) {
			let record_stop = cc.find('Canvas/btn_record_stop');

			record_stop.emit('click');
			this.unschedule(this.onCountdown);
		} else {
			let bg_countdown_label = cc.find('Canvas/bg_countdown/label');
			bg_countdown_label.getComponent(cc.Label).string = this._countdown + '';
			if (this._countdown > 9) {
				bg_countdown_label.color = cc.color(83, 102, 138);
				bg_countdown_label.getComponent(cc.Label).fontSize = 50;
				bg_countdown_label.getComponent(cc.LabelOutline).enabled = false;
			} else {
				bg_countdown_label.color = cc.color(255, 132, 132);
				bg_countdown_label.getComponent(cc.Label).fontSize = 64;
				bg_countdown_label.getComponent(cc.LabelOutline).enabled = true;
			}
		}
	}

	onCallBack(event: cc.Event.EventTouch, str: string) {
		if (str === 'start' || str === 'restart') {
			cc.audioEngine.stopAll();
			this.playLocalAudio('btn');
			this.hideTip();
		} else if (str === 'record_start') {
		} else if (str === 'record_stop') {
		}
	}

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