<template>
	<view class="page">
		<!-- 引入FontAwesome -->
		<view>
			<link rel="stylesheet"
				href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
		</view>

		<!-- 顶部导航栏 -->
		<view class="custom-navbar">
			<view class="navbar-left" @click="goBack">
				<text class="fa fa-angle-left"></text>
			</view>
			<view class="navbar-center">
				<view class="navbar-title">
					<image class="navbar-avatar" :src="myinfo.avatar" mode="aspectFill"></image>
					<text class="navbar-text">{{ myinfo.nickname }}</text>
					<text class="navbar-badge" v-if="myinfo.is_vip > 0">VIP</text>
				</view>
			</view>
			<view class="navbar-right" @click="showActionSheet">
				<text class="fa fa-ellipsis-h"></text>
			</view>
		</view>

		<!-- 内容头图区域 -->
		<view class="topUser">
			<image :src="home_image" class="home_image" mode="aspectFill"></image>

			<!-- 图片指示器 -->
			<!-- <view class="image-indicator" v-if="image_list.length > 1">
				<text>{{ selImg + 1 }}/{{ image_list.length }}</text>
			</view> -->

			<!-- 音乐类型时显示歌词 -->
			<view class="lyrics-overlay" v-if="queueDetail.task_type == 2" @mousedown="startDrag" @mouseup="stopDrag" @mousemove="drag">
				<text class="lyrics-text" ref="lyricsText" :style="{ transform: `translateY(${offsetY}px)` }">{{ queueDetail.description }}</text>
			</view>

			<!-- 音乐类型且状态为9时显示播放按钮 -->
			<view class="play-button" v-if="queueDetail.task_type == 2 && queueDetail.status >= 9" @click="toggleAudio">
				<text class="fa" :class="isPlaying ? 'fa-pause' : 'fa-play'"></text>
			</view>


		</view>

		<view class="body">
			<view class="article-header">
				<text class="title">{{ queueDetail.title }}</text>
				<view class="meta-info">
					<view class="meta-item">
						<text class="fa fa-clock-o"></text>
						<text class="meta-text">{{ queueDetail.create_time }}</text>
					</view>
					<view class="meta-item">
						<text class="fa fa-tag"></text>
						<text class="meta-text">{{ queueDetail.task_type == 1 ? '灵感创作' : '音乐创作' }}</text>
					</view>
					<view class="meta-item">
						<text class="fa fa-circle" :style="getStatusStyle(queueDetail.status)"></text>
						<text class="meta-text">{{ getStatusText(queueDetail.status) }}</text>
					</view>
				</view>
			</view>

			<view class="divider"></view>

			<view class="article-content">
				<!-- 灵感创作显示description -->
				<view v-if="queueDetail.task_type == 1">
					<text class="content">{{ queueDetail.description }}</text>
				</view>

				<!-- 音乐创作显示lyrics -->
				<view v-if="queueDetail.task_type == 2">
					<text class="content">{{ queueDetail.lyrics }}</text>
				</view>

				<!-- 显示创作详情 -->
				<view class="creation-details" v-if="queueDetail.task_type == 1">
					<view class="detail-item" v-if="queueDetail.action">
						<text class="detail-label">行为动作：</text>
						<text class="detail-value">{{ queueDetail.action }}</text>
					</view>
					<view class="detail-item" v-if="queueDetail.environment">
						<text class="detail-label">主体环境：</text>
						<text class="detail-value">{{ queueDetail.environment }}</text>
					</view>
					<view class="detail-item" v-if="queueDetail.subject">
						<text class="detail-label">主体形象：</text>
						<text class="detail-value">{{ queueDetail.subject }}</text>
					</view>
					<view class="detail-item" v-if="queueDetail.style">
						<text class="detail-label">参考风格：</text>
						<text class="detail-value">{{ queueDetail.style }}</text>
					</view>
				</view>

				<!-- 音乐创作显示歌曲名称 -->
				<view class="creation-details" v-if="queueDetail.task_type == 2">
					<view class="detail-item" v-if="queueDetail.song_name">
						<text class="detail-label">歌曲名称：</text>
						<text class="detail-value">{{ queueDetail.song_name }}</text>
					</view>
				</view>

				<!-- 显示状态信息 -->
				<view class="status-info" v-if="queueDetail.status < 4">
					<view class="queue-info">
						<text class="queue-text">队列位置:
							{{ queueDetail.queue_position }}/{{ queueDetail.all_position }}</text>
						<view class="progress-bar">
							<view class="progress-fill" :style="{ width: getProgressWidth() }"></view>
						</view>
					</view>
				</view>

				<!-- 显示错误信息 -->
				<view class="error-message" v-if="queueDetail.status == 3">
					<text class="error-text">{{ queueDetail.error_msg }}</text>
				</view>
			</view>
		</view>

		<view class="thread2"></view>

		<!-- 音频元素 -->
		<audio id="audioPlayer" :src="queueDetail.result_audio" style="display:none;"></audio>

		<!-- 底部漂浮栏 -->
		<view class="floating-bar" v-if="queueDetail.status == 9">
			<view class="floating-bar-content">
				<view class="add-note-btn" @click="showAddNotePopup">
					<text>添加说明</text>
				</view>
				<view class="publish-btn" @click="publishWork">
					<text>公布作品</text>
				</view>
			</view>
		</view>

		<!-- 添加说明弹窗 -->
		<view class="popup-mask" v-if="showNotePopup" @click="closeAddNotePopup"></view>
		<view class="note-popup" v-if="showNotePopup">
			<view class="popup-header">
				<text class="popup-title">添加说明</text>
			</view>
			<view class="popup-content">
				<textarea class="note-textarea" v-model="noteContent" placeholder="请描述你想添加的内容。"
					maxlength="500"></textarea>
				<view class="word-count">{{noteContent.length}}/500</view>
			</view>
			<view class="popup-footer">
				<view class="cancel-btn" @click="closeAddNotePopup">
					<text>取消</text>
				</view>
				<view class="confirm-btn" @click="confirmAddNote">
					<text>确认</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import previewImage from '@/components/kxj-previewImage/kxj-previewImage.vue'; //引用插件

	export default {
		components: {
			previewImage
		},
		data() {
			return {
				title: '',
				arcID: 0,
				selImg: 0,
				home_image: '',
				myinfo: {},
				tag_list: [],
				image_list: [],
				imgs: [],
				descs: [],
				isPlaying: false,
				audioPlayer: null,
				showNotePopup: false,
				noteContent: '',

				// 队列详情数据
				queueDetail: {
					id: 0,
					sso_id: 0,
					task_type: 1,
					title: '',
					description: '',
					action: '',
					environment: '',
					subject: '',
					style: '',
					song_name: '',
					lyrics: '',
					generate_uuid: '',
					result_images: '',
					result_audio: '',
					queue_position: 0,
					status: 1,
					generate_status: 1,
					points_cost: 0,
					error_msg: '',
					create_time: '',
					update_time: '',
					all_position: 0
				},
				myinfo: {},
				offsetY: 0,
				isDragging: false,
				startY: 0,
				initialOffsetY: 0
			}
		},
		onLoad(parms) {
			let self = this;
			this.arcID = parms.id || 3;
			this.getMyInfo();
		},
		onShow() {
			this.loadData();
		},
		onReady() {
			// 获取音频元素
			this.audioPlayer = uni.createInnerAudioContext();
			this.audioPlayer.onEnded(() => {
				this.isPlaying = false;
			});
		},
		onUnload() {
			// 页面卸载时停止音频播放
			if (this.audioPlayer) {
				this.audioPlayer.stop();
				this.audioPlayer.destroy();
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				});
			},
			getMyInfo() {
				uni.request({
					url: this.$apiHost + '/My/getnum',
					method: 'GET',
					header: {
						'content-type': 'application/json',
						'sign': getApp().globalData.headerSign
					},
					data: {
						uuid: getApp().globalData.uuid
					},
					success: (res) => {
						console.log("获取用户信息：", res.data);
						this.myinfo = res.data
					}
				})

			},
			selPhoto(item, sel) {
				this.selImg = sel;
				this.home_image = this.image_list[sel];
			},
			toArr(imgs) {
				let arr = imgs.split("|");
				return arr;
			},
			previewOpen(imgs1, index) {
				this.imgs = imgs1.split("|");
				setTimeout(() => this.$refs.previewImage.open(index), 0)
				// 传入当前选中的图片地址或序号
				return; //如需测试和uni原生预览差别可注释这两行
			},
			// 切换音频播放状态
			toggleAudio() {
				if (!this.queueDetail.result_audio) return;

				if (this.isPlaying) {
					this.audioPlayer.pause();
					this.isPlaying = false;
				} else {
					this.audioPlayer.src = this.queueDetail.result_audio;
					this.audioPlayer.play();
					this.isPlaying = true;
				}
			},
			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					1: '排队中',
					2: '生成中',
					3: '生成失败',
					4: '已完成',
					9: '已完成'
				};
				return statusMap[status] || '未知状态';
			},
			// 获取状态样式
			getStatusStyle(status) {
				const colorMap = {
					1: '#ffa500', // 橙色 - 排队中
					2: '#2979ff', // 蓝色 - 生成中
					3: '#ff5151', // 红色 - 生成失败
					4: '#4caf50', // 绿色 - 已完成
					9: '#4caf50' // 绿色 - 已完成
				};
				return `color: ${colorMap[status] || '#999'}`;
			},
			// 获取进度条宽度
			getProgressWidth() {
				if (this.queueDetail.all_position === 0) return '0%';
				const progress = (1 - (this.queueDetail.queue_position / this.queueDetail.all_position)) * 100;
				return `${progress}%`;
			},
			// 加载数据
			loadData() {
				uni.showLoading({
					title: '加载中...'
				});

				uni.request({
					url: this.$apiHost + '/WorkAI/getQueueDetail',
					data: {
						uuid: getApp().globalData.uuid,
						id: this.arcID
					},
					header: {
						"content-type": "application/json",
						'sign': getApp().globalData.headerSign
					},
					success: (res) => {
						console.log("队列详情:", res.data);
						if (res.data.success === "yes") {
							// 更新队列详情
							this.queueDetail = res.data.data;
							this.noteContent = res.data.data.content;

							// 更新图片列表
							if (this.queueDetail.result_images && this.queueDetail.result_images !== "") {
								this.image_list = this.queueDetail.result_images.split(",");
								this.home_image = this.image_list[0];
							} else {
								this.home_image = "../../static/home/avator.png";
							}

							// 如果是音频类型，设置音频源
							if (this.queueDetail.task_type == 2 && this.queueDetail.result_audio) {
								this.audioPlayer.src = this.queueDetail.result_audio;
							}
						} else {
							uni.showToast({
								title: '获取详情失败',
								icon: 'none'
							});
						}
					},
					complete: () => {
						uni.hideLoading();
					},
					fail: (e) => {
						console.log("请求失败:", e);
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						});
					}
				});
			},
			showActionSheet() {
				// 显示操作列表
				uni.showActionSheet({
					itemList: ['修改封面', '删除作品'],
					success: (res) => {
						switch (res.tapIndex) {
							case 0:
								// 修改封面
								this.editCover();
								break;
							case 1:
								// 删除作品
								this.deleteWork();
								break;
						}
					},
					fail: (res) => {
						console.log(res.errMsg);
					}
				});
			},
			// 修改封面
			editCover() {
				var _self = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success: function(res) {
						console.log('res:', res)
						if (res.tempFilePaths.length > 0) {
							_self.imglocal = res.tempFilePaths[0]
							const tempFilePaths = res.tempFilePaths[0];
							console.log('tempFilePaths:', tempFilePaths);
							const uploadTask = uni.uploadFile({
								url: _self.$apiHost + '/Xweb/upload_img?skey=' + _self.skey,
								filePath: res.tempFilePaths[0],
								name: 'file',
								success: function(uploadFileRes) {
									let resdata = JSON.parse(uploadFileRes.data)
									console.log('Success11:', uploadFileRes);
									console.log('Success21:', resdata);
									if (resdata.success == 'yes') {
										_self.home_image = resdata.url;
										// 调用修改封面接口
										uni.request({
											url: _self.$apiHost + '/WorkAI/queueAction',
											method: 'GET',
											data: {
												uuid: getApp().globalData.uuid,
												act: 'editImg',
												result_images: resdata.url,
												id: _self.arcID
											},
											header: {
												'content-type': 'application/json',
												'sign': getApp().globalData.headerSign
											},
											success: (res) => {
												if (res.data.success === "yes") {
													uni.showToast({
														title: '修改封面成功',
														icon: 'success'
													});
												} else {
													uni.showToast({
														title: '修改封面失败',
														icon: 'none'
													});
												}
											},
											fail: () => {
												uni.showToast({
													title: '修改封面失败',
													icon: 'none'
												});
											}
										});
									}
								},
								fail: function(uploadFileFail) {
									console.log('Error:', uploadFileFail.data);
									uni.showToast({
										title: '图片上传失败',
										icon: 'none'
									});
								}
							});
						}
					},
					error: function(e) {
						console.log(e);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},
			// 删除作品
			deleteWork() {
				// 显示确认对话框
				uni.showModal({
					title: '确认删除',
					content: '确定要删除这个作品吗？',
					confirmColor: '#ff5151',
					success: (res) => {
						if (res.confirm) {
							// 用户点击确定，执行删除操作
							this.confirmDelete();
						}
					}
				});
			},
			// 确认删除
			confirmDelete() {
				uni.showLoading({
					title: '删除中...'
				});

				uni.request({
					url: this.$apiHost + '/WorkAI/queueAction',
					method: 'GET',
					data: {
						uuid: getApp().globalData.uuid,
						act: 'del',
						id: this.arcID
					},
					header: {
						'content-type': 'application/json',
						'sign': getApp().globalData.headerSign
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.success === "yes") {
							uni.showToast({
								title: '删除成功',
								icon: 'success'
							});
							// 删除成功后返回上一页
							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								});
							}, 1500);
						} else {
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '删除失败',
							icon: 'none'
						});
					}
				});
			},
			// 显示添加说明弹窗
			showAddNotePopup() {
				this.showNotePopup = true;
			},
			// 关闭添加说明弹窗
			closeAddNotePopup() {
				this.showNotePopup = false;
			},
			// 确认添加说明
			confirmAddNote() {
				if (!this.noteContent.trim()) {
					uni.showToast({
						title: '请输入说明内容',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '保存中...'
				});

				uni.request({
					url: this.$apiHost + '/WorkAI/queueAction',
					method: 'GET',
					data: {
						uuid: getApp().globalData.uuid,
						act: 'editContent',
						content: this.noteContent,
						id: this.arcID
					},
					header: {
						'content-type': 'application/json',
						'sign': getApp().globalData.headerSign
					},
					success: (res) => {
						uni.hideLoading();
						if (res.data.success === "yes") {
							uni.showToast({
								title: '添加说明成功',
								icon: 'success'
							});
							this.showNotePopup = false;
							// this.noteContent = '';
							// 重新加载数据
							this.loadData();
						} else {
							uni.showToast({
								title: '添加说明失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '添加说明失败',
							icon: 'none'
						});
					}
				});
			},
			// 发布作品
			publishWork() {
				uni.showLoading({
					title: '发布中...'
				});

				uni.request({
					url: this.$apiHost + '/WorkAI/queueAction',
					method: 'GET',
					data: {
						uuid: getApp().globalData.uuid,
						act: 'fabu',
						id: this.arcID
					},
					header: {
						'content-type': 'application/json',
						'sign': getApp().globalData.headerSign
					},
					success: (res) => {
						console.log("resddd", res.data);
						uni.hideLoading();
						if (res.data.success === "yes") {
							uni.showToast({
								title: '发布成功',
								icon: 'success'
							});
							// 重新加载数据
							// this.loadData();
						} else {
							uni.showToast({
								title: res.data.str || '发布失败',
								icon: 'none'
							});
						}
					},
					fail: () => {
						uni.hideLoading();
						uni.showToast({
							title: '发布失败',
							icon: 'none'
						});
					}
				});
			},
			startDrag(event) {
				this.isDragging = true;
				this.startY = event.clientY;
				this.initialOffsetY = this.offsetY || 0;
			},
			stopDrag() {
				this.isDragging = false;
			},
			drag(event) {
				if (this.isDragging) {
					const deltaY = event.clientY - this.startY;
					const newOffsetY = this.initialOffsetY + deltaY;

					// Get the height of the lyrics text
					const lyricsTextHeight = this.$refs.lyricsText ? this.$refs.lyricsText.clientHeight : 0;


					// Define the threshold limits based on the height of the lyrics text
					const minY = -lyricsTextHeight + 20; // Allow some space above
					const maxY = 20;  // Allow some space below

					// Apply the limits
					this.offsetY = Math.min(Math.max(newOffsetY, minY), maxY);

					// Log the height and current offset
					console.log('Lyrics Text Height:', lyricsTextHeight);
					console.log('Current Offset Y:', this.offsetY);
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@import 'makeDetail.scss';
</style>