<template>
  <BasePage>
    <div class="card">
      <div class="card-header pb-0">
        <h6>{{ title }}</h6>
        <hr />
      </div>
      <div
        v-if="isFetching"
        class="card-body p-5 text-center d-flex align-items-center justify-content-center"
        style="min-height: 300px"
      >
        <div class="spinner-border text-primary" role="status">
          <span class="visually-hidden">Loading...</span>
        </div>
      </div>
      <DynamicForm
        v-if="!isFetching"
        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 { useRouter, useRoute } from "vue-router";
import BasePage from "./BasePage.vue";
import DynamicForm from "./../Form/DynamicForm.vue";
import { Swal, showLoading, hideLoading } from "@/utils/alert.js";

const emit = defineEmits(["saved", "dataLoaded"]);
const route = useRoute();

const props = defineProps({
  schemas: {
    type: Array,
    default: [],
  },
  title: {
    type: String,
    default: "",
  },
  api: {},
  isEdit: {
    default: false,
  },
});

const createForm = ref(null);
const isFetching = ref(false);
const formValue = ref({});

const handleSubmit = async (payload, { resetForm }) => {
  // console.log(payload)
  // return
  try {
    showLoading();
    const response = props.isEdit
      ? await props.api.update(route.params.id, payload)
      : await props.api.store(payload);
    hideLoading();
    Swal.fire("Sukses", "", "success");
    if (!props.isEdit) {
      resetForm();
    }
    emit("saved", 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");
  }
};

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

  if (props.isEdit) {
    isFetching.value = true;
    let response = await props.api.detail(route.params.id);
    const data = response.result;
    emit("dataLoaded", data);
    props.schemas.forEach((schema) => {
      if (schema.type == "password") {
        data[schema.name] = null;
      }
      if (schema.type == "checkbox") {
        if (data[schema.name] == 1) {
          data[schema.name] = true;
        } else {
          data[schema.name] = false;
        }
      }
    });
    formValue.value = data;
    isFetching.value = false;
  }
});
</script>
