import { ref, nextTick } from "vue";
import { ElForm } from "element-plus";

export function useForm<T = any>(initalData?: T) {
  const formRef = ref<InstanceType<typeof ElForm> | null>(null);

  const formData = ref({ ...initalData });

  function formValidCallback(fn: Function) {
    formRef.value.validate(isValid => {
      if (!isValid) return;
      fn();
    });
  }

  function resetForm() {
    nextTick(() => formRef.value.resetFields());
  }

  return {
    formRef,
    formData,
    resetForm,
    formValidCallback
  };
}
