<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" :value="videoName" placeholder="请输入视频名称">
			</view>
			<view class="form-area-item">
				<text class="form-area-item-text">选择您的形象</text>
				<!-- 				<lsj-upload ref="lsjUpload" childId="upload1" width="150rpx" height="100%" :option="option" :size="10"
					:debug="true" :multiple="false" formats="xlsx" :count="1" :instantly="false" @change="uploadChange"
					@uploadEnd="onuploadEnd">
					<button class="cu-btn bg-red">选择文件</button>
				</lsj-upload>
				<button type="primary" @click="handleUploadSubmit"
					style="padding: 0rpx 0;margin-top: 20rpx;font-size:25rpx;background-color: #E62F3D;">确认上传</button> -->
				<button @click="chooseFile" class="cu-btn bg-red">选择文件</button>
				<text class="none-file" v-if="fileInfo.name">{{fileInfo.name}} ({{formatFileSize(fileInfo.size)}})</text>
				<text class="none-file" v-else>未选择文件</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>
				<!-- <picker @change="bindPickerChange" :value="modelIndex" :range="array">
					<view class="uni-input">{{array[modelIndex]}}</view>
				</picker> -->
				<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 placeholder="请输入视频中的文字内容" />
			</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>
		</form>
		<view class="btn-area">
			<button @click="jumpToList" class="bg-red lg round create-project">生成数字人视频</button>
		</view>
	</view>
</template>
<script>
	import CustomModal from '../components/CustomModal.vue';
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		components: {
			CustomModal
		},
		data() {
			return {
				videoName: '',
				fileInfo: {},
				imageInfo: {},
				array: [{
						value: 'ceshi1',
						text: 'demo1'
					},
					{
						value: 'ceshi2',
						text: 'demo3'
					},
				],
				modelIndex: undefined,
				isModalVisible: false,
				modalMessage: '',
				modalImageSrc: '',
				videoContent: [{
						value: 'text',
						text: '文字输入'
					},
					{
						value: 'record',
						text: '语音录入'
					}
				],
				current: 'text',
				// 上传组件接口参数
				option: {
					// 上传服务器地址，需要替换为你的接口地址
					url: this.$URL + '/App/selection/xp/uploadExcel',
					// 上传附件的key
					name: 'file',
					// 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
					header: {
						token: uni.getStorageSync('token'),
					},
					// 根据你接口需求自定义body参数
					formData: {
						// 'orderId': 1000
					}
				},
				chooseFile: {},
				upload1: 1, // 控件的id
				imagePath: '',
				isRecording: false,
				audioPath: null,
				recorderManager: null,
				innerAudioContext: null
			}
		},
		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'
				});
				console.error('录音错误：', err);
			});
		},
		methods: {
			/* // 上传组件 change
			uploadChange(files) {
				this.showUploadResult = false
				console.log('当前选择的文件列表：', files);
				// file 为 Map对象
				// 更新选择的文件 
				// this.files = files;
				for (let value of files.values()) {
					// 我这里使用的是 单选上传
					this.chooseFile = value
					console.log(value);
				}
			},
			// 点击上传 按钮
			handleUploadSubmit() {
				uni.showLoading({
					mask: true
				})
				if (!this.chooseFile.path) {
					uni.showToast({
						title: '请选择上传文件',
						icon: 'none'
					})
					return
				}
				console.log('uploadPath', this.chooseFile)

				// 上传组件上传
				this.$refs['lsjUpload'].upload();
				// 上传组件 获取的文件路径path是一个blobURL，如果不想用组件本身的上传方法，需自行处理

			},
			// 文件上传完毕 事件
			onuploadEnd(item) {
				uni.hideLoading()
				if (item.type !== 'success') {
					uni.showToast({
						title: '上传文件失败',
						icon: 'none'
					})
				}
				console.log(`${item.name}已上传结束，上传状态=${item.type},`, item);
				const result = JSON.parse(item.responseText)
				// 这里可以做后续操作
			}, */
			/* async chooseFile() {
				try {
					const [file] = await uni.chooseFile({
						count: 1,
						extension: ['.zip', '.doc'],
					})
					this.fileInfo = {
						name: file.name,
						size: file.size,
						type: file.type,
						path: file.path
					}
					uni.showToast({
						title: '文件选择成功',
						icon: 'success'
					})
					// 这里可以处理文件上传或其他操作
					console.log('选择的文件:', this.fileInfo)
				} catch (error) {
					if (error.errMsg !== 'chooseFile:fail cancel') {
						uni.showToast({
							title: '选择文件失败',
							icon: 'none'
						})
					}
				}
			}, */

			async chooseImage() {
				const that = this;
				uni.chooseImage({
					count: 1, // 默认只能选一张
					sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
					sourceType: ['album', 'camera'], // 从相册选择或使用相机
					success: function(res) {
						// res.tempFilePaths 是图片临时路径数组
						console.log('选择成功：', res);
						// that.imageInfo.name=res.tempFilePaths[0].split('/')[res.tempFilePaths[0].split('/').length-1]
						// 设置选中的图片路径（第一张）
						that.imagePath = res.tempFilePaths[0];
					},
					fail: function(err) {
						console.error('图片选择失败：', err);
						uni.showToast({
							title: '图片选择失败',
							icon: 'none'
						});
					}
				});
				/* try {
					const [file] = await uni.chooseImage({
						count: 1,
						sizeType: ['original', 'compressed'],
						sourceType: ['album'],
							success: function(res) {
								console.log(JSON.stringify(res.tempFilePaths),res,'=============');
							}
					});
					console.log(file,'----------')
					this.imageInfo = {
						name: file.name,
						size: file.size,
						type: file.type,
						path: file.path
					}
					uni.showToast({
						title: '文件选择成功',
						icon: 'success'
					})
					// 这里可以处理文件上传或其他操作
					console.log('选择的文件:', this.imageInfo)
				} catch (error) {
					if (error.errMsg !== 'chooseFile:fail cancel') {
						uni.showToast({
							title: '选择文件失败',
							icon: 'none'
						})
					}
				} */
			},
			// formatFileSize(bytes) {
			// 	if (bytes === 0) return '0 B'
			// 	const k = 1024
			// 	const sizes = ['B', 'KB', 'MB', 'GB']
			// 	const i = Math.floor(Math.log(bytes) / Math.log(k))
			// 	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
			// },
			bindPickerChange(e) {
				console.log(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.modelIndex = e.detail.value; // 更新选中的值
				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;
					}
				}
			},
			// startRecord() {
			// 	console.log('开始录音');
			// 	recorderManager.start();
			// },
			// endRecord() {
			// 	console.log('录音结束');
			// 	recorderManager.stop();
			// },
			// playVoice() {
			// 	console.log('播放录音');
			// 	if (this.voicePath) {
			// 		innerAudioContext.src = this.voicePath;
			// 		innerAudioContext.play();
			// 	}
			// },
			toggleRecording() {
				if (this.isRecording) {
					// 停止录音
					this.recorderManager.stop();
				} else {
					// 开始录音前，如果已有录音则清空
					if (this.audioPath) {
						this.audioPath = null;
					}

					// 开始录音
					this.recorderManager.start({
						duration: 60000, // 最大录音时间（毫秒）
						sampleRate: 44100,
						numberOfChannels: 1,
						encodeBitRate: 192000,
						format: 'mp3',
						frameSize: 50
					});

					this.isRecording = true;
				}
			},
			playAudio() {
				if (!this.audioPath) {
					uni.showToast({
						title: '没有可播放的录音',
						icon: 'none'
					});
					return;
				}

				this.innerAudioContext.src = this.audioPath;
				this.innerAudioContext.play();
			},
			jumpToList() {
				uni.navigateTo({
					url: 'list/index'
				});
			}
		}
	}
</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;
			}
		}
	}

	.btn-area {
		display: flex;
		justify-content: center;
		margin: 0 auto;
		width: 100%;
		margin-bottom: 10px;
	}
	.audio-bar {
	  background-color: #f0f0f0;
	  border-radius: 8px;
	  text-align: center;
	}
</style>