<template>
  <div class="w-full">
    <div
      v-for="(form, index) in formBuilder.formFields"
      :key="index"
      class="w-12"
    >
      <span class="p-text-secondary block mb-5">{{ form.title }}</span>
      <div
        class="grid align-items-center mb-3"
        v-for="(row, indez) in form.fields"
        :key="indez"
      >
        <div class="col-3">
          <label :for="row.field" class="font-semibold md:mb-0">{{
            row.label
          }}</label>
        </div>
        <div class="col-9">
          <component
            :is="row.component"
            v-bind="row.attributes"
            v-model="formData[row.field]"
            :key="row.field"
          ></component>
          <small v-if="errors[row.field]" class="text-red-700"
            ><i>{{ errors[row.field][0] }}</i></small
          >
        </div>
      </div>
    </div>
    <div class="flex justify-content-end gap-2">
      <Button
        type="button"
        label="Cancel"
        severity="secondary"
        @click="close"
      ></Button>
      <Button
        type="button"
        @click="submit"
        :loading="saving"
        label="Save"
      ></Button>
    </div>
    <Toast />
  </div>
</template>
<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { useToast } from "primevue/usetoast";
import { RoleService } from "@/service/security-management/RoleService.js";

const roleService = new RoleService();
const toast = useToast();
const loading = ref(true);
const saving = ref(false);
const errors = ref({});
const selections = reactive({
  fnctions: [],
  apps: [],
});
const props = defineProps({
  data: Object,
});
const initForm = {
  id: "",
  name: "",
  app_code: "",
  desc: "",
  permission_id: [],
};

const formData = ref({
  ...initForm,
});
const initData = ref({
  ...initForm,
});

const emit = defineEmits(["closeForm"]);
const close = () => {
  emit("closeForm");
};

const formBuilder = computed(() => {
  return {
    header: formData?.id ? "Update Role" : "New Role",
    formFields: [
      {
        title: "",
        fields: [
          {
            label: "Name",
            field: "name",
            component: "InputText",
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
          // {
          //   label: "App",
          //   field: "app_code",
          //   component: "Dropdown",
          //   required: true,
          //   attributes: {
          //     options: selections.apps,
          //     class: "w-full",
          //     placeholder: "Select app",
          //     optionLabel: "name",
          //     optionValue: "code",
          //   },
          // },
          {
            label: "Function",
            field: "permission_id",
            component: "TreeSelect",
            attributes: {
              options: selections.fnctions,
              class: "w-full",
              placeholder: "Select permission",
              selectionMode: "checkbox",
            },
          },
          {
            label: "Description",
            field: "description",
            component: "Textarea",
            attributes: {
              type: "text",
              class: "w-full",
            },
          },
        ],
      },
    ],
  };
});

onMounted(async () => {
  await getSelection();
  if (props.data) {
    formData.value = props.data;
    initData.value = JSON.parse(JSON.stringify(formData.value));
  }
});
const getKey = (data) => {
  const arr = [];
  Object.keys(data).forEach((key) => {
    arr.push(key);
  });
  return key;
};
const preparedModel = (data) => {
  let formData = new FormData();
  Object.keys(data).forEach((key) => {
    if (key !== "permission_id") {
      formData.append(key, data[key]);
    } else {
      Object.keys(data[key]).forEach((index) => {
        if (!isNaN(index)) {
          formData.append("permission_id[]", index);
        } else {
          formData.append("fnction_id[]", index);
        }
      });
    }
  });
  return formData;
};
const submit = () => {
  if (JSON.stringify(initData.value) !== JSON.stringify(formData.value)) {
    const data = preparedModel(formData.value);
    saving.value = true;
    if (formData.value?.id) {
      data.append('_method','PATCH');
      roleService
        .update(formData.value.id, data)
        .then((res) => {
          let response = res.data;
          toast.add({
            severity: "success",
            summary: "Success",
            detail: response.message,
            life: 3000,
          });
          emit("closeForm");
        })
        .catch((errors) => {
          errors.value = errors.data;
        })
        .finally((res) => {
          saving.value = false;
        });
    } else {
      roleService
        .create(data)
        .then((res) => {
          let response = res.data;
          toast.add({
            severity: "success",
            summary: "Success",
            detail: response.message,
            life: 3000,
          });
          emit("closeForm");
        })
        .catch((res) => {
          let response = res.response?.data;
          errors.value = response.errors;
          toast.add({
            severity: "error",
            summary: "Errors",
            detail: response.message,
            life: 3000,
          });
        })
        .finally((res) => {
          saving.value = false;
        });
    }
  } else {
    toast.add({
      severity: "warn",
      summary: "Warning",
      detail: "No data changes",
      life: 3000,
    });
  }
};

const getSelection = () => {
  roleService.getSelection().then((res) => {
    let data = res.data;
    selections.fnctions = data.fnctions;
  });
};
defineExpose({
  close,
});
</script>