<template>
	<view class="page">
		<HazardFormPanel
			ref="formRef"
			page-mode
			title="新增隐患排查"
			mode="direct"
			:extra-params="hazardExtraParams"
			:show-draft-banner="showRestoreBanner"
			canvas-id="hazardAddWatermarkCanvas"
			@success="onSubmitSuccess"
			@clear-draft="clearDraft(true)"
			@draft-change="draftSnapshot = $event"
		/>
	</view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onLoad, onHide } from '@dcloudio/uni-app'
import { enterCheckPlan, getCheckTaskDetail } from '@/request/api.js'
import HazardFormPanel from '@/components/hazard/HazardFormPanel.vue'
import { buildDraftKey, DRAFT_NS, removeDraft } from '@/utils/draftCache.js'
import { useDraftCache } from '@/utils/useDraftCache.js'
import { hasHazardFormContent } from '@/components/hazard/hazardForm.js'

const formRef = ref(null)
const taskId = ref('')
const checkPointId = ref('')
const oneTableId = ref('')
const draftSnapshot = ref(null)
const draftInitialized = ref(false)

const hazardExtraParams = computed(() => ({
	taskId: taskId.value,
	checkPointId: checkPointId.value,
	locationDraftKey: buildDraftKey(
		DRAFT_NS.HAZARD_ADD,
		'location',
		oneTableId.value,
		taskId.value,
		checkPointId.value
	)
}))

const getDraftKey = () => buildDraftKey(
	DRAFT_NS.HAZARD_ADD,
	oneTableId.value,
	taskId.value,
	checkPointId.value
)

const {
	showRestoreBanner,
	clear: clearDraft,
	restore: restoreDraft,
	save: saveDraft,
	bindAutoSave
} = useDraftCache({
	getKey: getDraftKey,
	getPayload: () => formRef.value?.getPayload?.() || {},
	hasContent: hasHazardFormContent,
	applyPayload: (data) => {
		nextTick(() => {
			formRef.value?.applyPayload?.(data)
		})
	},
	clearForm: () => {
		formRef.value?.resetForm?.()
	},
	canSave: () => draftInitialized.value,
	requireInitialized: true,
	showRestoreToast: false,
	onAfterRestore: (data) => {
		draftSnapshot.value = data
	}
})

const fetchTaskInfo = async (tableId) => {
	try {
		const startRes = await enterCheckPlan(tableId)
		if (startRes.code === 0 && startRes.data) {
			const tid = startRes.data.taskId
			const detailRes = await getCheckTaskDetail(tid)
			if (detailRes.code === 0 && detailRes.data) {
				taskId.value = detailRes.data.taskId
				checkPointId.value = detailRes.data.checkPointId
			}
		}
	} catch (error) {
		console.error('获取任务信息失败:', error)
	}
}

const clearLocationPickerDraft = () => {
	removeDraft(hazardExtraParams.value.locationDraftKey)
}

const restoreFormDraft = async () => {
	await nextTick()
	restoreDraft()
}

const onSubmitSuccess = () => {
	clearLocationPickerDraft()
	clearDraft(false)
}

bindAutoSave(() => draftSnapshot.value)

const initPage = async (options = {}) => {
	if (options.taskId) {
		taskId.value = options.taskId
	}
	if (options.checkPointId) {
		checkPointId.value = options.checkPointId
	}
	if (options.id) {
		oneTableId.value = options.id
		if (!options.taskId || !options.checkPointId) {
			await fetchTaskInfo(options.id)
		}
	}
	draftInitialized.value = true
	await restoreFormDraft()
}

onLoad(async (options) => {
	await initPage(options)
})

onHide(() => {
	saveDraft()
})
</script>

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