import { useRoute, useRouter } from 'vue-router'
import { cloneDeep } from 'lodash-es'
import useTabs from '@/utils/useTabs'

export default function useFormHandler(formItems, api) {
	const state = reactive({
		PAGE_TYPE: ''
	})

	let formData = reactive({})
	const submitLoading = ref(false)
	const formRefs = ref([])
	const route = useRoute()
	const router = useRouter()

	const initializeFormData = (formItems, formData) => {
		formItems.forEach((item) => {
			formData[item.name] = item.defaultValue || null
		})
	}

	const onSubmit = async (params) => {
		Promise.all(formRefs.value.map((form) => form.validate()))
			.then(() => {
				submitLoading.value = true
				let formDataParam = params.isDeep ? cloneDeep(params) : cloneDeep(formData)

				if (route.query.id) {
					formDataParam = { ...formDataParam, id: route.query.id }
				}
				api
					.submitForm(formDataParam, route.query.id)
					.then(() => {
						router.go(-1)
						useTabs.close()
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch((error) => {
				console.error('Validation error:', error)
			})
	}

	const handleBack = () => {
		router.replace('/basicData/publicAccount')
		useTabs.close()
	}

	const fetchData = async (pageType) => {
		initializeFormData(formItems, formData)
		if (pageType && pageType !== 'ADD') {
			try {
				const res = await api.getDetail({ id: route.query.id })
				for (let key in formData) {
					if (res[key] !== undefined) {
						formData[key] = res[key]
					}
				}

				return res
			} catch (error) {
				console.error('API request failed:', error)
			}
		}
	}

	return {
		formData,
		submitLoading,
		formRefs,
		onSubmit,
		handleBack,
		fetchData
	}
}
