<template>
	<view class="content">
		<view class="uni-margin-wrap">
			<swiper class="swiper" circular :indicator-dots="true" indicator-color="#DE868F" indicator-active-color="#fff"
				:autoplay="true" :interval="1000" :duration="500">
				<swiper-item>
					<view class="swiper-item">功能介绍1</view>
				</swiper-item>
				<swiper-item>
					<view class="swiper-item">功能介绍2</view>
				</swiper-item>
				<swiper-item>
					<view class="swiper-item">功能介绍3</view>
				</swiper-item>
			</swiper>
		</view>
		<form class="form-area">
			<view class="form-area-item">
				<text class="form-area-item-text">视频名称</text>
				<input type="text" v-model="videoName" placeholder="请输入视频名称">
			</view>
			<!-- 			<view class="form-area-item" :key="timeStamp">
				<text class="form-area-item-text">选择您的形象</text>
				<button @click="chooseFile" class="cu-btn bg-red">选择文件</button>
				<text class="file-name" v-if="fileInfo.name">{{fileInfo.name}}</text>
				<text class="none-file" v-if="!showPerson">未选择文件</text>
			</view> -->
			<view class="form-area-item">
				<text class="form-area-item-text">选择您的形象</text>
				<button @click="chooseImage" class="cu-btn bg-red">选择图片</button>
				<text class="none-file" v-if="!imagePath">未选择图片</text>
				<image :src="imagePath" v-else mode="aspectFit" style="width: 30px; height: 30px;margin-left:10px" />
			</view>
			<!-- 			<view class="form-area-item">
				<text class="form-area-item-text">选择模板</text>
				<uni-data-select v-model="modelIndex" :localdata="array" @change="bindPickerChange"></uni-data-select>
				<CustomModal :visible="isModalVisible" :message="modalMessage" :imageSrc="modalImageSrc" @confirm="onConfirm"
					@cancel="onCancel" />
			</view> -->
			<view class="form-area-item">
				<text class="form-area-item-text">视频内容</text>
				<uni-data-checkbox selectedColor="#BD3124" selectedTextColor="#BD3124" v-model="current"
					:localdata="videoContent" />
			</view>
			<view class="form-area-item" v-if="current=='text'">
				<textarea v-model="videoText" placeholder="请输入视频中的文字内容" />
			</view>
			<view class="form-area-item" v-if="current=='text'">
				<text class="form-area-item-text">音色选择</text>
				<uni-data-checkbox selectedColor="#BD3124" selectedTextColor="#BD3124" v-model="timbre"
					:localdata="timbreContent" />
			</view>
			<view class="form-area-item" v-if="current=='record'">
				<button @click="toggleRecording">{{ isRecording ? '停止录音' : '开始录音' }}</button>
				<!-- 				<view v-if="audioPath" class="audio-bar" @click="playAudio">
					🎵 录音文件（点击播放）
				</view> -->
			</view>
			<audio v-if="audioPath" class="audio-bar" :src="audioPath" name="语音试听" poster="../static/images/xijiao/avator.png"
				:action="audioAction" controls></audio>
		</form>
		<view class="btn-area">
			<button @click="jumpToList" class="bg-red lg round create-project">生成数字人视频</button>
			<uni-popup ref="alertDialog" type="dialog">
				<uni-popup-dialog type="warning" cancelText="确定" title="提示" :content="missingContent"
					@close="dialogClose"></uni-popup-dialog>
			</uni-popup>
		</view>
	</view>
</template>
<script>
	// import CustomModal from '../components/CustomModal.vue';
	import {
		uploadPerson
	} from "@/api/system/user"
	import store from '@/store'
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		// components: {
		// 	CustomModal
		// },
		data() {
			return {
				videoName: '',
				fileInfo: {},
				videoContent: [{
						value: 'text',
						text: '文字输入'
					},
					{
						value: 'record',
						text: '语音录入'
					}
				],
				current: 'text',
				imagePath: '',
				isRecording: false,
				audioPath: null,
				recorderManager: null,
				innerAudioContext: null,
				showPerson: false,
				timeStamp: null,
				audioAction: {
					method: 'pause'
				},
				videoText: '',
				missingContent: [],
				timbre: 'a',
				timbreContent: [{
						value: 'a',
						text: 'timbre1'
					},
					{
						value: 'b',
						text: 'timbre2'
					}
				],
				personPath: ''
			}
		},
		onLoad() {
			this.recorderManager = uni.getRecorderManager();
			this.innerAudioContext = uni.createInnerAudioContext();

			// 监听录音停止
			this.recorderManager.onStop((res) => {
				console.log('录音结束，临时路径：', res.tempFilePath);
				this.audioPath = res.tempFilePath; // 替换为新录音路径
				this.isRecording = false;
			});

			// 监听录音错误
			this.recorderManager.onError((err) => {
				uni.showToast({
					title: '录音出错',
					icon: 'none'
				});
			});
		},
		onShow() {
			this.timeStamp = new Date().getTime()
			this.fileInfo.path = uni.getStorageSync('filePath');
			this.fileInfo.name = uni.getStorageSync('fileName');
			if (this.fileInfo.name) this.showPerson = true
		},
		methods: {
			/* chooseFile() {
				uni.navigateTo({
					url: "/pages/root-filelist/root-filelist",
				});
			}, */
			async chooseImage() {
				const that = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						that.imagePath = res.tempFilePaths[0];
						that.uploadImagePath()
					},
					fail: function(err) {
						uni.showToast({
							title: '图片选择失败',
							icon: 'none'
						});
					}
				});
			},
			/* 			bindPickerChange(e) {
							const tempOption = this.array.find(item => item.value == e).text;
							this.modalMessage = `您选择的是: ${tempOption}`;
							this.modalImageSrc = '../static/images/xijiao/avator.png';
							this.isModalVisible = true;
							this.modelIndex = e
						},
						onConfirm() {
							this.isModalVisible = false;
						},
						onCancel() {
							this.isModalVisible = false;
						}, */
			radioChange(evt) {
				for (let i = 0; i < this.videoContent.length; i++) {
					if (this.videoContent[i].value === evt.detail.value) {
						this.current = i;
						break;
					}
				}
			},

			toggleRecording() {
				if (this.isRecording) {
					this.recorderManager.stop();
				} else {
					// 开始录音前，如果已有录音则清空
					if (this.audioPath) {
						this.audioPath = null;
					}
					// 开始录音
					this.recorderManager.start({
						duration: 600000, // 最大录音时间（毫秒）
						sampleRate: 44100,
						numberOfChannels: 1,
						encodeBitRate: 192000,
						format: 'wav',
					});
					this.isRecording = true;
				}
			},
			// playAudio() {
			// 	if (!this.audioPath) {
			// 		uni.showToast({
			// 			title: '没有可播放的录音',
			// 			icon: 'none'
			// 		});
			// 		return;
			// 	}
			// 	this.innerAudioContext.src = this.audioPath;
			// 	this.innerAudioContext.play();
			// },
			uploadImagePath() {
				let data = {
					file: this.imagePath
				}
				uploadPerson(data).then(response => {
					this.personPath = response.data.url
				})
			},
			jumpToList() {
				let missingFields = [];
				if (!this.videoName.trim()) {
					missingFields.push('视频名称');
				}
				// if (!this.fileInfo.path) {
				// 	missingFields.push('人物形象');
				// }
				if (!this.imagePath) {
					missingFields.push('人物形象');
				}
				// if (!this.modelIndex) {
				// 	missingFields.push('视频模板');
				// }
				const hasContent = this.videoText.trim() !== '' && this.timbre;
				const hasVoice = this.audioPath;
				if (!hasContent && !hasVoice) {
					missingFields.push('文字内容或语音输入');
				}
				if (missingFields.length > 0) {
					this.missingContent = `请确定：${missingFields.join('、')}是否填写完整！`
					this.$refs.alertDialog.open()
					return;
				}
				uni.navigateTo({
					url: 'list/creatingVideo/creatingVideo',
				});
			},
			dialogClose() {
				console.log('点击关闭')
			},
		}
	}
</script>
<style scoped lang="scss">
	.content {
		display: flex;
		flex-direction: column;
		/* 		align-items: center;
		justify-content: center; */
	}

	.uni-margin-wrap {
		width: 690rpx;
		width: 100%;
	}

	.swiper {
		height: 300rpx;
	}

	.swiper-item {
		display: block;
		height: 300rpx;
		line-height: 300rpx;
		text-align: center;
		background-color: #BD3124;
		color: #fff;
	}

	.form-area {
		padding: 20px;

		.form-area-item {
			display: flex;
			flex-direction: row;
			margin-top: 30px;
			align-items: center;

			.form-area-item-text {
				width: 120px;
			}

			/deep/ uni-input {
				border: 1px solid #e5e5e5;
				border-radius: 4px;
				height: 30px;
				width: 200px;
			}

			/deep/ uni-picker {
				border-bottom: 1px solid #aaa;
				height: 30px;
				width: 200px;
				display: flex;
				align-items: center;
			}

			/deep/ uni-radio-group,
			/deep/ uni-label {
				display: flex;
				align-items: center;
			}

			/deep/ uni-label {
				margin-right: 10px;
			}

			/deep/ textarea {
				border: 1px solid #aaa;
				border-radius: 4px;
				width: 320px;
				padding: 5px;
				margin: 0 auto;
			}

			.none-file {
				margin-left: 10px;
				color: #aaa;
			}

			.file-name {
				margin-left: 10px;
				width: 50px;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}
		}
	}

	.btn-area {
		display: flex;
		justify-content: center;
		margin: 20px auto;
		width: 100%;
	}

	.audio-bar {
		text-align: center;
		display: block;
		margin-top: 10px;
	}

	/deep/ .uni-border-left {
		display: none;
	}
</style>