import { useForm } from "vee-validate"; import { ref } from "vue"; import { apiBack } from "src/boot/axios"; import { quasarNotify } from "src/functions/quasarNotify"; import { useFormStore } from "src/stores/forms"; import { questionSchema } from "src/utils/zod/schemas"; import { watch } from "vue"; export function useQuestionForm() { const formStore = useFormStore(); const { handleQuestionData } = formStore; //! Elements const questionPhoneRef = ref(null); const questionPhoneData = ref({ country: { name: "", iso2: "", dialCode: "", priority: 0, areaCodes: null, }, countryCallingCode: "", nationalNumber: "", number: "", countryCode: "", valid: false, formatted: "", }); const { errors, meta, defineField, handleSubmit, handleReset } = useForm({ validationSchema: questionSchema, initialValues: { terms: false, }, }); const [firstName, firstNameAttrs] = defineField("name"); const [secondName, secondNameAttrs] = defineField("surname"); const [email, emailAttrs] = defineField("email"); const [phone, phoneAttrs] = defineField("phone", { validateOnModelUpdate: false, }); const [query, queryAttrs] = defineField("query"); const [message, messageAttrs] = defineField("message"); const [terms, termsAttrs] = defineField("terms"); watch( () => questionPhoneRef.value?.modelValue, () => { questionPhoneData.value = questionPhoneRef.value.phoneObject; } ); const isQuestionSubmitLoading = ref(false); const isQuestionSubmitError = ref(false); const onSubmit = handleSubmit(async (values, actions) => { isQuestionSubmitLoading.value = true; if (!questionPhoneData.value.valid) { actions.setFieldError("phone", "El teléfono no es válido"); return; } try { const contactData = { name: `${values.name} ${values.surname}`, phone: questionPhoneData.value.number, email: values.email, message: values.message, }; await apiBack.post("contact/save", contactData); isQuestionSubmitLoading.value = false; quasarNotify({ type: "success", message: "Mensaje enviado" }); } catch (error) { console.error(`FATAL ERROR ::: ${error}`); isQuestionSubmitLoading.value = false; isQuestionSubmitError.value = true; } finally { handleQuestionData(values); handleReset(); } }); return { questionPhoneData, questionPhoneRef, formState: { isQuestionSubmitLoading, onSubmit, errors, meta, }, fields: { firstName, firstNameAttrs, secondName, secondNameAttrs, email, emailAttrs, phone, phoneAttrs, query, queryAttrs, message, messageAttrs, terms, termsAttrs, }, }; }