<template>
  <div class="w-full">
    <div
      v-for="(form, index) in formBuilder.formFields"
      :key="'field' + index"
      class="w-12"
    >
      <span class="p-text-secondary block mb-5">{{ form.title }}</span>
      <div
        class="grid align-items-center mb-2"
        v-for="(row, indez) in form.fields"
        :key="indez"
      >
        <label :for="row.field" class="font-semibold col-4 md:mb-0"
          >{{ row.label }}
          <span v-if="row.required" class="text-red-600">*</span></label
        >
        <div class="col-8">
          <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, ref, reactive } from "vue";
import { useToast } from "primevue/usetoast";
import { FunctionService } from "@/service/security-management/FunctionService.js";

const functionService = new FunctionService();
const toast = useToast();
const loading = ref(true);
const saving = ref(false);
const errors = ref({});
const props = defineProps({
  data: Object,
});
const selections = reactive({
  apps: [],
  permissions: [],
});
const initForm = {
  id: "",
  name: "",
  desc: "",
  app_code: "",
  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 User" : "New User",
    formFields: [
      {
        title: "",
        fields: [
          {
            label: "Code",
            field: "code",
            component: "InputText",
            required: true,
            attributes: {
              type: "text",
              class: "w-full uppercase",
              placeholder: "Code",
            },
          },
          {
            label: "Name",
            field: "name",
            component: "InputText",
            required: true,
            attributes: {
              type: "text",
              class: "w-full",
              placeholder: "Name",
            },
          },
          // {
          //   label: "App",
          //   field: "app_code",
          //   component: "Dropdown",
          //   required: true,
          //   attributes: {
          //     options: selections.apps,
          //     class: "w-full",
          //     placeholder: "Select app",
          //     optionLabel: "name",
          //     optionValue: "code",
          //   },
          // },
          {
            label: "Permissions",
            field: "permission_id",
            component: "MultiSelect",
            required: true,
            attributes: {
              options: selections.permissions,
              class: "w-full",
              placeholder: "Select permission",
              optionLabel: "name",
              optionValue: "code",
              display: "chip",
            },
          },
          {
            label: "Description",
            field: "desc",
            component: "Textarea",
            attributes: {
              rows: 3,
              type: "text",
              class: "w-full",
              autocomplete: "new-password",
              placeholder: "Description",
            },
          },
        ],
      },
    ],
  };
});

onMounted(async () => {
  await getSelection();
  if (props.data) {
    formData.value = props.data;
    initData.value = JSON.parse(JSON.stringify(formData.value));
  }
});

const getSelection = () => {
  functionService.getSelection().then((res) => {
    let data = res.data;
    selections.apps = data.apps;
    selections.permissions = data.permissions;
  });
};
const submit = () => {
  console.log(JSON.stringify(initData.value), JSON.stringify(formData.value));
  if (JSON.stringify(initData.value) !== JSON.stringify(formData.value)) {
    saving.value = true;
    if (formData.value?.id) {
      functionService
        .update(formData.value.id, formData.value)
        .then((res) => {
          let data = res.data;
          toast.add({
            severity: "success",
            summary: "Success",
            detail: data.message,
            life: 3000,
          });
          emit("closeForm");
        })
        .catch((errors) => {
          errors.value = errors.data;
        })
        .finally((res) => {
          saving.value = false;
        });
    } else {
      functionService
        .create(formData.value)
        .then((res) => {
          let data = res.data;
          emit("closeForm");
          toast.add({
            severity: "success",
            summary: "Success",
            detail: data.message,
            life: 3000,
          });
        })
        .catch((res) => {
          let data = res.response?.data;
          errors.value = data.errors;
          toast.add({
            severity: "error",
            summary: "Errors",
            detail: data.message,
            life: 3000,
          });
        })
        .finally((res) => {
          saving.value = false;
        });
    }
  } else {
    toast.add({
      severity: "warn",
      summary: "Warning",
      detail: "No data changes",
      life: 3000,
    });
  }
};
defineExpose({
  close,
});
</script>
<style scoped>
::placeholder {
    text-transform: none;
}
</style>