<template>
  <BasePage>
    <div class="card">
      <div class="card-header pb-0">
        <h6>{{ title }}</h6>
        <hr />
      </div>
      <DynamicForm
        ref="createForm"
        :schemas="schemas"
        @formSubmit="handleSubmit"
        :form-value="formValue"
      >
        <template v-for="(schema, index) in schemas" #[schema.name]="values">
          <slot :name="schema.name" v-bind="values"></slot>
        </template>
      </DynamicForm>
    </div>
  </BasePage>
</template>
<script setup>
import { ref, onBeforeMount } from "vue";
import BasePage from "./BasePage.vue";
import DynamicForm from "./../Form/DynamicForm.vue";
import { Swal, showLoading, hideLoading } from "@/utils/alert.js";
const props = defineProps({
  schemas: {
    type: Array,
    default: [],
  },
  title: {
    type: String,
    default: "",
  },
  api: {},
});

const createForm = ref(null);

const handleSubmit = async (payload, { resetForm }) => {
  // console.log(payload)
  // return
  try {
    showLoading();
    const response = await props.api.store(payload);
    hideLoading();
    Swal.fire("Sukses", "", "success");
    resetForm();
    emit("created", response);
  } catch (err) {
    console.log(err);
    if (err.response && err.response.status == 422) {
      createForm.value.setError(err.response.data);
      hideLoading();
      return;
    }
    hideLoading();
    Swal.fire("Error", "Terjadi Error", "error");
  }
};

const formValue = ref({});

onBeforeMount(async () => {
  const initialValue = {};
  props.schemas.forEach((schema) => {
    if (schema.type == "checkbox") {
      initialValue[schema.name] = false;
    }
  });
  formValue.value = initialValue;
});
</script>
