<template>
	<view class="page padding">
		<view class="padding bg-white radius">
			<view class="text-gray margin-bottom">整改记录</view>
			<view class="padding solid radius">
				<view class="flex">
					<view>整改方案：</view>
					<view>{{ rectifyData.rectifyPlan || '暂无' }}</view>
				</view>
				<view class="flex margin-top-sm">
					<view>完成情况：</view>
					<view>{{ rectifyData.rectifyResult || '暂无' }}</view>
				</view>
				<view class="margin-top-sm">
					<view>整改附件：</view>
					<view class="flex margin-top-xs" style="flex-wrap: wrap; gap: 10rpx;" v-if="rectifyAttachments.length > 0">
						<image v-for="(img, idx) in rectifyAttachments" :key="idx" :src="getFullPath(img.filePath)" style="width: 136rpx;height: 136rpx;border-radius: 16rpx;" mode="aspectFill" @click="previewImage(idx)"></image>
					</view>
					<view v-else class="text-gray text-sm margin-top-xs">暂无附件</view>
				</view>
			</view>
			<view class="flex margin-bottom margin-top">
				<view class="text-gray">验收结果</view>
				<view class="text-red">*</view>
			</view>
			<view class="flex" style="gap: 20rpx;">
				<button :class="['result-btn', formData.result === 1 ? 'active' : '']" @click="formData.result = 1">通过</button>
				<button :class="['result-btn', formData.result === 2 ? 'active' : '']" @click="formData.result = 2">不通过</button>
			</view>
			<view class="flex margin-bottom margin-top">
				<view class="text-gray">验收备注</view>
			</view>
			<up-textarea v-model="formData.verifyRemark" placeholder="请输入验收备注"></up-textarea>
			<view class="flex margin-bottom margin-top">
				<view class="text-gray">验收图片/视频</view>
			</view>
			<up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="10"></up-upload>
			<view class="flex margin-top-xl" style="gap: 20rpx;">
				<button class="round flex-sub" @click="handleCancel">取消</button>
				<button class="bg-blue round flex-sub" @click="handleSubmit">提交验收</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import { acceptanceRectification, getHiddenDangerDetail } from '@/request/api.js';
	import { baseUrl,getToken } from '@/request/request.js';
	
	// 页面参数
	const rectifyId = ref('');
	const hazardId = ref('');
	const assignId = ref('');
	
	// 整改记录数据
	const rectifyData = reactive({
		rectifyPlan: '',
		rectifyResult: ''
	});
	
	// 整改附件
	const rectifyAttachments = ref([]);
	
	// 表单数据
	const formData = reactive({
		result: 1, // 验收结果 1.通过 2.不通过
		verifyRemark: '' // 验收备注
	});
	
	const fileList1 = ref([]);
	
	// 获取完整图片路径
	const getFullPath = (filePath) => {
		if (!filePath) return '';
		if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
			return filePath;
		}
		return baseUrl + filePath;
	};
	
	// 图片预览
	const previewImage = (index) => {
		const urls = rectifyAttachments.value.map(item => getFullPath(item.filePath));
		uni.previewImage({
			current: index,
			urls: urls
		});
	};
	
	// 获取隐患详情
	const fetchDetail = async () => {
		if (!hazardId.value || !assignId.value) return;
		
		try {
			const res = await getHiddenDangerDetail({ hazardId: hazardId.value, assignId: assignId.value });
			if (res.code === 0 && res.data) {
				// 提取整改信息：assigns[0].rectify
				if (res.data.assigns && res.data.assigns.length > 0) {
					const assign = res.data.assigns[0];
					if (assign.rectify) {
						rectifyData.rectifyPlan = assign.rectify.rectifyPlan || '';
						rectifyData.rectifyResult = assign.rectify.rectifyResult || '';
						if (assign.rectify.attachments) {
							rectifyAttachments.value = assign.rectify.attachments;
						}
						console.log('整改记录:', rectifyData);
						console.log('整改附件:', rectifyAttachments.value);
					}
				}
			} else {
				uni.showToast({ title: res.msg || '获取详情失败', icon: 'none' });
			}
		} catch (error) {
			console.error('获取隐患详情失败:', error);
			uni.showToast({ title: '请求失败', icon: 'none' });
		}
	};
	
	onLoad((options) => {
		if (options.rectifyId) {
			rectifyId.value = options.rectifyId;
		}
		if (options.hazardId) {
			hazardId.value = options.hazardId;
		}
		if (options.assignId) {
			assignId.value = options.assignId;
		}
		console.log('验收页面参数:', { rectifyId: rectifyId.value, hazardId: hazardId.value, assignId: assignId.value });
		
		// 获取隐患详情
		fetchDetail();
	});
	
	// 取消
	const handleCancel = () => {
		uni.navigateBack();
	};
	
	// 提交验收
	const handleSubmit = async () => {
		if (!rectifyId.value) {
			uni.showToast({
				title: '缺少整改ID',
				icon: 'none'
			});
			return;
		}
		
		// 构建附件列表
		const attachments = fileList1.value.map(file => {
			let url = '';
			if (typeof file.url === 'string') {
				url = file.url;
			} else if (file.url && typeof file.url === 'object') {
				url = file.url.url || file.url.path || '';
			}
			const fileName = (typeof url === 'string' && url) ? url.split('/').pop() : (file.name || '');
			return {
				fileName: fileName || '',
				filePath: url || '',
				fileType: file.type || 'image/png',
				fileSize: file.size || 0
			};
		});
		
		const params = {
			rectifyId: Number(rectifyId.value),
			result: formData.result,
			verifyRemark: formData.verifyRemark || '',
			attachments: attachments
		};
		
		console.log('提交验收参数:', params);
		
		try {
			const res = await acceptanceRectification(params);
			if (res.code === 0) {
				uni.showToast({
					title: '验收成功',
					icon: 'success'
				});
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			} else {
				uni.showToast({
					title: res.msg || '验收失败',
					icon: 'none'
				});
			}
		} catch (error) {
			console.error('验收失败:', error);
			uni.showToast({
				title: '请求失败',
				icon: 'none'
			});
		}
	};
	
	// 删除图片
	const deletePic = (event) => {
	  fileList1.value.splice(event.index, 1);
	};
	
	// 新增图片
	const afterRead = async (event) => {
	  let lists = [].concat(event.file);
	  let fileListLen = fileList1.value.length;
	  lists.map((item) => {
	    fileList1.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	  for (let i = 0; i < lists.length; i++) {
	    const result = await uploadFilePromise(lists[i].url);
	    let item = fileList1.value[fileListLen];
	    fileList1.value.splice(fileListLen, 1, {
	      ...item,
	      status: 'success',
	      message: '',
	      url: result,
	    });
	    fileListLen++;
	  }
	};
	
	const uploadFilePromise = (filePath) => {
	  return new Promise((resolve, reject) => {
			uni.uploadFile({
	      url: baseUrl + '/frontend/attachment/upload',
				filePath: filePath,
	      name: 'file',
				header: {
					'Authorization': getToken()
	      },
	      success: (res) => {
					const data = JSON.parse(res.data);
					if (data.code === 0) {
						resolve(data.data);
					} else {
						reject(data.msg || '上传失败');
					}
				},
				fail: (err) => {
					console.error('上传失败:', err);
					reject(err);
				}
	    });
	  });
	};
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: #EBF2FC;
	}
	
	.result-btn {
		flex: 1;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 8rpx;
		background: #f5f5f5;
		color: #666;
		font-size: 28rpx;
		
		&::after {
			border: none;
		}
		
		&.active {
			background: #2667E9;
			color: #fff;
		}
	}
</style>
