<template>
	<view class="task-upload">
		<!-- 任务头部信息 -->
		<view class="task-header">
			<view class="task-title">{{taskInfo.title}}</view>
			<view class="task-deadline">请于{{taskInfo.taskEndTime ? formatDate(taskInfo.taskEndTime) : ''}}之前上传任务，超时将自动取消</view>
		</view>
		
		<!-- 驳回原因提示(如果任务被驳回) -->
		<view class="reject-box" v-if="isRejected">
			<view class="reject-title">审核未通过原因：</view>
			<view class="reject-reason">{{taskInfo.examineText || '暂无驳回原因'}}</view>
		</view>
		
		<!-- 上传表单 -->
		<view class="upload-form">
			<!-- 链接输入 -->
			<view class="form-item">
				<view class="form-label">笔记/视频链接</view>
				<view class="form-input">
					<u-input v-model="formData.examineText" placeholder="请输入小红书/抖音等平台的笔记链接" />
				</view>
			</view>
			
			<!-- 图片上传 -->
			<view class="form-item">
				<view class="form-label">证明截图</view>
				<view class="form-notice">请上传任务完成的截图证明，例如发布成功的截图</view>
				<view class="upload-box">
					<u-upload
						:fileList="fileList"
						@afterRead="afterRead"
						@delete="deletePic"
						name="examineImage"
						multiple
						:maxCount="3"
					></u-upload>
				</view>
			</view>
			
			<!-- 提交按钮 -->
			<view class="submit-btn">
				<u-button type="primary" color="#ffaa48" shape="circle" @click="submitTaskHandler">提交审核</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import { getTaskDetail, submitTask } from "@/api/order/task.js"
	export default {
		data() {
			return {
				taskId: null,
				taskStatus: '',
				isRejected: false,
				taskInfo: {
					id: 0,
					title: '',
					taskEndTime: '',
					examineText: '',
					taskState: 0,
					examineState: 0
				},
				formData: {
					taskId: 0,
					examineImage: [],
					examineText: '',
				},
				fileList: []
			}
		},
		onLoad(options) {
			if (options.id) {
				this.taskId = options.id
				this.formData.taskId = options.id
				this.taskStatus = options.status || ''
				this.isRejected = this.taskStatus === 'REJECTED'
				this.getTaskDetail()
			} else {
				uni.showToast({
					title: '任务ID不存在',
					icon: 'none'
				})
				setTimeout(() => {
					uni.navigateBack()
				}, 1500)
			}
		},
		methods: {
			getTaskDetail() {
				// 获取任务详情
				getTaskDetail(this.taskId).then(res => {
					if (res && res.code === 200) {
						this.taskInfo = res.data

                        // 如果任务已有审核文本，填充到表单
                        if (res.data.examineText) {
                            this.formData.examineText = res.data.examineText;
                        }
                        
                        // 如果任务已有图片，添加到文件列表显示
                        if (res.data.examineImage) {
                            const imageUrls = res.data.examineImage.split(',');
                            imageUrls.forEach(url => {
                                if (url) {
                                    this.fileList.push({
                                        url: url,
                                        status: 'success',
                                        message: '已上传',
                                        isImage: true
                                    });
                                    // 同时更新formData中的图片数组
                                    this.formData.examineImage.push(url);
                                }
                            });
                        }
					}
				})
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let uploadTask = uni.uploadFile({
						url: 'https://store-test.catmdogd.com/test-api/h5/oss/upload',
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							if(res && res.data) {
								try {
									let resData = JSON.parse(res.data);
									if(resData.url) {
										resolve(resData.url);
									} else {
										reject("上传失败: 未获取到图片URL");
									}
								} catch(e) {
									reject("上传失败: 解析响应数据错误");
								}
							} else {
								reject("上传失败: 响应数据为空");
							}
						},
						fail: (err) => {
							reject("上传失败: " + (err.errMsg || JSON.stringify(err)));
						}
					});
					
					// 监听上传进度
					uploadTask.onProgressUpdate((res) => {
						// 查找当前正在上传的文件
						const index = this.fileList.findIndex(file => file.status === 'uploading');
						if(index !== -1) {
							// 更新上传进度信息
							this.fileList[index].message = '上传中 ' + res.progress + '%';
						}
					});
				})
			},
			formatDate(dateStr) {
				if (!dateStr) return '';
				let date = new Date(dateStr);
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			afterRead(event) {
				// 读取文件后的处理
				const { file } = event
				
				// 处理文件数组
				const fileList = Array.isArray(file) ? file : [file]
				
				// 遍历处理每个文件
				fileList.forEach(item => {
					// 更新UI显示上传中状态
					const fileListItem = {
						...item,
						status: 'uploading',
						message: '上传中'
					}
					this.fileList.push(fileListItem)
					const currentIndex = this.fileList.length - 1
					
					// 使用Promise上传图片
					this.uploadFilePromise(item.url)
						.then(url => {
							// 上传成功，更新状态和URL
							this.fileList[currentIndex].status = 'success'
							this.fileList[currentIndex].message = '上传成功'
							this.fileList[currentIndex].url = url
							// 保存上传后的URL
							this.formData.examineImage.push(url)
						})
						.catch(err => {
							// 上传失败
							this.fileList[currentIndex].status = 'failed'
							this.fileList[currentIndex].message = '上传失败'
							
							uni.showToast({
								title: '图片上传失败',
								icon: 'none'
							})
						})
				})
			},
			deletePic(event) {
				// 删除图片
				const index = event.index
				this.fileList.splice(index, 1)
				this.formData.examineImage.splice(index, 1)
			},
			submitTaskHandler() {
				// 表单验证
				if (!this.formData.examineText) {
					uni.showToast({
						title: '请输入笔记链接',
						icon: 'none'
					})
					return
				}
				
				if (this.formData.examineImage.length === 0) {
					uni.showToast({
						title: '请上传至少一张截图',
						icon: 'none'
					})
					return
				}
				
				// 检查是否有正在上传的图片
				const isUploading = this.fileList.some(file => file.status === 'uploading')
				if (isUploading) {
					uni.showToast({
						title: '图片正在上传中，请稍候',
						icon: 'none'
					})
					return
				}
				
				// 显示提交中提示
				uni.showLoading({
					title: '提交中...'
				})
				
				// 提交任务
				submitTask({
					id: this.taskId,
					taskId: this.formData.taskId,
					examineText: this.formData.examineText,
					examineImage: this.formData.examineImage.join(',')
				}).then(res => {
					uni.hideLoading()
					if (res && res.code === 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'success'
						})
						// 返回任务详情页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg || '提交失败',
							icon: 'none'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					uni.showToast({
						title: '提交失败',
						icon: 'none'
					})
					console.error('提交任务失败:', err)
				})
			}
		}
	}
</script>

<style lang="scss">
	.task-upload {
		background-color: #f5f5f7;
		min-height: 100vh;
		
		.task-header {
			background-color: #FFFFFF;
			padding: 30rpx;
			
			.task-title {
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.task-deadline {
				font-size: 24rpx;
				color: #999;
			}
		}
		
		.reject-box {
			background-color: #FFF1F0;
			margin-top: 20rpx;
			padding: 30rpx;
			
			.reject-title {
				font-size: 28rpx;
				font-weight: bold;
				color: #F5222D;
				margin-bottom: 10rpx;
			}
			
			.reject-reason {
				font-size: 26rpx;
				color: #F5222D;
			}
		}
		
		.upload-form {
			background-color: #FFFFFF;
			margin-top: 20rpx;
			padding: 30rpx;
			
			.form-item {
				margin-bottom: 40rpx;
				
				.form-label {
					font-size: 30rpx;
					font-weight: bold;
					color: #333;
					margin-bottom: 20rpx;
				}
				
				.form-notice {
					font-size: 24rpx;
					color: #999;
					margin-bottom: 20rpx;
				}
				
				.form-input {
					background-color: #F8F8F8;
					border-radius: 8rpx;
					padding: 10rpx;
				}
				
				.upload-box {
					margin-top: 20rpx;
				}
			}
			
			.submit-btn {
				margin-top: 60rpx;
				padding: 0 40rpx;
			}
		}
	}
</style>