<script setup>
import {inject, ref} from "vue";
import useUtils from "@/utils/utils.js";

const props = defineProps(["data", "action", "method"])
const Tea = inject("$Tea")
const popupState = inject("$popupState", null)
const utils = useUtils()
const emits = defineEmits(["error", "done"])
const formRef = ref()

const onSubmit = (e) => {
	if (!popupState) {
		return
	}

	let url = props.action
	if (typeof url !== "string" || url.length === 0) {
		if (!popupState) {
			url = window.location.pathname
		} else {
			url = popupState.action.path
		}
	}

	let data = props.data

	// submit form if 'data' property undefined
	if (data === undefined) {
		if (popupState) {
			data = {}
			const formData = new FormData(formRef.value)
			formData.forEach((value, key) => {
				data[key] = value
			})
		}
	}

	if (typeof data === "object") {
		const params = Tea.serialize(data)
		if (params.length > 0) {
			if (url.indexOf("?") > 0) {
				url += "&" + params
			} else {
				url += "?" + params
			}
		}
	}

	// submit form if not in popup
	if (!popupState) {
		window.location.href = url

		e.preventDefault()
		return
	}

	if (e != null) {
		e.preventDefault()
	}

	if (typeof props.method === "string" && props.method.length > 0 && props.method.toLowerCase() != "get") {
		console.error("'GetForm' says: invalid method: '" + props.method + "'")
		return
	}

	// TODO 显示加载进度条

	const actionObject = Tea.action(url)
	actionObject
		.header("X-From-Front", "1")
		.error((resp) => {
			console.error(resp.message)
			emits("error", resp)
		})
		.done(() => {
			emits("done")
		})
		.timeout(30)
		.success((resp) => {
			popupState.url = url

			if (resp.data != null && typeof resp.data === "object") {
				let ctx = window.X_VIEW_CTX
				if (popupState) {
					ctx = popupState.ctx
				}
				for (const k in resp.data) {
					ctx[k] = resp.data[k]
				}
			}
		})
		.alert((message, callback, success) => {
			if (typeof message === "string" && message.length > 0) {
				if (success) {
					utils.success(message, () => {
						if (typeof callback === "function") {
							callback()
						} else {
							if (props.refresh || props.refresh === "") {
								Tea.reload()
							}
						}
					})
				} else {
					utils.warn(message, () => {
						if (typeof callback === "function") {
							callback()
						} else {
							if (props.refresh || props.refresh === "") {
								Tea.reload()
							}
						}
					})
				}
			}
		})
		.get()
}

defineExpose({
	submit(e) {
		onSubmit(e)
	}
})

</script>

<template>
	<form method="get" class="mb-4" @submit="onSubmit" ref="formRef">
		<slot></slot>
	</form>
</template>

<style scoped>

</style>