<template>
	<view class="padding page">
		<view class="padding bg-white radius">
			<view class="flex margin-bottom">
				<view>隐患</view>
				<view class="text-red">*</view>
			</view>
			<view class="picker-input readonly" v-if="hazardLocked">
				<text :class="selectedHazard ? '' : 'text-gray'">{{ selectedHazard || '加载中...' }}</text>
			</view>
			<view class="picker-input" v-else @click="showHazardPicker = true">
				<text :class="selectedHazard ? '' : 'text-gray'">{{ selectedHazard || '请选择隐患' }}</text>
			</view>

			<view class="flex margin-bottom margin-top">
				<view>整改时限</view>
			</view>
			<view class="picker-input readonly">
				<text :class="formData.rectifyDeadline ? '' : 'text-gray'">{{ formData.rectifyDeadline || '请先选择隐患' }}</text>
			</view>

			<view class="margin-bottom margin-top">隐患治理责任单位</view>
			<view class="picker-input readonly">
				<text :class="selectedDeptName ? '' : 'text-gray'">{{ selectedDeptName || '请先选择隐患' }}</text>
			</view>

			<view class="margin-bottom margin-top">主要负责人</view>
			<view class="picker-input readonly">
				<text :class="formData.responsiblePerson ? '' : 'text-gray'">{{ formData.responsiblePerson || '请先选择隐患' }}</text>
			</view>

			<view class="ai-btn-wrapper margin-top margin-bottom">
				<button class="ai-analyze-btn" :loading="aiGenerating" :disabled="aiGenerating" @click="handleAiGenerate">
					<text v-if="!aiGenerating" class="cuIcon-magic ai-btn-icon"></text>
					{{ aiGenerating ? 'AI生成中...' : 'AI 生成销号方案' }}
				</button>
			</view>

			<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>

			<view class="flex margin-bottom margin-top">
				<view class="text-gray">是否结束销号</view>
				<view class="text-red">*</view>
			</view>
			<up-radio-group :key="'hazard-end-' + hazardEndRadio" v-model="hazardEndRadio" placement="row" activeColor="#2667e9">
				<up-radio
					label="否"
					name="no"
					:customStyle="{ marginRight: '48rpx' }"
				></up-radio>
				<up-radio label="是" name="yes"></up-radio>
			</up-radio-group>

			<template v-if="!hazardEnd">
				<view class="flex margin-bottom margin-top">
					<view class="text-gray">下一步流程</view>
					<view class="text-red">*</view>
				</view>
				<view class="static-field">{{ nextStepDisplay }}</view>

				<view class="flex margin-bottom margin-top">
					<view class="text-gray">短信提醒</view>
					<view class="text-red">*</view>
				</view>
				<up-radio-group v-model="sendMsgFlagRadio" placement="row" activeColor="#2667e9">
					<up-radio
						label="是"
						name="yes"
						:customStyle="{ marginRight: '48rpx' }"
					></up-radio>
					<up-radio label="否" name="no"></up-radio>
				</up-radio-group>
			</template>

			<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>

		<up-picker
			v-if="!hazardLocked"
			:show="showHazardPicker"
			:columns="hazardColumns"
			@confirm="onHazardConfirm"
			@cancel="showHazardPicker = false"
			@close="showHazardPicker = false"
		></up-picker>

		<!-- 暂时注释：下一步处理人弹窗
		<u-popup :show="showAssigneePopup" mode="bottom" round="20" @close="cancelAssigneeSelect">
			<view class="user-popup">
				<view class="popup-header">
					<view class="popup-title text-bold">选择下一步处理人</view>
					<view class="popup-close" @click="cancelAssigneeSelect">×</view>
				</view>
				<scroll-view class="user-list-scroll" scroll-y>
					<view v-if="assigneeLoading" class="empty-tip">加载中...</view>
					<view v-else-if="assigneeList.length === 0" class="empty-tip">暂无人员数据</view>
					<template v-else>
						<view
							v-for="user in assigneeList"
							:key="getAssigneeItemKey(user)"
							class="user-item"
							:class="{ active: String(pickerAssigneeIdentityId) === String(resolveAssigneeIdentityId(user)) }"
							@click="onAssigneeItemClick(user)"
						>
							<text class="user-item-text">{{ formatAssigneeDisplayName(user) }}</text>
							<text v-if="String(pickerAssigneeIdentityId) === String(resolveAssigneeIdentityId(user))" class="cuIcon-check text-blue"></text>
						</view>
					</template>
				</scroll-view>
				<view class="popup-footer">
					<button class="btn-cancel" @click="cancelAssigneeSelect">取消</button>
					<button class="btn-confirm bg-blue" @click="confirmAssigneeSelect">确定</button>
				</view>
			</view>
		</u-popup>
		-->
	</view>
</template>

<script setup>
	import { ref, reactive, computed, nextTick } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import {
		applyDelete,
		getHiddenDangerDetail,
		getHiddenDangerList,
		getRectifyDetail,
		generateWriteoffContent,
		getFlowNextNodes,
		getDeptUsers
	} from '@/request/api.js';
	import { buildWriteoffHazardFromOptions } from '@/utils/hazardNav.js';

	const showHazardPicker = ref(false);
	const hazardLocked = ref(false);
	const selectedHazard = ref('');
	const selectedHazardId = ref('');
	const assignId = ref('');
	const taskId = ref('');
	const hazardColumns = ref([['暂无数据']]);
	const selectableHazardList = ref([]);
	const selectedDeptName = ref('');
	const aiGenerating = ref(false);
	const hazardEndRadio = ref('no');
	const hazardEnd = computed(() => hazardEndRadio.value === 'yes');
	const normalizeHazardEndRadio = (value) => (value === 'yes' ? 'yes' : 'no');
	const sendMsgFlagRadio = ref('yes');
	const sendMsgFlag = computed(() => sendMsgFlagRadio.value === 'yes');

	const nextStepName = ref('');
	const nextStepLoading = ref(false);
	const nextStepDisplay = computed(() => {
		if (nextStepLoading.value) return '加载中...';
		return nextStepName.value || '暂无下一步流程';
	});

	const selectedAssigneeIdentityId = ref('');
	const selectedAssigneeName = ref('');
	const pickerAssigneeIdentityId = ref('');
	const pickerAssigneeName = ref('');
	const showAssigneePopup = ref(false);
	const assigneeList = ref([]);
	const assigneeLoading = ref(false);

	const formData = reactive({
		rectifyDeadline: '',
		responsibleDeptId: '',
		responsiblePerson: '',
		mainTreatmentContent: '',
		treatmentResult: '',
		selfVerifyContent: ''
	});

	const findHazardInList = (hazardId) => {
		return selectableHazardList.value.find(
			(item) => String(item.hazardId) === String(hazardId) || String(item.id) === String(hazardId)
		);
	};

	const fillHazardRelatedFields = (hazard) => {
		formData.rectifyDeadline = hazard.deadline || '';
		selectedDeptName.value = hazard.deptName || '';
		formData.responsiblePerson = hazard.rectifierName || '';
		formData.responsibleDeptId = hazard.deptId || '';
	};

	const resolveTaskIdFromHazard = (hazard) => {
		if (!hazard) return '';
		const candidates = [
			hazard.taskId,
			hazard.flowTaskId,
			hazard.currentTaskId,
			hazard.flowTask?.taskId,
			hazard.currentTask?.taskId
		];
		for (const id of candidates) {
			if (id != null && id !== '') return String(id);
		}
		return '';
	};

	const resolveTaskIdFromAssign = (assign) => {
		if (!assign) return '';
		const candidates = [
			assign.taskId,
			assign.flowTaskId,
			assign.currentTaskId,
			assign.rectify?.taskId,
			assign.rectify?.flowTaskId,
			assign.rectify?.currentTaskId,
			assign.flow?.taskId,
			assign.currentTask?.taskId
		];
		for (const id of candidates) {
			if (id != null && id !== '') return String(id);
		}
		return '';
	};

	const resolveAssignWithRectify = (assigns, currentAssignId) => {
		if (!assigns?.length) return null;
		if (currentAssignId) {
			const byAssignId = assigns.find(
				(item) => String(item.assignId) === String(currentAssignId) && item.rectify
			);
			if (byAssignId) return byAssignId;
		}
		return assigns.find((item) => item.rectify) || assigns[0] || null;
	};

	const resolveTaskIdFromDetail = (data) => {
		if (!data) return '';
		if (data.taskId) return String(data.taskId);
		if (data.flowTaskId) return String(data.flowTaskId);
		if (data.currentTaskId) return String(data.currentTaskId);

		const assigns = data.assigns || [];
		const matchedAssign = resolveAssignWithRectify(assigns, assignId.value);
		const fromMatched = resolveTaskIdFromAssign(matchedAssign);
		if (fromMatched) return fromMatched;

		for (const assign of assigns) {
			const id = resolveTaskIdFromAssign(assign);
			if (id) return id;
		}
		return '';
	};

	const resolveNextTaskName = (data) => {
		if (!data) return '';
		const branches = data.branches || [];
		const matchedBranch = branches.find((item) => item.matched) || branches[0];
		return matchedBranch?.nextNode?.taskName || '';
	};

	const buildPreviewVariables = () => ({
		quickApprove: true
	});

	const getStoredUserInfo = () => {
		try {
			const stored = uni.getStorageSync('userInfo');
			if (!stored) return {};
			return typeof stored === 'string' ? JSON.parse(stored) : stored;
		} catch (error) {
			return {};
		}
	};

	const getCurrentDeptId = () => {
		const userInfo = getStoredUserInfo();
		const identity = userInfo.userIdentity;
		if (identity?.deptId != null && identity.deptId !== '') {
			return String(identity.deptId);
		}
		if (userInfo.deptId != null && userInfo.deptId !== '') {
			return String(userInfo.deptId);
		}
		return '';
	};

	const resolveAssigneeIdentityId = (user) => {
		if (!user) return '';
		const id = user.identityId ?? user.userIdentityId ?? user.userId ?? '';
		return id === '' || id == null ? '' : String(id);
	};

	const getAssigneeItemKey = (user) => {
		const identityId = resolveAssigneeIdentityId(user);
		if (identityId) return `identity-${identityId}`;
		return `user-${user.userId || user.nickName || ''}`;
	};

	const formatAssigneeDisplayName = (user) => {
		if (!user) return '';
		const name = user.nickName || user.userName || user.name || '';
		const identityName = user.identityName || '';
		if (name && identityName) return `${name}（${identityName}）`;
		return name || identityName || '未知人员';
	};

	const resolveAssigneeDeptUserType = () => 2;

	const fetchAssigneeList = async () => {
		const deptId = getCurrentDeptId();
		if (!deptId) {
			assigneeList.value = [];
			return;
		}
		assigneeLoading.value = true;
		try {
			const res = await getDeptUsers(deptId, { type: resolveAssigneeDeptUserType() });
			if (res.code === 0) {
				assigneeList.value = res.data || [];
			} else {
				assigneeList.value = [];
			}
		} catch (error) {
			console.error('获取部门人员失败:', error);
			assigneeList.value = [];
		} finally {
			assigneeLoading.value = false;
		}
	};

	const openAssigneePopup = async () => {
		pickerAssigneeIdentityId.value = selectedAssigneeIdentityId.value;
		pickerAssigneeName.value = selectedAssigneeName.value;
		showAssigneePopup.value = true;
		await fetchAssigneeList();
	};

	const onAssigneeItemClick = (user) => {
		const identityId = resolveAssigneeIdentityId(user);
		if (!identityId) return;
		pickerAssigneeIdentityId.value = String(identityId);
		pickerAssigneeName.value = formatAssigneeDisplayName(user);
	};

	const confirmAssigneeSelect = () => {
		if (!pickerAssigneeIdentityId.value) {
			uni.showToast({ title: '请选择下一步处理人', icon: 'none' });
			return;
		}
		selectedAssigneeIdentityId.value = pickerAssigneeIdentityId.value;
		selectedAssigneeName.value = pickerAssigneeName.value;
		showAssigneePopup.value = false;
	};

	const cancelAssigneeSelect = () => {
		showAssigneePopup.value = false;
	};

	const fetchNextStep = async () => {
		nextStepLoading.value = true;
		try {
			const currentTaskId = taskId.value;
			if (!currentTaskId) {
				nextStepName.value = '';
				return;
			}
			const res = await getFlowNextNodes({
				taskId: currentTaskId,
				previewVariables: buildPreviewVariables(),
				includeSubProcess: true
			});
			if (res.code === 0) {
				const payload = res.data && typeof res.data === 'object' ? res.data : res;
				nextStepName.value = resolveNextTaskName(payload);
			} else {
				nextStepName.value = '';
			}
		} catch (error) {
			console.error('获取下一步流程失败:', error);
			nextStepName.value = '';
		} finally {
			nextStepLoading.value = false;
		}
	};

	const resolveTaskIdForHazard = async (hazard) => {
		const presetTaskId = taskId.value;
		const fromHazard = resolveTaskIdFromHazard(hazard);
		if (fromHazard) {
			taskId.value = fromHazard;
		}

		if (!hazard?.hazardId) {
			return;
		}

		if (!assignId.value && hazard.assignId) {
			assignId.value = String(hazard.assignId);
		}

		if (taskId.value) {
			return;
		}

		try {
			const params = { hazardId: hazard.hazardId };
			if (assignId.value) {
				params.assignId = assignId.value;
			}
			const res = await getHiddenDangerDetail(params);
			if (res.code === 0 && res.data) {
				taskId.value = resolveTaskIdFromDetail(res.data) || presetTaskId;
			}
		} catch (error) {
			console.error('获取隐患任务信息失败:', error);
		}

		if (!taskId.value && presetTaskId) {
			taskId.value = presetTaskId;
		}
	};

	const resetFlowSelection = () => {
		selectedAssigneeIdentityId.value = '';
		selectedAssigneeName.value = '';
		nextStepName.value = '';
	};

	const applySelectedHazard = async (hazard) => {
		if (!hazard) return;
		selectedHazard.value = hazard.title || hazard.hazardTitle || `隐患${hazard.hazardId}`;
		selectedHazardId.value = hazard.hazardId;
		assignId.value = hazard.assignId ? String(hazard.assignId) : '';
		if (hazard.taskId) {
			taskId.value = String(hazard.taskId);
		}
		fillHazardRelatedFields(hazard);
		resetFlowSelection();
		await resolveTaskIdForHazard(hazard);
		await fetchNextStep();
	};

	const resolveSelectableRecords = (data) => {
		if (!data) return [];
		if (Array.isArray(data)) return data;
		if (Array.isArray(data.records)) return data.records;
		return [];
	};

	const canApplyWriteoff = (item) => (
		item?.statusName === '待销号' && (item?.applyFlag === true || item?.applyFlag === 1 || item?.applyFlag === '1')
	);

	/** 非锁定入口：从隐患列表拉取可申请销号的隐患（替代 verified/list） */
	const fetchSelectableHazardList = async () => {
		try {
			const res = await getHiddenDangerList({ pageNum: 1, pageSize: 100, status: 4 });
			if (res.code === 0 && res.data) {
				const list = resolveSelectableRecords(res.data).filter(canApplyWriteoff);
				selectableHazardList.value = list;
				if (list.length > 0) {
					hazardColumns.value = [list.map((item) => item.title || item.hazardTitle || `隐患${item.hazardId}`)];
				} else {
					hazardColumns.value = [['暂无可申请销号的隐患']];
				}
			}
		} catch (error) {
			console.error('获取可申请销号隐患列表失败:', error);
		}
	};

	const preselectHazardById = async (hazardId) => {
		const hazard = findHazardInList(hazardId);
		if (!hazard) return false;
		await applySelectedHazard(hazard);
		return true;
	};

	const onHazardConfirm = async (e) => {
		if (e.value && e.value.length > 0) {
			const index = e.indexs[0];
			const hazard = selectableHazardList.value[index];
			if (hazard) {
				await applySelectedHazard(hazard);
			}
		}
		showHazardPicker.value = false;
	};

	const handleAiGenerate = async () => {
		if (!selectedHazardId.value) {
			uni.showToast({ title: '请先选择隐患', icon: 'none' });
			return;
		}

		aiGenerating.value = true;
		try {
			const hazardRes = await getHiddenDangerDetail({ hazardId: selectedHazardId.value });
			if (hazardRes.code !== 0 || !hazardRes.data) {
				uni.showToast({ title: '获取隐患详情失败', icon: 'none' });
				return;
			}

			const assigns = hazardRes.data.assigns;
			if (!assigns || assigns.length === 0 || !assigns[0].rectify) {
				uni.showToast({ title: '该隐患暂无整改记录', icon: 'none' });
				return;
			}
			const rectifyId = assigns[0].rectify.rectifyId;

			const rectifyRes = await getRectifyDetail({ rectifyId });
			if (rectifyRes.code !== 0 || !rectifyRes.data) {
				uni.showToast({ title: '获取整改详情失败', icon: 'none' });
				return;
			}

			const rectifyPlan = rectifyRes.data.rectifyPlan;
			if (!rectifyPlan) {
				uni.showToast({ title: '整改方案内容为空', icon: 'none' });
				return;
			}

			const aiRes = await generateWriteoffContent({ rectifyContent: rectifyPlan });
			if (aiRes.code === 0 && aiRes.data) {
				formData.mainTreatmentContent = aiRes.data.mainContent || '';
				formData.treatmentResult = aiRes.data.completionContent || '';
				formData.selfVerifyContent = aiRes.data.selfInspection || '';
				uni.showToast({ title: 'AI生成成功', icon: 'success' });
			} else {
				uni.showToast({ title: aiRes.msg || 'AI生成失败', icon: 'none' });
			}
		} catch (error) {
			console.error('AI生成销号方案失败:', error);
			uni.showToast({ title: 'AI生成失败，请重试', icon: 'none' });
		} finally {
			aiGenerating.value = false;
		}
	};

	const handleCancel = () => {
		uni.navigateBack();
	};

	const handleSubmit = async () => {
		if (!selectedHazardId.value) {
			uni.showToast({ title: '请选择隐患', icon: 'none' });
			return;
		}
		// 暂时注释：下一步处理人必选校验
		// if (!selectedAssigneeIdentityId.value) {
		// 	uni.showToast({ title: '请选择下一步处理人', icon: 'none' });
		// 	return;
		// }

		const params = {
			hazardId: Number(selectedHazardId.value),
			rectifyDeadline: formData.rectifyDeadline || '',
			responsibleDeptId: Number(formData.responsibleDeptId) || 0,
			responsiblePerson: formData.responsiblePerson || '',
			mainTreatmentContent: formData.mainTreatmentContent || '',
			treatmentResult: formData.treatmentResult || '',
			selfVerifyContent: formData.selfVerifyContent || '',
			hazardEnd: hazardEnd.value,
			quickApprove: hazardEnd.value ? null : true,
			sendMsgFlag: hazardEnd.value ? null : sendMsgFlag.value
		};
		// 非快速审批时需传 assigneeIdentityId
		// if (!params.quickApprove) {
		// 	params.assigneeIdentityId = selectedAssigneeIdentityId.value;
		// }

		try {
			const res = await applyDelete(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(async (options) => {
		hazardLocked.value = options?.locked === '1';
		if (options?.assignId) {
			assignId.value = String(options.assignId);
		}
		if (options?.taskId) {
			taskId.value = String(options.taskId);
		}

		const hazardFromOptions = buildWriteoffHazardFromOptions(options);
		if (hazardFromOptions?.hazardId) {
			await applySelectedHazard(hazardFromOptions);
		} else {
			if (!hazardLocked.value) {
				await fetchSelectableHazardList();
			}

			if (taskId.value) {
				await fetchNextStep();
			}
		}

		nextTick(() => {
			hazardEndRadio.value = normalizeHazardEndRadio(hazardEndRadio.value);
		});
	});
</script>

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

	.ai-btn-wrapper {
		display: flex;
		justify-content: flex-end;
	}

	.ai-analyze-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 72rpx;
		padding: 0 32rpx;
		font-size: 28rpx;
		color: #fff;
		background: linear-gradient(135deg, #4facfe 0%, #2668EA 100%);
		border-radius: 36rpx;
		border: none;

		&::after {
			border: none;
		}

		.ai-btn-icon {
			margin-right: 8rpx;
			font-size: 30rpx;
		}

		&[disabled] {
			opacity: 0.7;
		}
	}

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

		text {
			font-size: 28rpx;
		}

		&.readonly {
			background: #f5f5f5;
			color: #666;
		}
	}

	.static-field {
		background: #fff;
		border: 1rpx solid #dcdfe6;
		border-radius: 8rpx;
		padding: 20rpx 24rpx;
		margin-bottom: 20rpx;
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
	}

	.select-trigger {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #fff;
		border: 1rpx solid #dcdfe6;
		border-radius: 8rpx;
		padding: 20rpx 24rpx;
		margin-bottom: 20rpx;

		.select-content {
			flex: 1;
			font-size: 28rpx;
			color: #333;
		}
	}

	.user-popup {
		background: #fff;

		.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;
			}
		}

		.user-list-scroll {
			max-height: 600rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
		}

		.empty-tip {
			padding: 80rpx 20rpx;
			text-align: center;
			color: #909399;
			font-size: 26rpx;
		}

		.user-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 24rpx 0;
			border-bottom: 1rpx solid #f5f5f5;

			&:last-child {
				border-bottom: none;
			}

			&.active {
				.user-item-text {
					color: #2667E9;
					font-weight: 600;
				}
			}

			.user-item-text {
				flex: 1;
				font-size: 28rpx;
				color: #333;
			}
		}

		.popup-footer {
			display: flex;
			gap: 24rpx;
			padding: 24rpx 30rpx;
			padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
			background: #fff;

			button {
				flex: 1;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 40rpx;
				font-size: 30rpx;
				margin: 0;
				padding: 0;

				&::after {
					border: none;
				}
			}

			.btn-cancel {
				background: #fff;
				color: #2667E9;
				border: 2rpx solid #2667E9;
			}

			.btn-confirm {
				color: #fff;
				border: none;
			}
		}
	}
</style>
