<script setup>
import { computed, ref, useAttrs, getCurrentInstance } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useQuasar, QForm } from "quasar";
import { model } from "#imports";
const route = useRoute();
const router = useRouter();
const quasar = useQuasar();
const form = ref(null);
const props = defineProps({
  modelValue: {
    type: Object
  },
  bordered: {
    type: Boolean,
    default: true
  },
  gutter: {
    type: String,
    default: "md"
  },
  submitLabel: {
    type: String,
    default: "Save"
  },
  submitIcon: {
    type: String,
    default: "sym_o_save"
  },
  noRedirect: {
    type: Boolean,
    default: false
  }
});
const loading = ref(false);
const attrs = useAttrs();
const emit = defineEmits(["save", "submit", "submitted"]);
const instance = getCurrentInstance();
const hasSubmitListener = computed(() => {
  return !!instance?.vnode?.props?.onSubmit;
});
const save = async () => {
  if (!form.value) return;
  let valid = await form.value.validate();
  if (!valid) return;
  emit("save");
  if (hasSubmitListener.value) {
    emit("submit", () => {
      loading.value = false;
    });
    return;
  }
  if (props.modelValue && route.name) {
    try {
      if (route.params[id_name]) {
        if (await model(module).update(parseInt(route.params[id_name]), props.modelValue)) {
          if (!props.noRedirect) {
            router.push(`/${module}`);
          }
          emit("submitted");
          return;
        }
      } else {
        if (await model(module).add(props.modelValue)) {
          if (!props.noRedirect) {
            router.push(`/${module}`);
          }
          emit("submitted");
          return;
        }
      }
    } catch (e) {
      quasar.dialog({
        title: "Error",
        message: e.message,
        ok: "OK"
      });
    }
  }
  loading.value = false;
};
const onSubmit = (e) => {
  e.preventDefault();
  save();
};
const localClass = computed(() => {
  if (attrs.class) {
    return attrs.class;
  }
  return "row q-col-gutter-" + props.gutter;
});
</script>

<template>
    <q-form ref="form" @submit="onSubmit">
        <l-card :bordered="bordered">
            <q-card-section :class="localClass">
                <slot></slot>
            </q-card-section>

            <q-card-actions align="right">
                <l-btn :icon="submitIcon" :label="submitLabel" :loading="loading" type="submit" />
            </q-card-actions>
        </l-card>
    </q-form>
</template>
