<template>
	<view class="talk-btns">
		<view class="touch-btn" @click="disabled_click">
			<uv-button
				class="touch-btn"
				@touchstart="startRecord"
				@touchend="stopRecord(false)"
				@touchmove="handleMove"
				v-if="!keyboardIsShow"
				:customStyle="{ height: '92rpx' }"
			>
				按住说话
			</uv-button>
			<uv-input
				v-if="keyboardIsShow"
				class="input-box"
				ref="inputRef"
				v-model="inputText"
				:maxlength="props.textValueLength"
				:adjustPosition="false"
				placeholderStyle="color:#999999;font-size:26rpx"
				placeholder="请输入文字"
				:disabled="props.isDisabled"
			></uv-input>
		</view>

		<view class="talk-btn-box">
			<image
				class="talk-btn-icon"
				v-show="!keyboardIsShow"
				src="@/static/images/course/jianpan.png"
				mode=""
				@click="changeBtn"
			></image>
			<image
				class="talk-btn-icon"
				v-show="keyboardIsShow && !inputText"
				src="@/static/images/course/record.png"
				mode=""
				@click="changeBtn"
			></image>
			<image
				class="talk-btn-icon"
				v-show="keyboardIsShow && !!inputText"
				src="@/static/images/course/send.png"
				mode=""
				@click.stop="showKeyboard"
			></image>
		</view>
		<uni-popup ref="popupRef" class="popup">
			<view class="overlay-box">
				<view class="circle-bg-box">
					<view class="icon-box">
						<image src="@/static/images/course/talk-icon.png"></image>
					</view>
				</view>
				<view class="tips-box">松开发送</view>
				<view class="btns-box">
					<view :class="['close-btn', isOut ? 'is-out' : '']" id="circleBox">
						取消
						<image class="btn-box" v-if="!isOut" src="@/static/images/course/close.png" mode=""></image>
						<image class="btn-box" v-else src="@/static/images/course/close-active.png" mode=""></image>
					</view>
				</view>
				<view :class="['talk-dialog', isOut ? 'is-out' : '']">
					<image src="@/static/images/course/voice-white.gif" mode="" class="gif-box"></image>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import { ref, computed, onMounted, nextTick, watch, reactive } from 'vue';
	import common from '@/common/common';
	import permission from '@/common/permission.js';
	import { getPhoneEnvBool } from '@/common/common.js';
	import { initRecord } from '@/composables/useExamSubject.js';
	const emit = defineEmits(['submit']);
	const props = defineProps({
		isDisabled: {
			default: false,
			type: Boolean
		},
		isLoading: {
			default: false,
			type: Boolean
		},
		loadingText: {
			default: '发送回答中，请稍后再试！',
			type: String
		},
		disabledText: {
			default: '请稍后再试！',
			type: String
		},
		canAnswer: {
			default: true,
			type: Boolean
		},
		canAnswerText: {
			default: '当前状态不能发送内容！',
			type: String
		},
		textValueLength: {
			type: Number,
			default: 500
		},
		minRecordDuration: {
			// 最小录音间隔
			type: Number,
			default: 1000
		}
	});

	// 键盘还是语音
	const keyboardIsShow = ref(false);
	const popupRef = ref(null);
	const inputText = ref('');
	let startTime = 0;

	// not_started 未开始， preparing 准备中， in_recording 录音中，ending 结束中
	const recordingStatus = ref('not_started');
	// 获取全局唯一的录音管理器 recorderManager

	// #ifdef APP-PLUS
	const recorderManager = uni.getRecorderManager();
	// #endif

	// const innerAudioContext = uni.createInnerAudioContext();
	const startTimer = ref(null); // 延迟启动的定时器ID
	const startFlag = ref(1);
	const startRecord = async (obj) => {
		try {
			await initRecord();
		} catch (err) {
			return;
		}
		if (props.isDisabled) return;
		// 开始录音
		console.log('开始录音', recordingStatus.value);
		if (recordingStatus.value !== 'not_started') return;
		touchY.value = obj.changedTouches[0].pageY;
		startTimer.value = setTimeout(() => {
			console.log('延迟开始');
			recordingStatus.value = 'preparing';
			popupRef.value.open();
			recorderManager.start({ duration: 59000 });
			startTime = Date.now();
		}, 80);
	};
	// 结束录音
	const stopRecord = (status = false) => {
		console.log('结束录音stopRecord', status);
		if (props.isDisabled) return;
		if (startTimer.value) {
			clearTimeout(startTimer.value);
			startTimer.value = null;
		}
		if (status) {
			nextTick(() => {
				popupRef.value.close();
			});
		} else {
			const endTime = Date.now();
			const times = Math.max(500 - endTime + startTime, 0);
			setTimeout(() => {
				console.log('停止录音');
				recorderManager?.stop();
				
				popupRef.value?.close();
			}, times);
		}
		nextTick(() => (recordingStatus.value = 'not_started'));
	};
	onMounted(async () => {
		// #ifdef APP-PLUS
		recorderManager.onStop(function (res) {
			console.log('录音文件临时位置', res.tempFilePath, isOut.value);
			if (isOut.value) return; // 被划掉的语音
			const endTime = Date.now();
			const recordDuration = endTime - startTime;
			console.log('说话时长', recordDuration);
			if (props.minRecordDuration > recordDuration) {
				nextTick(() => common.msg('说话时间太短，没有听清！'));
				// console.log('说话时间太短，没有听清');
				return;
			}
			popupRef.value?.close();
			recordingStatus.value = 'not_started';
			stopRecord(true); // 在去主动执行一次关闭
			console.log('录音结束，时长：', recordDuration, '秒');
			emit('submit', 'voice', res.tempFilePath);
		});
		recorderManager.onError(function (err) {
			console.log('录音错误', err);
		});
		recorderManager.onStart(function (res) {
			// 检测是否已经抬手结束了
			console.log('检测是否已经抬手结束了', recordingStatus.value);
			if (recordingStatus.value !== 'preparing') {
				stopRecord();
			}

			startTime = Date.now();

			recordingStatus.value = 'in_recording';
		});
		// #endif
	});

	const touchY = ref(0);
	const windowInfo = uni.getWindowInfo();
	// 安全区域信息
	const safeArea = windowInfo.safeArea;
	// 计算是否超出按下盒子位置
	const isOut = computed(() => {
		const btnHeight = (windowInfo.screenWidth / 750) * 234;
		return touchY.value < safeArea.bottom - btnHeight;
	});

	const activeNum = ref(1);
	const handleMove = (obj) => {
		touchY.value = obj.changedTouches[0].pageY;
	};
	const clearinputText = (text = '') => {
		const old_text = inputText.value;
		inputText.value = text;
		return old_text;
	};

	// 发送文本
	const showKeyboard = () => {
		if (keyboardIsShow.value) {
			const inputTextTram = inputText.value.trim();
			if (inputTextTram) {
				emit('submit', 'text', inputTextTram);
			} else {
				common.msg('不能发送空白消息！');
			}
		} else {
			keyboardIsShow.value = !keyboardIsShow.value;
		}
	};
	// 切换键盘语音
	const changeBtn = () => {
		if (props.isDisabled) return;
		keyboardIsShow.value = !keyboardIsShow.value;
		inputText.value = '';
	};
	// 禁用时点击给的提示
	const disabled_click = () => {
		console.log('禁用时点击给的提示');
		if (props.isDisabled) common.msg(props.disabledText);
	};

	// 外面调用放弃这次
	const give_up = () => {
		console.log('调用结束语音回答');
		stopRecord(false)
	};
	defineExpose({ clearinputText, give_up });
</script>

<style lang="scss" scoped>
	.talk-btns {
		height: 150rpx;
		background-color: #fff;
		padding: 25rpx 30rpx 0;
		position: relative;

		.touch-btn {
			height: 92rpx;
			box-shadow: 0 8rpx 20rpx 0 rgba(0, 0, 0, 0.06);
			text-align: center;
			line-height: 92rpx;
			color: #000;
			font-weight: 400;
			position: relative;

			.input-box {
				width: 100%;
				height: 92rpx;
				line-height: 92rpx;
				text-align: left;
				box-sizing: border-box;
				padding: 0 40rpx 0 40rpx;
			}
		}

		.talk-btn-box {
			position: absolute;
			height: 100%;
			width: 120rpx;
			right: 0;
			top: 0;

			.talk-btn-icon {
				width: 40rpx;
				height: 40rpx;
				position: absolute;
				right: 60rpx;
				top: 50%;
				margin-top: -20rpx;
			}
		}
	}

	.overlay-box {
		display: flex;
		flex-direction: column-reverse;
		// justify-content: flex-end;
		width: 100vw;
		height: 100vh;
		background-color: rgba(0, 0, 0, 0.9);

		.circle-bg-box {
			height: 234rpx;
			background: url(@/static/images/course/talking.png) no-repeat;
			background-size: cover;
			position: relative;

			.icon-box {
				position: absolute;
				left: 50%;
				top: 50%;
				margin-left: -17rpx;
				margin-top: -24rpx;
				width: 34rpx;
				height: 48rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}
		}

		.tips-box {
			height: 40rpx;
			line-height: 40rpx;
			color: #c0c0c0;
			text-align: center;
			margin: 12rpx 0 24rpx;
		}

		.btns-box {
			height: 270rpx;
			// padding: 0 120rpx;
			width: 154rpx;
			margin: 0 auto 100rpx;
			overflow: hidden;
			font-size: 28rpx;
			text-align: center;
			line-height: 116rpx;

			.close-btn {
				float: left;
				height: 100%;
				width: 154rpx;
				overflow: hidden;
				color: #999;

				&.is-out {
					color: #fff;
				}
			}

			.translate-btn {
				float: right;
				height: 100%;
				width: 154rpx;
				overflow: hidden;
				color: #999;
			}

			.btn-box {
				width: 100%;
				height: 154rpx;
			}
		}

		.talk-dialog {
			width: 506rpx;
			height: 234rpx;
			margin: 0 auto;
			background-color: #06f;
			border-radius: 32rpx;
			position: relative;

			&.is-out {
				background-color: #ff3e49;

				&::after {
					background-color: #ff3e49;
				}
			}

			.gif-box {
				position: absolute;
				width: 200rpx;
				height: 80rpx;
				left: 50%;
				top: 50%;
				transform: translate(-50%, -50%);
			}

			&::after {
				content: '';
				width: 44rpx;
				height: 44rpx;
				clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
				background-color: #06f;
				overflow: hidden;
				position: absolute;
				bottom: -22rpx;
				left: 50%;
				margin-left: -22rpx;
			}
		}

		.white-bg-box {
			height: 365rpx;
			background-color: #fff;
			overflow: hidden;
			border-radius: 32rpx 32rpx 0 0;
			padding: 58rpx 36rpx;

			.box-title {
				font-size: 32rpx;
				font-weight: bold;
				line-height: 46rpx;
				margin-bottom: 46rpx;
			}

			.box-btns {
				height: 46rpx;
				line-height: 46rpx;
				display: flex;
				justify-content: space-between;
				color: #999;

				.is-active {
					color: #06f;
				}
			}
		}
	}

	::v-deep .uv-input__content__field-wrapper__field {
		padding-right: 60rpx;
	}
</style>
