<template>
	<view class="padding page">
		<view class="padding bg-white radius margin-bottom" v-for="(item,index) in hazardList" :key="index">
			<view class="flex justify-between margin-bottom">
				<view class="text-bold text-black">{{item.hazardTitle}}</view>
				<view>{{item.statusName}}</view>
			</view>
			<view class="flex margin-bottom">
				<view class="text-gray">隐患日期：</view>
				<view class="text-black">{{item.hazardCreatedAt}}</view>
			</view>
			<view class="flex margin-bottom">
				<view class="text-gray">责任单位：</view>
				<view class="text-black">{{item.responsibleDeptName}}</view>
			</view>
			<view class="flex margin-bottom">
				<view class="text-gray">判定人员：</view>
				<view class="text-black">{{item.responsiblePerson}}</view>
			</view>
			<view class="flex margin-bottom">
				<view class="text-gray">创建时间：</view>
				
				<view class="text-black">{{item.createdAt}}</view>
			</view>
			<view class="flex justify-between">
				<view></view>
				<view><button class="bg-blue round cu-btn lg" @click="editor()">查看详情</button></view>
			</view>
		</view>
		<button class="cuIcon-add bg-blue round margin-top" @click="openAddPopup">新增</button>
		<!-- 弹出框 -->
		<u-popup :show="showAddPopup" mode="center" round="20" @close="showAddPopup = false">
			<view class="popup-content">
				<view class="popup-header">
					<view class="popup-title text-bold">新增销号申请</view>
					<view class="popup-close" @click="showAddPopup = false">×</view>
				</view>
				<scroll-view class="popup-body" scroll-y :style="{ height: '60vh' }">
					<view class="flex margin-bottom">
						<view>隐患</view>
						<view class="text-red">*</view>
					</view>
					<view class="picker-input" @click="showHazardPicker = true">
						<text :class="selectedHazard ? '' : 'text-gray'">{{ selectedHazard || '请选择隐患' }}</text>
					</view>
					<up-picker 
						:show="showHazardPicker" 
						:columns="hazardColumns" 
						@confirm="onHazardConfirm"
						@cancel="showHazardPicker = false"
						@close="showHazardPicker = false"
					></up-picker>

					<view class="flex margin-bottom margin-top">
						<view>整改时限</view>
					</view>
					<view class="picker-input" @click="showDatePicker = true">
						<text :class="formData.rectifyDeadline ? '' : 'text-gray'">{{ formData.rectifyDeadline || '请选择整改时限' }}</text>
					</view>
					<up-datetime-picker 
						:show="showDatePicker" 
						v-model="dateValue" 
						mode="datetime"
						@confirm="onDateConfirm"
						@cancel="showDatePicker = false"
						@close="showDatePicker = false"
					></up-datetime-picker>
					<view class="margin-bottom margin-top">隐患治理责任单位</view>
					<view class="picker-input" @click="showDeptPicker = true">
						<text :class="selectedDeptName ? '' : 'text-gray'">{{ selectedDeptName || '请选择隐患治理责任单位' }}</text>
					</view>
					<up-picker 
						:show="showDeptPicker" 
						:columns="deptColumns" 
						@confirm="onDeptConfirm"
						@cancel="showDeptPicker = false"
						@close="showDeptPicker = false"
					></up-picker>
					<view class="margin-bottom margin-top">主要负责人</view>
					<up-input v-model="formData.responsiblePerson" placeholder="请输入主要负责人"></up-input>
					<view class="margin-bottom margin-top">主要治理内容</view>
					<up-textarea v-model="formData.mainTreatmentContent" placeholder="请输入主要治理内容"></up-textarea>
					<view class="margin-bottom margin-top">隐患治理完成内容</view>
					<up-textarea v-model="formData.treatmentResult" placeholder="请输入隐患治理完成情况"></up-textarea>
					<view class="margin-bottom margin-top">隐患治理责任单位自行验收的情况</view>
					<up-textarea v-model="formData.selfVerifyContent" placeholder="请输入隐患治理责任单位自行验收的情况"></up-textarea>
				</scroll-view>
				<view class="popup-footer">
					<button class="btn-cancel" @click="showAddPopup = false">取消</button>
					<button class="btn-confirm bg-blue" @click="handleAdd">确定</button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup>
	import { ref, reactive, onMounted } from 'vue'
	import { getMyWriteOffList, applyDelete, getAcceptanceList, getDepartmentPersonUsers } from '@/request/api.js';

	// 弹窗控制
	const showAddPopup = ref(false);
	const showHazardPicker = ref(false);
	const showDatePicker = ref(false);
	const showDeptPicker = ref(false);
	
	// 隐患选择
	const selectedHazard = ref('');
	const selectedHazardId = ref('');
	const hazardColumns = ref([['暂无数据']]);
	const acceptanceHazardList = ref([]); // 存储可申请销号的隐患数据
	const hazardList = ref([]); // 存储销号申请列表
	
	// 部门选择
	const selectedDeptName = ref('');
	const selectedDeptId = ref('');
	const deptColumns = ref([['暂无数据']]);
	const deptList = ref([]); // 存储部门列表
	
	// 日期选择
	const dateValue = ref(Date.now());
	
	// 表单数据
	const formData = reactive({
		rectifyDeadline: '', // 整改时限
		responsibleDeptId: '', // 隐患治理责任单位ID
		responsiblePerson: '', // 主要负责人
		mainTreatmentContent: '', // 主要治理内容
		treatmentResult: '', // 隐患治理完成内容
		selfVerifyContent: '' // 责任单位自行验收情况
	});
	
	// 获取销号申请列表（页面显示用）
	const fetchWriteOffList = async () => {
		try {
			const res = await getMyWriteOffList();
			if (res.code === 0 && res.data) {
				hazardList.value = res.data;
				console.log('销号申请列表:', res.data);
			}
		} catch (error) {
			console.error('获取销号申请列表失败:', error);
		}
	};
	
	// 获取可申请销号的隐患列表（弹窗选择用）
	const fetchAcceptanceList = async () => {
		try {
			const res = await getAcceptanceList();
			if (res.code === 0 && res.data) {
				const list = res.data.records || res.data || [];
				acceptanceHazardList.value = list;
				// 转换为 picker 需要的格式
				if (list.length > 0) {
					hazardColumns.value = [list.map(item => item.title || item.hazardTitle || `隐患${item.hazardId}`)];
				} else {
					hazardColumns.value = [['暂无可申请销号的隐患']];
				}
				console.log('可申请销号的隐患列表:', list);
			}
		} catch (error) {
			console.error('获取可申请销号隐患列表失败:', error);
		}
	};
	
	// 获取部门列表
	const fetchDeptList = async () => {
		try {
			const res = await getDepartmentPersonUsers();
			if (res.code === 0 && res.data) {
				const users = [];
				res.data.forEach(dept => {
					if (dept.users && dept.users.length > 0) {
						dept.users.forEach(user => {
							users.push({
								userId: user.userId,
								deptId: dept.deptId,
								name: `${user.nickName}（${dept.deptName}）`
							});
						});
					}
				});
				deptList.value = users;
				// 转换为 picker 需要的格式
				if (users.length > 0) {
					deptColumns.value = [users.map(item => item.name)];
				} else {
					deptColumns.value = [['暂无人员数据']];
				}
				console.log('部门人员列表:', users);
			}
		} catch (error) {
			console.error('获取部门人员列表失败:', error);
		}
	};
	
	// 部门选择确认
	const onDeptConfirm = (e) => {
		console.log('选择的人员:', e);
		if (e.value && e.value.length > 0) {
			selectedDeptName.value = e.value[0];
			// 找到对应的用户ID和部门ID
			const index = e.indexs[0];
			if (deptList.value[index]) {
				selectedDeptId.value = deptList.value[index].deptId;
				formData.responsibleDeptId = deptList.value[index].deptId;
			}
		}
		showDeptPicker.value = false;
	};
	
	// 打开新增弹窗
	const openAddPopup = () => {
		resetForm();
		fetchAcceptanceList(); // 获取可申请销号的隐患列表
		fetchDeptList(); // 获取部门列表
		showAddPopup.value = true;
	};
	
	// 隐患选择确认
	const onHazardConfirm = (e) => {
		console.log('选择的隐患:', e);
		if (e.value && e.value.length > 0) {
			selectedHazard.value = e.value[0];
			// 找到对应的隐患ID
			const index = e.indexs[0];
			if (acceptanceHazardList.value[index]) {
				selectedHazardId.value = acceptanceHazardList.value[index].hazardId;
			}
		}
		showHazardPicker.value = false;
	};
	
	// 日期时间选择确认
	const onDateConfirm = (e) => {
		console.log('选择的日期时间:', e);
		const date = new Date(e.value);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');
		const day = String(date.getDate()).padStart(2, '0');
		const hours = String(date.getHours()).padStart(2, '0');
		const minutes = String(date.getMinutes()).padStart(2, '0');
		const seconds = String(date.getSeconds()).padStart(2, '0');
		formData.rectifyDeadline = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		showDatePicker.value = false;
	};
	
	// 重置表单
	const resetForm = () => {
		selectedHazard.value = '';
		selectedHazardId.value = '';
		selectedDeptName.value = '';
		selectedDeptId.value = '';
		formData.rectifyDeadline = '';
		formData.responsibleDeptId = '';
		formData.responsiblePerson = '';
		formData.mainTreatmentContent = '';
		formData.treatmentResult = '';
		formData.selfVerifyContent = '';
	};
	
	// 确定新增
	const handleAdd = async () => {
		if (!selectedHazardId.value) {
			uni.showToast({ title: '请选择隐患', icon: 'none' });
			return;
		}
		
		// 构建请求参数（与接口文档对应）
		const params = {
			hazardId: Number(selectedHazardId.value), // 隐患ID（必需）
			rectifyDeadline: formData.rectifyDeadline || '', // 整改时限
			responsibleDeptId: Number(formData.responsibleDeptId) || 0, // 隐患治理责任单位ID
			responsiblePerson: formData.responsiblePerson || '', // 主要负责人
			mainTreatmentContent: formData.mainTreatmentContent || '', // 主要治理内容
			treatmentResult: formData.treatmentResult || '', // 隐患治理完成内容
			selfVerifyContent: formData.selfVerifyContent || '' // 责任单位自行验收情况
		};
		
		console.log('提交数据:', params);
		
		try {
			const res = await applyDelete(params);
			if (res.code === 0) {
				uni.showToast({ title: '申请成功', icon: 'success' });
				showAddPopup.value = false;
				resetForm();
				// 刷新销号申请列表
				fetchWriteOffList();
			} else {
				uni.showToast({ title: res.msg || '申请失败', icon: 'none' });
			}
		} catch (error) {
			console.error('申请失败:', error);
			uni.showToast({ title: '请求失败', icon: 'none' });
		}
	};
	
	const editor = () => {
		uni.navigateTo({
			url: '/pages/closeout/editor'
		})
	};
	
	// 页面加载时获取销号申请列表
	onMounted(() => {
		fetchWriteOffList();
	});
</script>

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

	.popup-content {
		width: 600rpx;
		background: #fff;
		border-radius: 20rpx;
		overflow: hidden;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;

		.popup-title {
			font-size: 32rpx;
			color: #333;
		}

		.popup-close {
			font-size: 40rpx;
			color: #999;
			line-height: 1;
		}
	}

	.popup-body {
		padding: 30rpx;
	}

	.popup-footer {
		display: flex;
		border-top: 1rpx solid #eee;

		button {
			flex: 1;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 0;
			font-size: 30rpx;

			&::after {
				border: none;
			}
		}

		.btn-cancel {
			background: #fff;
			color: #666;
		}

		.btn-confirm {
			color: #fff;
		}
	}
	.picker-input {
		background: #fff;
		border-radius: 8rpx;
		padding: 24rpx 20rpx;
		margin-bottom: 20rpx;
		// border: 1rpx solid #F6F6F6;
		border: 1rpx solid #eee;
		
		text {
			font-size: 28rpx;
			// color: #333;
		}
	}
</style>