<template>
  <Dialog
    v-model:visible="dialogBuilder.visible"
    modal
    :draggable="false"
    :closable="false"
    class="w-30rem"
    position="top"
  >
    <template #header>
      <span class="p-dialog-title" data-pc-section="title">Permission</span>
      <div class="flex align-items-center mr-0">
        <Button icon="pi pi-times" @click="close" text rounded></Button>
      </div>
    </template>
    <div
      class="flex justify-content-center mb-6 mt-6"
      v-if="!dataModal?.id && route.params.id"
    >
      <ProgressSpinner
        style="width: 50px; height: 50px"
        strokeWidth="8"
        fill="var(--surface-ground)"
        animationDuration=".5s"
        aria-label="Custom ProgressSpinner"
      />
    </div>
    <div v-else>
      <component
        :is="dialogBuilder?.form?.is"
        v-bind="{...dialogBuilder.form?.props}"
        :key="formKey"
        @closeForm="close"
      ></component>
    </div>
  </Dialog>
</template>
<script setup>
import { computed, markRaw, onMounted, reactive, ref } from "vue";
import Form from "./components/Form.vue";
import { PermissionService } from "@/service/security-management/PermissionService.js";
import { useRoute, useRouter } from "vue-router";

const dataModal = ref({});
const permissionService = new PermissionService();
const route = useRoute();
const router = useRouter();
const errors = ref({});
const option = ref({});
const formKey = ref(0);
const formModel = ref()
const id = computed(() => {
  return dataModal.value?.id || route.params?.id;
});
const state = reactive({
  builder: {
    visible: false,
    loading: true,
    form: {
      is: markRaw(Form),
      props: null,
    },
  },
});

const dialogBuilder = computed({
  get() {
    return state.builder;
  },
  set(
    newValue = {
      visible: false,
      loading: true,
      form: {
        is: markRaw(Form),
        props: null,
      },
    }
  ) {
    Object.assign(state.builder, newValue)
  },
});
const emit = defineEmits(["closeModal"]);
const close = () => {
  resetForm();
};
const resetForm = (data) => {
  formKey.value += 1;
  if (data) {
    setDialog(data);
  } else {
    dialogBuilder.value = {
      visible:false
    };
    router.push({
      name: "permissionIndex",
    });
    emit('closeModal');
  }
};
const openModal = async (data) => {
  if (data?.id) {
    dataModal.value = null
    getUser(data.id);
  } else {
    setDialog(data);
  }
};
onMounted(async () => {
  if (route.params.id) {
    await getUser(route.params.id);
  }
});
const setDialog = (data) => {
  dataModal.value = data;
  dialogBuilder.value = {
    loading: false,
    visible: true,
    form: {
      is:markRaw(Form),
      props: {
        data: data,
      },
    },
  };
};
const getUser = (id) => {
  dialogBuilder.value = {
    loading: true,
    visible: true,
  };
  permissionService.show(id).then((res) => {
    let data = res.data.permission;
    setDialog(data);
  });
};
defineExpose({
  openModal,
});
</script>