<template>
	<view class="container">
		<!-- 会员信息卡片 -->
		<view class="member-card">
			<view class="member-info">
				<view class="member-avatar">👤</view>
				<view class="member-details">
					<view class="member-name">{{ memberName }}</view>
					<view class="member-id">消费记录ID: {{ consumeId }}</view>
				</view>
			</view>
		</view>

		<!-- 表单卡片 -->
		<view class="form-card">
			<view class="form-content">
				<form @submit="handleFormSubmit">
					<!-- 使用前图片 -->
					<view class="form-group">
						<text class="form-label">使用前图片</text>
						<view class="input-wrapper">
							<view class="file-upload-area" @tap.stop="chooseFile('before')">
								<view class="file-upload-text">
									<text class="file-upload-icon">📷</text>
									<text>点击选择使用前图片</text>
								</view>
								<view class="file-list">
									<view v-for="(file, index) in beforeImages" :key="file.id || index" class="file-item">
										<view class="file-info">
											<text class="file-icon">🖼️</text>
											<text class="file-name">{{ file.name }}</text>
										</view>
										<view class="file-actions">
											<view v-if="file.status === 'uploading'" class="file-status uploading">上传中...</view>
											<view v-else-if="file.status === 'success'" class="file-status success">✓ 已上传</view>
											<view v-else-if="file.status === 'error'" class="file-status error">✗ 上传失败</view>
											<button v-if="file.status === 'success'" class="btn-error" @click.stop="removeFile('before', index)">删除</button>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 使用后图片 -->
					<view class="form-group">
						<text class="form-label">使用后图片</text>
						<view class="input-wrapper">
							<view class="file-upload-area" @tap.stop="chooseFile('after')">
								<view class="file-upload-text">
									<text class="file-upload-icon">📷</text>
									<text>点击选择使用后图片</text>
								</view>
								<view class="file-list">
									<view v-for="(file, index) in afterImages" :key="file.id || index" class="file-item">
										<view class="file-info">
											<text class="file-icon">🖼️</text>
											<text class="file-name">{{ file.name }}</text>
										</view>
										<view class="file-actions">
											<view v-if="file.status === 'uploading'" class="file-status uploading">上传中...</view>
											<view v-else-if="file.status === 'success'" class="file-status success">✓ 已上传</view>
											<view v-else-if="file.status === 'error'" class="file-status error">✗ 上传失败</view>
											<button v-if="file.status === 'success'" class="btn-error" @click.stop="removeFile('after', index)">删除</button>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>

					<!-- 反馈备注 -->
					<view class="form-group">
						<text class="form-label">反馈备注</text>
						<view class="input-wrapper">
							<textarea v-model="formData.remark" placeholder="请输入反馈备注" :maxlength="500" :count="true"
								class="textarea-input" />
						</view>
					</view>

					<!-- 科技部备注 -->
					<view class="form-group">
						<text class="form-label">科技部备注</text>
						<view class="input-wrapper">
							<textarea v-model="formData.kjbRemark" placeholder="请输入科技部备注" :maxlength="500" :count="true"
								class="textarea-input" />
						</view>
					</view>

					<!-- 提交按钮 -->
					<view class="btn-group">
						<button type="submit" class="btn btn-primary" :style="{opacity: isSubmitting?0.5:1}" @tap="isSubmitting?null:submitServiceLog()">
							{{ isSubmitting?(isEditMode?'更新中...':'提交中...'):(isEditMode?'更新服务日志':'提交服务日志') }}
						</button>
					</view>
				</form>
			</view>
		</view>
	</view>
</template>

<script>
	import lxApi from '@/apis/modules/lx.js'
	import config from '@/common/config.js'
	
	export default {
		data() {
			return {
				consumeId: '',
				memberName: '',
				logId: '',
				isEditMode: false,
				isSubmitting: false,
				baseUrl: '',
				formData: {
					remark: '',
					kjbRemark: ''
				},
				beforeImages: [],
				afterImages: []
			}
		},
		onLoad(options) {
			// 获取传递的参数
			this.consumeId = options.consumeId || ''
			this.memberName = decodeURIComponent(options.memberName || '未知会员')
			this.logId = options.logId || ''
			this.isEditMode = options.mode === 'edit'
			
			// 初始化基础URL
			this.baseUrl = config.getApiBaseUrl()
			
			// 如果是编辑模式，加载现有数据
			if (this.isEditMode && this.logId) {
				this.loadServiceLogDetail()
			}
		},
		methods: {
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},

			// 加载服务日志详情（编辑模式）
			async loadServiceLogDetail() {
				try {
					uni.showLoading({
						title: '加载中...'
					})
					
					const result = await lxApi.getServiceLogDetail(this.logId)
					uni.hideLoading()
					
					if (result.code === 200 && result.data) {
						const log = result.data
						
						// 填充表单数据
						this.formData.remark = log.remark || ''
						this.formData.kjbRemark = log.kjbRemark || ''
						
						// 加载图片数据
						this.beforeImages = this.parseImageJson(log.beforeImage)
						this.afterImages = this.parseImageJson(log.afterImage)
					} else {
						uni.showToast({
							title: result.msg || '加载失败',
							icon: 'none'
						})
					}
				} catch (error) {
					uni.hideLoading()
					console.error('加载服务日志详情失败:', error)
					uni.showToast({
						title: '加载失败，请稍后重试',
						icon: 'none'
					})
				}
			},

			// 解析图片JSON字符串
			parseImageJson(imageJson) {
				try {
					if (!imageJson) return []
					const images = JSON.parse(imageJson)
					// 将现有图片转换为文件列表格式
					return images.map((image, index) => ({
						id: `existing_${Date.now()}_${index}`,
						name: image.name || image.fileId || `图片${index + 1}`,
						size: 0,
						type: 'image/jpeg',
						status: 'success',
						url: image.url || '',
						fileId: image.fileId || image.name || ''
					}))
				} catch (error) {
					console.error('解析图片JSON失败:', error)
					return []
				}
			},

			// 选择文件
			chooseFile(type) {
				uni.chooseImage({
					count: 9,
					success: (res) => {
						// 将tempFilePaths转换为tempFiles格式
						const tempFiles = res.tempFilePaths.map((path, index) => ({
							path: path,
							tempFilePath: path,
							size: res.tempFiles ? res.tempFiles[index].size : 0,
							name: `image_${Date.now()}_${index}.jpg`,
							type: 'image/jpeg'
						}));
						this.handleFileSelect(tempFiles, type);
					}
				});
			},

			// 处理文件选择
			async handleFileSelect(files, type) {
				for (let i = 0; i < files.length; i++) {
					const file = files[i];

					// 验证文件大小 (限制为10MB)
					if (file.size > 10 * 1024 * 1024) {
						uni.showToast({
							title: `文件 ${file.name} 大小超过10MB限制`,
							icon: 'none'
						});
						continue;
					}

					// 上传文件
					await this.uploadSingleFile(file, type);
				}
			},

			// 上传单个文件
			async uploadSingleFile(file, type) {
				const fileId = `file_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

				// 添加到文件列表显示
				this.addFileToList(file, fileId, 'uploading', type);

				try {
					const result = await lxApi.uploadFile(file);

					if (result.code === 200 && result.data) {
						// 更新文件状态为成功
						this.updateFileStatus(fileId, 'success', type, result.data);

						uni.showToast({
							title: '文件上传成功',
							icon: 'success'
						});
					} else {
						throw new Error(result.msg || '上传失败');
					}
				} catch (error) {
					console.error('文件上传失败:', error);
					this.updateFileStatus(fileId, 'error', type);
					uni.showToast({
						title: `文件 ${file.name} 上传失败`,
						icon: 'none'
					});
				}
			},

			// 添加文件到列表显示
			addFileToList(file, fileId, status, type) {
				const fileItem = {
					id: fileId,
					name: file.name,
					size: file.size,
					type: file.type,
					status: status,
					url: '',
					fileId: ''
				};

				if (type === 'before') {
					this.beforeImages.push(fileItem);
				} else {
					this.afterImages.push(fileItem);
				}
			},

			// 更新文件状态
			updateFileStatus(fileId, status, type, uploadData = null) {
				const fileList = type === 'before' ? this.beforeImages : this.afterImages;
				const fileIndex = fileList.findIndex(file => file.id === fileId);

				if (fileIndex !== -1) {
					fileList[fileIndex].status = status;
					if (uploadData) {
						fileList[fileIndex].url = uploadData.url;
						fileList[fileIndex].fileId = uploadData.name;
						fileList[fileIndex].name = uploadData.name;
					}
				}
			},

			// 删除文件
			removeFile(type, index) {
				if (type === 'before') {
					this.beforeImages.splice(index, 1);
				} else {
					this.afterImages.splice(index, 1);
				}
			},

			// 表单提交
			handleFormSubmit(event) {
				event.preventDefault();
				this.submitServiceLog();
			},

			// 提交服务日志
			async submitServiceLog() {
				try {
					// 验证表单
					if (!this.formData.remark.trim()) {
						uni.showToast({
							title: '请输入反馈备注',
							icon: 'none'
						});
						return;
					}

					// 检查是否有图片正在上传
					const uploadingBefore = this.beforeImages.some(file => file.status === 'uploading');
					const uploadingAfter = this.afterImages.some(file => file.status === 'uploading');
					
					if (uploadingBefore || uploadingAfter) {
						uni.showToast({
							title: '请等待图片上传完成',
							icon: 'none'
						});
						return;
					}

					// 准备提交数据
					const submitData = {
						consumeId: this.consumeId,
						beforeImage: JSON.stringify(this.beforeImages.filter(file => file.status === 'success').map(file => ({
							name: file.name,
							url: file.url,
							fileId: file.fileId
						}))),
						afterImage: JSON.stringify(this.afterImages.filter(file => file.status === 'success').map(file => ({
							name: file.name,
							url: file.url,
							fileId: file.fileId
						}))),
						remark: this.formData.remark,
						kjbRemark: this.formData.kjbRemark
					};

					this.isSubmitting = true;
					uni.showLoading({
						title: this.isEditMode ? '正在更新...' : '正在提交...'
					});

					let result;
					if (this.isEditMode && this.logId) {
						// 编辑模式：调用更新接口
						result = await lxApi.updateServiceLog({...submitData, id: this.logId});
					} else {
						// 新增模式：调用创建接口
						result = await lxApi.createServiceLog(submitData);
					}
					uni.hideLoading();

					if (result.code === 200) {
						uni.showToast({
							title: this.isEditMode ? '服务日志更新成功！' : '服务日志提交成功！',
							icon: 'success'
						});
						
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack({
								delta: 1
							});
						}, 1500);
					} else {
						uni.showToast({
							title: result.msg || (this.isEditMode ? '更新失败！' : '提交失败！'),
							icon: 'none'
						});
					}
				} catch (error) {
					uni.hideLoading();
					console.error('提交失败:', error);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					});
				} finally {
					this.isSubmitting = false;
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		// height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 40rpx;
		box-sizing: border-box;
	}

	.member-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		padding: 40rpx;
		margin-bottom: 40rpx;
	}

	.member-info {
		display: flex;
		align-items: center;
	}

	.member-avatar {
		width: 80rpx;
		height: 80rpx;
		background: linear-gradient(135deg, #4caf50 0%, #66bb6a 100%);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		margin-right: 24rpx;
	}

	.member-details {
		flex: 1;
	}

	.member-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #2e7d32;
		margin-bottom: 8rpx;
	}

	.member-id {
		font-size: 24rpx;
		color: #6a9c6a;
	}

	.form-card {
		background: #fff;
		border-radius: 32rpx;
		box-shadow: 0 8rpx 32rpx rgba(76, 175, 80, 0.1);
		overflow: hidden;
		flex: 1;
	}

	.form-content {
		padding: 48rpx;
	}

	.form-group {
		margin-bottom: 40rpx;
	}

	.form-group:last-child {
		margin-bottom: 0;
	}

	.form-label {
		display: block;
		margin-bottom: 16rpx;
		font-weight: bold;
		color: #388e3c;
		letter-spacing: 2rpx;
		font-size: 28rpx;
	}

	.input-wrapper {
		position: relative;
	}

	.textarea-input {
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #2e7d32;
		min-height: 200rpx;
		box-sizing: border-box;
		width: 100%;
	}

	/* 文件上传样式 */
	.file-upload-area {
		border: 4rpx dashed #c8e6c9;
		border-radius: 24rpx;
		padding: 48rpx;
		text-align: center;
		background: linear-gradient(135deg, #f9fff9 0%, #e8f5e9 100%);
		cursor: pointer;
		min-height: 240rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		position: relative;
		overflow: hidden;
	}

	.file-upload-text {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 24rpx;
		color: #6a9c6a;
		font-size: 19rpx;
		position: relative;
		z-index: 1;
	}

	.file-upload-icon {
		font-size: 50rpx;
		opacity: 0.8;
	}

	.file-list {
		margin-top: 32rpx;
		text-align: left;
		max-height: 400rpx;
		overflow-y: auto;
	}

	.file-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 24rpx;
		background: #fff;
		border: 1rpx solid #e8f5e9;
		border-radius: 12rpx;
		margin-bottom: 12rpx;
		font-size: 26rpx;
		box-shadow: 0 2rpx 8rpx rgba(67, 233, 123, 0.08);
		transition: all 0.3s ease;
	}

	.file-info {
		display: flex;
		align-items: center;
		gap: 20rpx;
		overflow: hidden;
		width: 40%;
	}

	.file-icon {
		font-size: 32rpx;
		width: 56rpx;
		height: 56rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #f9fff9 0%, #e8f5e9 100%);
		border-radius: 10rpx;
		flex-shrink: 0;
		border: 1rpx solid #c8e6c9;
	}

	.file-name {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		line-height: 1.4;
	}

	.file-actions {
		display: flex;
		align-items: center;
		gap: 12rpx;
		flex-shrink: 0;
		width: 55%;
	}

	.file-status {
		font-size: 22rpx;
		padding: 6rpx 12rpx;
		border-radius: 6rpx;
		font-weight: 500;
		white-space: nowrap;
	}

	.file-status.success {
		color: #2e7d32;
		background: #e8f5e9;
		border: 1rpx solid #c8e6c9;
	}

	.file-status.error {
		color: #c62828;
		background: #ffebee;
		border: 1rpx solid #ffcdd2;
	}

	.file-status.uploading {
		color: #ef6c00;
		background: #fff3e0;
		border: 1rpx solid #ffe0b2;
	}

	.btn-error {
		background: #f44336;
		color: #fff;
		border: none;
		border-radius: 6rpx;
		font-size: 20rpx;
	}

	.btn-group {
		display: flex;
		gap: 24rpx;
		margin-top: 48rpx;
	}

	.btn {
		flex: 1;
		padding: 10rpx 40rpx;
		border: none;
		border-radius: 20rpx;
		font-size: 28rpx;
		font-weight: bold;
		cursor: pointer;
		transition: all 0.2s ease;
		letter-spacing: 2rpx;
	}

	.btn-primary {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		box-shadow: 0 4rpx 16rpx rgba(67, 233, 123, 0.3);
	}

	.btn-primary:hover {
		box-shadow: 0 8rpx 32rpx rgba(67, 233, 123, 0.4);
		transform: translateY(-2rpx);
	}
</style>
