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

// import { threadId } from _ls_gramophone'worker_threads';
import Item from '../script/Item_ls_gramophone';
import { MyCocosSceneComponent } from '../script/MyCocosSceneComponent_ls_gramophone';
import { onHomeworkFinish } from '../script/util_ls_gramophone';
import pg from './pg_ls_gramophone';

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;

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

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

	@property(cc.Node)
	btn_last: cc.Node = null;
	@property(cc.Node)
	btn_audio_off: cc.Node = null;
	@property(cc.Node)
	btn_audio_on: cc.Node = null;

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

	// 当前
	_curIndex = -1;

	_results = [];

	private _curData = null;
	private isPlayBgAudio: boolean;
	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.questions.length; index++) {
			this._audioResList.push({ url: this.data.questions[index].audio });
		}
	}

	addPreloadAnima() { }

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

	initData() {
		this._recording = false;
		this._curData = null;
		this.roundIdx = 0;

		this._records.length = 0;
		this._results.length = 0;
		this.data.questions.forEach((element, idx) => {
			this._records.push([]);
			this._results.push([]);
			element.options.forEach(op => {
				this._records[idx].push(null);
				this._results[idx].push(null);
			});
		});
		this.isPlayBgAudio = true;
	}

	private stopQuestionAudio() {
		if (this.questionAudioId > -1) pg.audio.stopAudio(this.questionAudioId);

	}
	private questionAudioId = -1;
	initView() {
		let self = this;
		const bgNode = cc.find('Canvas/bg');
		bgNode.scale = this._mapScaleMax;

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

		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', () => {
			this.stopQuestionAudio();

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

			play.active = true;
			stop.active = false;
			pg.audio.playAudioByUrl(this.data.questions[this.roundIdx].audio, (() => {
				play.active = false;
				stop.active = true;
			})).then((audioId: number) => {
				this.questionAudioId = audioId;
			})
		});
		let pag = cc.find("PageView", this.node);
		pag.on('page-turning', this.pageTurning, this);
		for (let i = 0; i < this.data.questions.length; i++) {
			let ScrollView = cc.instantiate(cc.find("ScrollView", this.node));
			// this.pagContent.addChild(ScrollView);
			pag.getComponent(cc.PageView).addPage(ScrollView);
			let option = this.data.questions[i];
			let content = cc.find("view/content", ScrollView);
			for (let index = 0; index < option.options.length; index++) {
				let quest = option.options[index];
				let element = cc.instantiate(this.item);
				element.active = true;
				element.name = '' + index;
				element.parent = content;

				// const element = this.content.children[index];
				element.getComponent(Item).init(quest.text);

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

					pg.audio.stopAudio(this.itemAudio);
					element.getComponent(Item).playing();
					pg.audio.playAudioByUrl(quest.audio, () => {
						element.getComponent(Item).stop();
					}).then((audioId: number) => {
						this.itemAudio = audioId;
					});
				});

				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();
					this.stopQuestionAudio();
					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._curData = quest;
					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();
					this.stopQuestionAudio();
					element.getComponent(Item).playRecord();
					//
					if (this._records[this.roundIdx][index] != null) {
						this.playAudioByUrl(this._records[this.roundIdx][index], () => {
							element.getComponent(Item).stopRecord();
						}); // 播放音效
					}
				});
				myrecord_play.on('click', () => {
					// cc.audioEngine.stopAll();
					this.stopQuestionAudio();
					element.getComponent(Item).stopRecord();
				});
			}

		}
		pag.getComponent(cc.PageView).enabled = false;
		// 录音界面
		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');

			this.stopBgAudio();
			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._curData) {
				cd = this._curData.duration;
			}
			this.unschedule(this.onCountdown);
			this._countdown = Number(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;
			// 	}
			// }
			this.pagContent.children.forEach((sc) => {
				let content = cc.find("view/content", sc);
				content.children.forEach((item, index) => {
					if (item.getComponent(Item).getRecording()) {
						idx = index;
					}
				})
			})
			this.log('idx:' + idx);
			let text = self.data.questions[this.roundIdx].options[idx].text;
			this.log("text: " + text);
			if (window['courseware']) {
				if (idx !== -1) {
					this.log("1");
					window['courseware'].startTest(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._curData = null

			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;
			// 	}
			// }
			this.pagContent.children.forEach((sc) => {
				let content = cc.find("view/content", sc);
				content.children.forEach((item, index) => {
					if (item.getComponent(Item).getRecording()) {
						idx = index;
					}
				})
			})
			this.log('idx:' + idx);

			if (window['courseware']) {
				this.playBgAudio();
				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);
						let content = cc.find("view/content", this.pagContent.children[this.roundIdx]);
						let it = 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);
						}

						it.cleanLow();
						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[this.roundIdx][idx] = res.audioUrl;
							// this._records[idx] = res.audioUrl;
							this.log(`${idx} ===> ${res.audioUrl}`);
							this.resetRecord();

							// this.scheduleOnce(() => {});
						}
					}

					this._results[this.roundIdx][idx] = res;
					for (const iterator of this._results) {
						for (const op of iterator) {
							if (op === null) {
								return;
							}
						}
					}
					onHomeworkFinish({ stone: 10, details: this._results });
				});
			} else {
				this.playBgAudio();
				if (idx !== -1) {
					let content = cc.find("view/content", this.pagContent.children[this.roundIdx]);
					content.children[idx].getComponent(Item).recorded();
				}
				// 模拟测试
				this._records[this.roundIdx][idx] = 'http://staging-teach.cdn.ireadabc.com/92ddbc65e9af775f7a8450a5bef1a732.mp3';
			}
			this.resetRecord();
		});
		this.btn_arrow.on(cc.Node.EventType.TOUCH_END, this.onArrow, this);
		this.btn_last.on(cc.Node.EventType.TOUCH_END, this.onLast, this);
		this.btn_audio_off.on(cc.Node.EventType.TOUCH_END, this.onAudioOff, this);
		this.btn_audio_on.on(cc.Node.EventType.TOUCH_END, this.onAudioOn, this);
		this.setPagBg();
		this.refreshArrow();
		if (this.data.bgAudio && this.data.bgAudio != "") {
			this.btn_audio_on.active = true;
		}
	}
	private itemAudio = -1;
	private onAudioOn() {
		this.btn_audio_off.active = true;
		this.btn_audio_on.active = false;
		this.isPlayBgAudio = false;
		this.stopBgAudio();
	}
	private onAudioOff() {
		this.btn_audio_on.active = true;
		this.btn_audio_off.active = false;
		this.isPlayBgAudio = true;
		this.playBgAudio();
	}
	private playBgAudio() {
		if (!this.isPlayBgAudio) return;
		cc.audioEngine.resumeMusic();
	}
	private stopBgAudio() {
		cc.audioEngine.pauseMusic();
	}
	private roundIdx;
	private setPagBg() {
		let play = cc.find('Canvas/btn_play');
		let stop = cc.find('Canvas/btn_stop');
		play.active = false;
		stop.active = true;
		// cc.audioEngine.stopAll();
		this.stopQuestionAudio();
		this.resetText();
		this.resetRecord();

		let pag = cc.find("PageView", this.node);
		let idx = pag.getComponent(cc.PageView).getCurrentPageIndex();
		let data = this.data.questions[this.roundIdx].pageImage;
		this.getSpriteFrimeByUrl(data, (sp) => {//+ '?x-oss-process=image/resize,m_fill,h_520,w_560'
			// this.getSpriteFrimeByUrl(this.data.pageImage, (sp) => {
			cc.find('Canvas/bg_img/img').getComponent(cc.Sprite).spriteFrame = sp;
			cc.find('Canvas/bg_img/img').width = 435;
			cc.find('Canvas/bg_img/img').height = 585;
			cc.find('Canvas/bg_img/img').scale = 1;// Math.max(520 / cc.find('Canvas/bg_img/img').width, 560 / cc.find('Canvas/bg_img/img').height);
		});

	}
	private refreshArrow() {
		this.btn_last.active = this.roundIdx > 0;
		this.btn_arrow.active = this.roundIdx < this.data.questions.length - 1;
	}
	private arrowTouch = false;
	private onArrow() {
		if (this.arrowTouch) return;
		this.arrowTouch = true;
		this.roundIdx++;
		let pag = cc.find("PageView", this.node);
		pag.getComponent(cc.PageView).enabled = true;
		pag.getComponent(cc.PageView).scrollToPage(this.roundIdx, 0.1);
		this.setPagBg();
		this.refreshArrow();
	}
	private onLast() {
		if (this.arrowTouch) return;
		this.arrowTouch = true;
		this.roundIdx--;
		let pag = cc.find("PageView", this.node);
		let len = pag.getComponent(cc.PageView).getPages().length;
		if (len <= 1) return;
		pag.getComponent(cc.PageView).enabled = true;
		pag.getComponent(cc.PageView).scrollToPage(this.roundIdx, 0.1);
		this.setPagBg();
		this.refreshArrow();
	}
	private pageTurning() {
		let pag = cc.find("PageView", this.node);
		pag.getComponent(cc.PageView).scrollToPage(this.roundIdx, 0.1);
		setTimeout(() => {
			pag.getComponent(cc.PageView).enabled = false;
			this.arrowTouch = false;
		}, 200);
	}
	/**
	 * 重置文字
	 */
	resetText() {
		this.pagContent.children.forEach((sc) => {
			let content = cc.find("view/content", sc);
			content.children.forEach((item) => {
				item.getComponent(Item).stop();
			})
		})
	}

	/**
	 * 重置录制音频
	 */
	resetRecord() {
		let content = cc.find("view/content", this.pagContent.children[this.roundIdx]);
		for (let index = 0; index < content.childrenCount; index++) {
			const element = content.children[index];
			if (this._records[this.roundIdx][index] === null) {
				element.getComponent(Item).hideRecord();
			} else {
				console.log(`===> ${index}`);
				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');
			pg.audio.playBgAudioByUrl(this.data.bgAudio);
			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);
			});
		});
	}
}

