<template>
	<view class="container">
		<view class="textbox">
			<view class="header-tips">请朗读以下文字</view>
			<view class="textbox-con" :style="{height: textHeight}">
				在这片神奇的森林里，小鸟轻快地唱着歌，仿佛在诉说着春天的故事。
			</view>
		</view>
		<view class="voice-footer">
			<view class="voice-footer-tips">1、选择安静的录音环境，可在房间或车内录音。</view>
			<view class="voice-footer-tips">2、保持20cm距离，避免手机太远录音不清晰。</view>
			<view class="voice-footer-tips">3、使用普通话朗读，语速适中，吐字清晰。</view>
			<view class="voice-footer-btnbox">
				<view class="btnbox-item" :style="{visibility: voicePath ? 'visible' : 'hidden',color: status=='start' ? '#ccc !important':''}">
					<view class="iconsbox" @click="playVoice" :style="{borderColor: status=='start' ? '#ccc' :isVoicePlay ? 'red':''}">
						<u-icon name="volume-fill"  size="30" :color="status=='start' ? '#ccc' :isVoicePlay ? 'red':'#757575'"></u-icon>
						<!-- <uni-icons type="sound-filled" size="30" :color="status=='start' ? '#ccc' :isVoicePlay ? 'red':'#757575'"></uni-icons> -->
					</view>
					<view>试听录音</view>
				</view>
				<view class="btnbox-item">
					<view class="iconsbox iconsbox-voice" :style="{backgroundColor: status=='end' ? 'red':''}" @click="handleRecord">
						<!-- <uni-icons v-show="status=='stop'|| status=='end'" type="mic-filled" size="35" color="#fff"></uni-icons> -->
						<u-icon name="mic"  v-show="status=='stop'|| status=='end'" size="35" color="#fff"></u-icon>
						<image v-show="status=='start'" src="https://obs.jnmyunl.com/fs/20250813/1755047925090.png" mode="aspectFill"></image>
					</view>
					<view v-show="status=='stop'">点击录制</view>
					<view v-show="status=='start'">点击停止</view>
					<view v-show="status=='end'">重新录制</view> 
				</view>
				<view class="btnbox-item" :style="{visibility: voicePath ? 'visible' : 'hidden',color: status=='start' ? '#ccc !important':''}">
					<button class="iconsbox" :disabled="btnLoading" @click="onSubmit">
						<!-- <uni-icons type="checkmarkempty" size="30" :color="status=='start' ? '#ccc' : '#757575'"></uni-icons> -->
						<u-icon name="checkmark" size="30" :color="status=='start' ? '#ccc' : '#757575'"></u-icon>
					</button>
					<view>提交</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {addVoicePrintUrl} from '@/api/test'
	let innerAudioContext = null
	export default {
		data() {
			return {
				recorderManager: null,
				// innerAudioContext: null,
				textHeight: '',
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
				screenHeight: uni.getSystemInfoSync().windowHeight + 'px',
				voicePath: '',
				status: "stop",
				isVoicePlay: false,
				btnLoading: false
			}
		},
		onLoad() {
			console.log('==onLoad==',this.recorderManager)
			// #ifndef H5
			this.recorderManager = uni.getRecorderManager();
			innerAudioContext = uni.createInnerAudioContext();
			
			let self = this;
			console.log('==recorderManager22222222==',this.recorderManager)
			if(this.recorderManager) {
				console.log('==recorderManager==')
				this.recorderManager.onStart(()=>{
					console.log('==start==')
					this.status = 'start'
				})
				this.recorderManager.onStop((res)=> {
					console.log('recorder stop' + JSON.stringify(res));
					this.status = 'end'
					self.voicePath = res.tempFilePath;
				});
				this.recorderManager.onError((res)=> {
					console.log('onError ==' + JSON.stringify(res));
				});
			}
			
			if(innerAudioContext) {
				// innerAudioContext.autoplay = true;
				innerAudioContext.onPlay(() => {
				  // console.log('开始播放');
				  this.isVoicePlay = true
				});
				innerAudioContext.onStop(() => {
				  // console.log('停止播放');
				  this.isVoicePlay = false
				});
				innerAudioContext.onEnded(() => {
				  // console.log('播放结束');
				  this.isVoicePlay = false
				});
				innerAudioContext.onError((res) => {
					// console.log('播放res',res);
				  this.isVoicePlay = false
				});
				innerAudioContext.onPause(() => {
				  // console.log('暂停播放');
				  this.isVoicePlay = false
				});
			}
			// #endif
		},
		onReady() {
			const query = uni.createSelectorQuery().in(this);
			query
			  .select(".voice-footer")
			  .boundingClientRect((data) => {
				this.textHeight = `calc(${this.screenHeight} - ${data.height}px - ${this.statusBarHeight} - 45px - ${uni.upx2px(120)}px)`
			  })
			  .exec();
		},
		onHide() {
			if(innerAudioContext){
				innerAudioContext.pause();
			}
		},
		onUnload() {
			this.recorderManager = null
			if(innerAudioContext) {
				innerAudioContext.destroy()
				innerAudioContext = null
			}
		},
		methods: {
			handleRecord() {
				console.log('handleRecord',this.status)
				if(innerAudioContext){
					innerAudioContext.pause();
				}
				if(this.status == 'stop') {
					this.startRecord()
				} else if(this.status == 'start') {
					this.endRecord()
				} else if(this.status == 'end') {
					this.startRecord()
				}
			},
			startRecord() {
				console.log('this.recorderManager',this.recorderManager)
				// console.log('开始录音');
				// 声音采集限制10秒
				this.recorderManager.start({
					format: 'mp3',
					duration: 10000
				});
			},
			endRecord() {
				// console.log('录音结束');
				this.recorderManager.stop();
			},
			playVoice() {
				console.log(innerAudioContext)
				if(this.status == "start") return
				if (this.voicePath) {
					if(this.isVoicePlay == false) {
						innerAudioContext.src = this.voicePath;
						innerAudioContext.play();
					} else {
						innerAudioContext.stop();
					}
				}
			},
			onSubmit() {
				console.log("==onSubmit=",this.status)
				if(this.status == "start") return
				this.btnLoading = true
				uni.showLoading({
					title:"提交中..."
				})
				uni.uploadFile({
					url: uni.getStorageSync('requestPath')+'/app/common/uploadOSS', //仅为示例，非真实的接口地址
					filePath: this.voicePath,
					name: 'file',
					success: (uploadFileRes) => {
						console.log(JSON.parse(uploadFileRes.data).url)
						let voicePrintUrl = JSON.parse(uploadFileRes.data).url
						addVoicePrintUrl({voicePrintUrl: voicePrintUrl}).then(res=>{
							uni.hideLoading()
							this.btnLoading = false
							if(res.code==200){
								uni.showToast({
									icon:'none',
									title: '提交成功',
								});
							}else{
								uni.showToast({
									icon:'none',
									title: res.msg,
								});
							}
						}).catch(()=>{
							uni.hideLoading()
							this.btnLoading = false
						})
					},
					fail: ()=>{
						uni.hideLoading()
						this.btnLoading = false
					}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}
	.container {
		position: relative;
		.header-tips {
			padding-bottom: 24rpx;
			box-sizing: border-box;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #757575;
			// color: $mainThemeHColor;
			text-align: center;
		}
		.textbox {
			padding: 24rpx 50rpx;
			box-sizing: border-box;
			&-con {
				padding: 32rpx;
				box-sizing: border-box;
				background-color: #fff;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 40rpx;
				color: #222222;
				overflow-y: auto;
				line-height: 60rpx;
				letter-spacing: 4rpx;
			}
		}
		.voice-footer {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 100%;
			box-sizing: border-box;
			&-tips {
				padding: 0 50rpx;
				box-sizing: border-box;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #757575;
				margin-bottom: 10rpx;
			}
		}
	}
	.voice-footer-btnbox {
		@include u-flex(row,flex-end,space-evenly);
		margin-top: 100rpx;
		padding: 50rpx 24rpx;
		background-color: #fff;
		text-align: center;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #333;
		.iconsbox {
			height: 110rpx;
			width: 110rpx;
			margin: 0;
			margin-bottom: 20rpx;
			box-sizing: border-box;
			@include u-flex(row,center,center);
			border-radius: 50%;
			background-color: #fff;
			border: 1rpx solid #CCCCCC;
			&::after {
				border: none;
			}
			&-voice {
				height: 150rpx;
				width: 150rpx;
				background-color: #FF5C03;
				border: 1rpx solid #FF5C03;
				image {
					height: 60rpx;
					width: 60rpx;
				}
			}
		}
		.btnbox-item {
			flex: 1;
			@include u-flex(column,center,center);
		}
		
	}
</style>