<template>
	<view class="page padding">
		<view class="padding bg-white radius">
			<view class="flex margin-bottom">
				<view class="text-gray">整改方案</view>
				<view class="text-red">*</view>
			</view>
			<up-textarea v-model="formData.rectifyPlan" placeholder="请输入内容"></up-textarea>
			<view class="flex margin-bottom margin-top">
				<view class="text-gray">整改完成情况</view>
				<view class="text-red">*</view>
			</view>
			<up-textarea v-model="formData.rectifyResult" placeholder="请输入内容"></up-textarea>
			<view class="flex margin-bottom">
				<view class="text-gray margin-top">投资资金(计划)</view>
				<view class="text-red">*</view>
			</view>
			<up-input v-model="formData.planCost" placeholder="请输入内容" type="number"></up-input>
			<view class="flex margin-bottom">
				<view class="text-gray margin-top">投资资金(实际)</view>
				<view class="text-red">*</view>
			</view>
			<up-input v-model="formData.actualCost" placeholder="请输入内容" type="number"></up-input>
			<view class="flex margin-bottom">
				<view class="text-gray margin-top">限定整改时间</view>
				<view class="text-red">*</view>
			</view>
			<up-datetime-picker hasInput :show="show" v-model="value1" mode="date"></up-datetime-picker>
			<view class="flex margin-bottom margin-top">
				<view class="text-gray">整改人员</view>
				<view class="text-red">*</view>
				<view class="margin-left-sm text-black" v-if="selectedUserName">{{ selectedUserName }}</view>
			</view>
			<up-select v-model:current="cateId" :options="cateList" @select="selectItem"></up-select>
			
			<view class="flex margin-bottom">
				<view class="text-gray">整改图片/视频</view>
				<view class="text-red">*</view>
			</view>
			<up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
				:maxCount="10"></up-upload>
			<button class="bg-blue round margin-top-xl" @click="handleSubmit">提交整改</button>
		</view>
	</view>
</template>

<script setup>
	import {ref,reactive,onMounted} from 'vue'
	import {onLoad} from '@dcloudio/uni-app'
	import {submitRectification,getDepartmentPersonUsers} from '@/request/api.js'
	import {baseUrl,getToken} from '@/request/request.js'

	// 从页面参数获取的ID
	const hazardId = ref('');
	const assignId = ref('');

	// 表单数据
	const formData = reactive({
		rectifyPlan: '', // 整改方案
		rectifyResult: '', // 整改完成情况
		planCost: '', // 投资资金(计划)
		actualCost: '' // 投资资金(实际)
	});

	const show = ref(false);
	const value1 = ref(Date.now());
	const radiovalue1 = ref('');

	// 整改人员 
	const cateId = ref('')
	const cateList = ref([])
	const selectedUserName = ref('')  // 选中的人员名称
	
	// 获取部门人员列表
	const fetchDeptUsers = async () => {
		try {
			const res = await getDepartmentPersonUsers();
			if (res.code === 0 && res.data) {
				// 将部门下的用户数据扁平化为 up-select 需要的格式
				const userList = [];
				res.data.forEach(dept => {
					if (dept.users && dept.users.length > 0) {
						dept.users.forEach(user => {
							userList.push({
								id: String(user.userId),
								name: `${user.nickName}（${dept.deptName}）`
							});
						});
					}
				});
				cateList.value = userList;
				console.log('整改人员列表:', cateList.value);
			}
		} catch (error) {
			console.error('获取部门人员失败:', error);
		}
	};
	
	// 页面加载时获取人员列表
	fetchDeptUsers();

	// 上传图片
	const fileList1 = ref([]);

	// 删除图片
	const deletePic = (event) => {
		fileList1.value.splice(event.index, 1);
	};

	// 新增图】片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		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);
				}
			});
		});
	};

	// 提交整改
	const handleSubmit = async () => {
		if (!formData.rectifyPlan) {
			uni.showToast({
				title: '请输入整改方案',
				icon: 'none'
			});
			return;
		}
		if (!formData.rectifyResult) {
			uni.showToast({
				title: '请输入整改完成情况',
				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 = {
			hazardId: hazardId.value,
			assignId: assignId.value,
			rectifyPlan: formData.rectifyPlan,
			rectifyResult: formData.rectifyResult,
			planCost: Number(formData.planCost) || 0,
			actualCost: Number(formData.actualCost) || 0,
			attachments: attachments
		};

		try {
			const res = await submitRectification(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'
			});
		}
	};

	onLoad((options) => {
		if (options.hazardId) {
			hazardId.value = options.hazardId;
		}
		if (options.assignId) {
			assignId.value = options.assignId;
		}
	});
	// 选择整改人员
	const selectItem = (item) => {
		console.log('选择的整改人员:', item);
		cateId.value = item.id;
		selectedUserName.value = item.name;  // 显示选中的人员名称
	};
</script>

<style lang="scss" scoped>
	.page {
		min-height: 100vh;
		background: #EBF2FC;
	}

	.date-input {
		background: #fff;
		border-radius: 8rpx;
		padding: 24rpx 20rpx;
		margin-bottom: 20rpx;
		border: 1rpx solid #F6F6F6;

		text {
			font-size: 28rpx;
			color: #333;
		}
	}
</style>