<template>
	<view class="container" :class="AppStyle">
		<!-- 自定义导航栏 -->
		<view class="header" :style="[{height:CustomBar + 'px'}]">
			<view class="cu-bar bg-white" :style="{'height': CustomBar + 'px','padding-top':StatusBar + 'px'}">
				<view class="action" @tap="back">
					<text class="cuIcon-back"></text>
				</view>
				<view class="content text-bold" :style="[{top:StatusBar + 'px'}]">
					上传视频
				</view>
				<view class="action">
					<!-- 占位 -->
				</view>
			</view>
		</view>
		<view :style="[{padding:(NavBar+5) + 'px 10px 0px 10px'}]"></view>

		<!-- 上传表单 -->
		<view class="upload-form">
			<!-- 视频预览 -->
			<view class="video-preview" v-if="formData.video_url">
				<video :src="formData.video_url" :poster="formData.cover_url" controls></video>
			</view>

			<!-- 视频上传按钮 -->
			<view class="upload-btn" v-else @tap="chooseVideo">
				<text class="cuIcon-cameraadd"></text>
				<text>选择视频</text>
			</view>

			<!-- 表单内容 -->
			<view class="form-content">
				<view class="form-item">
					<view class="form-label">视频标题</view>
					<input
						type="text"
						v-model="formData.title"
						placeholder="请输入视频标题"
						class="form-input"
						maxlength="50"
					/>
				</view>

				<view class="form-item">
					<view class="form-label">视频描述</view>
					<textarea
						v-model="formData.description"
						placeholder="请输入视频描述"
						class="form-textarea"
						maxlength="200"
					></textarea>
				</view>

				<!-- 封面图 -->
				<view class="form-item">
					<view class="form-label">视频封面</view>
					<view class="cover-preview" v-if="formData.cover_url">
						<image :src="formData.cover_url" mode="aspectFill"></image>
						<view class="cover-actions">
							<view class="cover-action" @tap="chooseCover">更换</view>
							<view class="cover-action" @tap="removeCover">删除</view>
						</view>
					</view>
					<view class="cover-upload" v-else @tap="chooseCover">
						<text class="cuIcon-picfill"></text>
						<text>选择封面</text>
					</view>
				</view>

				<!-- 视频信息 -->
				<view class="video-info" v-if="formData.video_url">
					<view class="info-item">
						<text class="info-label">时长：</text>
						<text class="info-value">{{formatDuration(formData.duration)}}</text>
					</view>
					<view class="info-item">
						<text class="info-label">大小：</text>
						<text class="info-value">{{formatSize(formData.size)}}</text>
					</view>
				</view>

				<!-- 提交按钮 -->
				<button
					class="submit-btn"
					:disabled="!formData.video_url || !formData.title || !formData.cover_url || uploading"
					@tap="submitForm"
				>
					{{uploading ? '上传中...' : '发布视频'}}
				</button>

				<!-- 提示信息 -->
				<view class="tips">
					<text>提示：</text>
					<text>1. 视频最大时长为{{Math.floor(videoSettings.max_duration/60)}}分钟</text>
					<text>2. 视频最大大小为{{(videoSettings.max_size/(1024*1024)).toFixed(0)}}MB</text>
					<text>3. 支持的格式：{{videoSettings.allowed_formats}}</text>
					<text>4. {{videoSettings.auto_approve ? '视频将自动发布' : '视频将在审核通过后发布'}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			StatusBar: this.StatusBar,
			CustomBar: this.CustomBar,
			NavBar: this.StatusBar + this.CustomBar,
			AppStyle: this.$store.state.AppStyle,
			token: '',
			uploading: false,
			// 视频设置
			videoSettings: {
				max_duration: 300, // 默认5分钟
				max_size: 100 * 1024 * 1024, // 默认100MB
				allowed_formats: 'mp4,mov,avi,wmv', // 默认格式
				auto_approve: 0 // 默认需要审核
			},
			formData: {
				title: '',
				description: '',
				video_url: '',
				cover_url: '',
				duration: 0,
				width: 0,
				height: 0,
				size: 0
			}
		}
	},
	onLoad() {
		try {
			this.token = uni.getStorageSync('token') || '';
			if (!this.token) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});

				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					});
				}, 1500);
			} else {
				// 获取视频设置
				this.getVideoSettings();
			}
		} catch(e) {
			this.token = '';
		}
	},
	methods: {
		// 返回上一页
		back() {
			uni.navigateBack({
				delta: 1
			});
		},

		// 选择视频
		chooseVideo() {
			const that = this;

			uni.chooseVideo({
				sourceType: ['album', 'camera'],
				compressed: false,
				maxDuration: that.videoSettings.max_duration, // 使用动态设置
				success: (res) => {
					//console.log('选择视频成功:', res);

					// 检查视频时长
					if (res.duration > that.videoSettings.max_duration) {
						const minutes = Math.floor(that.videoSettings.max_duration / 60);
						uni.showToast({
							title: `视频时长不能超过${minutes}分钟`,
							icon: 'none'
						});
						return;
					}

					// 检查视频大小
					if (res.size > that.videoSettings.max_size) {
						const maxSizeMB = that.videoSettings.max_size / (1024 * 1024);
						uni.showToast({
							title: `视频大小不能超过${maxSizeMB}MB`,
							icon: 'none'
						});
						return;
					}

					// 上传视频
					that.uploadVideo(res.tempFilePath, res);
				}
			});
		},

		// 上传视频
		uploadVideo(filePath, videoInfo) {
			const that = this;
			that.uploading = true;

			uni.showLoading({
				title: '上传中...'
			});

			uni.uploadFile({
				url: that.$API.upload(),
				filePath: filePath,
				name: 'file',
				formData: {
					token: that.token
				},
				success: (uploadRes) => {
					try {
						const data = JSON.parse(uploadRes.data);

						if (data.code === 1) {
							// 上传成功
							that.formData.video_url = data.data.url;
							that.formData.duration = videoInfo.duration;
							that.formData.width = videoInfo.width;
							that.formData.height = videoInfo.height;
							that.formData.size = videoInfo.size;

							// 自动截取第一帧作为封面
							that.generateCover(filePath);
						} else {
							uni.showToast({
								title: data.msg || '视频上传失败',
								icon: 'none'
							});
						}
					} catch (e) {
						//console.error('解析上传响应失败:', e);
						uni.showToast({
							title: '视频上传失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					//console.error('视频上传失败:', err);
					uni.showToast({
						title: '视频上传失败',
						icon: 'none'
					});
				},
				complete: () => {
					that.uploading = false;
					uni.hideLoading();
				}
			});
		},

		// 生成视频封面
		generateCover(videoPath) {
			// 在某些平台上可能无法自动生成封面，这里使用默认图片
			// 实际应用中可以使用更复杂的方法来生成封面
			this.chooseCover();
		},

		// 选择封面图
		chooseCover() {
			const that = this;

			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					// 上传封面图
					that.uploadCover(res.tempFilePaths[0]);
				}
			});
		},

		// 上传封面图
		uploadCover(filePath) {
			const that = this;
			that.uploading = true;

			uni.showLoading({
				title: '上传中...'
			});

			uni.uploadFile({
				url: that.$API.upload(),
				filePath: filePath,
				name: 'file',
				formData: {
					token: that.token
				},
				success: (uploadRes) => {
					try {
						const data = JSON.parse(uploadRes.data);

						if (data.code === 1) {
							// 上传成功
							that.formData.cover_url = data.data.url;
						} else {
							uni.showToast({
								title: data.msg || '封面上传失败',
								icon: 'none'
							});
						}
					} catch (e) {
						//console.error('解析上传响应失败:', e);
						uni.showToast({
							title: '封面上传失败',
							icon: 'none'
						});
					}
				},
				fail: (err) => {
					//console.error('封面上传失败:', err);
					uni.showToast({
						title: '封面上传失败',
						icon: 'none'
					});
				},
				complete: () => {
					that.uploading = false;
					uni.hideLoading();
				}
			});
		},

		// 移除封面
		removeCover() {
			this.formData.cover_url = '';
		},

		// 提交表单
		submitForm() {
			if (!this.formData.video_url) {
				uni.showToast({
					title: '请先上传视频',
					icon: 'none'
				});
				return;
			}

			if (!this.formData.title) {
				uni.showToast({
					title: '请输入视频标题',
					icon: 'none'
				});
				return;
			}

			if (!this.formData.cover_url) {
				uni.showToast({
					title: '请上传视频封面',
					icon: 'none'
				});
				return;
			}

			const that = this;
			that.uploading = true;

			uni.showLoading({
				title: '提交中...'
			});

			// 使用表单数据格式发送请求
			uni.request({
				url: that.$API.PluginLoad('xqy_video'),
				data: {
					action: 'uploadVideo',
					plugin: 'xqy_video',
					upload_type: 'url',
					title: that.formData.title,
					description: that.formData.description,
					video_url: that.formData.video_url,
					cover_url: that.formData.cover_url,
					duration: that.formData.duration,
					width: that.formData.width,
					height: that.formData.height,
					size: that.formData.size,
					token: that.token
				},
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				success: function(res) {
					//console.log('上传响应成功:', res);
					if (res.data.code === 200) {
						uni.showToast({
							title: res.data.msg || '上传成功',
							icon: 'success'
						});

						// 返回上一页
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					} else {
						//console.log('上传响应失败:', res.data);
						uni.showToast({
							title: res.data.msg || '上传失败',
							icon: 'none'
						});
					}
				},
				fail: function(error) {
					//console.log('上传请求失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				},
				complete: function() {
					that.uploading = false;
					uni.hideLoading();
				}
			});
		},

		// 格式化时长
		formatDuration(seconds) {
			const minutes = Math.floor(seconds / 60);
			const remainingSeconds = Math.floor(seconds % 60);
			return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
		},

		// 格式化大小
		formatSize(bytes) {
			if (bytes === 0) return '0 B';

			const k = 1024;
			const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));

			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		},

		// 获取视频设置
		getVideoSettings() {
			const that = this;

			uni.request({
				url: that.$API.PluginLoad('xqy_video'),
				data: {
					action: 'getVideoSettings',
					plugin: 'xqy_video',
					token: that.token
				},
				method: 'POST',
				header: {
					'content-type': 'application/x-www-form-urlencoded'
				},
				success: function(res) {
					if (res.data.code === 200 && res.data.data) {
						// 更新视频设置
						const settings = res.data.data;
						if (settings.max_duration) {
							that.videoSettings.max_duration = parseInt(settings.max_duration);
						}
						if (settings.max_size_mb) {
							that.videoSettings.max_size = parseInt(settings.max_size_mb) * 1024 * 1024; // MB转字节
						}
						if (settings.allowed_formats) {
							that.videoSettings.allowed_formats = settings.allowed_formats;
						}
						if (settings.auto_approve !== undefined) {
							that.videoSettings.auto_approve = parseInt(settings.auto_approve);
						}
					}
				},
				fail: function(error) {
					console.log('获取视频设置失败:', error);
				}
			});
		}
	}
}
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background-color: #f6f6f6;

	.upload-form {
		padding: 20rpx;

		.video-preview {
			width: 100%;
			height: 400rpx;
			background-color: #000;
			margin-bottom: 30rpx;
			border-radius: 12rpx;
			overflow: hidden;

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

		.upload-btn {
			width: 100%;
			height: 400rpx;
			background-color: #f0f0f0;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-bottom: 30rpx;
			border-radius: 12rpx;
			border: 2rpx dashed #ddd;

			text:first-child {
				font-size: 80rpx;
				color: #999;
				margin-bottom: 20rpx;
			}

			text:last-child {
				font-size: 28rpx;
				color: #999;
			}
		}

		.form-content {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 30rpx;

			.form-item {
				margin-bottom: 30rpx;

				.form-label {
					font-size: 28rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}

				.form-input {
					width: 100%;
					height: 80rpx;
					background-color: #f6f6f6;
					border-radius: 8rpx;
					padding: 0 20rpx;
					font-size: 28rpx;
				}

				.form-textarea {
					width: 100%;
					height: 200rpx;
					background-color: #f6f6f6;
					border-radius: 8rpx;
					padding: 20rpx;
					font-size: 28rpx;
				}
			}

			.cover-preview {
				width: 100%;
				height: 200rpx;
				position: relative;
				border-radius: 8rpx;
				overflow: hidden;

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

				.cover-actions {
					position: absolute;
					bottom: 0;
					left: 0;
					right: 0;
					display: flex;
					background-color: rgba(0, 0, 0, 0.5);

					.cover-action {
						flex: 1;
						height: 60rpx;
						line-height: 60rpx;
						text-align: center;
						color: #fff;
						font-size: 24rpx;

						&:first-child {
							border-right: 1rpx solid rgba(255, 255, 255, 0.3);
						}
					}
				}
			}

			.cover-upload {
				width: 100%;
				height: 200rpx;
				background-color: #f0f0f0;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				border-radius: 8rpx;
				border: 2rpx dashed #ddd;

				text:first-child {
					font-size: 60rpx;
					color: #999;
					margin-bottom: 10rpx;
				}

				text:last-child {
					font-size: 24rpx;
					color: #999;
				}
			}

			.video-info {
				margin-bottom: 30rpx;

				.info-item {
					display: flex;
					margin-bottom: 10rpx;
					font-size: 24rpx;

					.info-label {
						color: #999;
					}

					.info-value {
						color: #333;
					}
				}
			}

			.submit-btn {
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				background-color: #0081ff;
				color: #fff;
				border-radius: 40rpx;
				font-size: 28rpx;
				margin-bottom: 30rpx;

				&[disabled] {
					background-color: #ccc;
				}
			}

			.tips {
				font-size: 24rpx;
				color: #999;

				text {
					display: block;
					line-height: 1.6;
				}

				text:first-child {
					margin-bottom: 10rpx;
				}
			}
		}
	}
}
</style>
