<template>
  <div class="grid">
    <div class="col-12">
      <Card>
        <template #title>
          <div
            class="flex flex-column md:flex-row gap-2 md:justify-content-between md:align-items-center"
          >
            <div class="align-item-start">
              <h4>Users</h4>
            </div>
            <div class="align-item-end">
              <Button
                label="New"
                icon="pi pi-user-plus"
                severity="info"
                @click="openModal"
                raised
              />
              <Button
                label="Delete"
                icon="pi pi-trash"
                class="ml-2"
                severity="danger"
                :disabled="oneSelected"
                @click="deleteRows"
                raised
              />
            </div>
          </div>
        </template>
        <template #content>
          <PrimeTable
            ref="tableRef"
            :dataTable="dataTable"
            @handleDblClick="rowDblClick"
          ></PrimeTable>
        </template>
      </Card>
    </div>
  </div>
  <Modal
    :option="formOption"
    @closeModal="close"
    @handleDblClick="openModal"
    ref="modalRef"
  ></Modal>
  <ConfirmDelete
    :confirm="deleteRef"
    @confClose="confirmClose"
    @confDelete="confirmDelete"
  ></ConfirmDelete>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from "vue";
import { UserService } from "@/service/security-management/UserService";
import Modal from "./Modal.vue";
import PrimeTable from "@/components/PrimeTable.vue";
import ConfirmDelete from "@/components/ConfirmDelete.vue";
import { useToast } from "primevue/usetoast";
import { useRoute, useRouter } from "vue-router";

const state = reactive({
  modal: {
    show: false,
  },
});
const route = useRoute();
const router = useRouter();
const toast = useToast();
const userService = new UserService();
const tableRef = ref();
const modalRef = ref();

const oneSelected = computed(() => {
  return !(tableRef.value?.selectedRows.length ?? 0);
});
const deleteRef = ref({
  visible: false,
  loading: false,
});
const dataTable = ref({
  dataUrl: "/api/security-management/users",
  columns: [
    { field: "id", header: "No" },
    { field: "name", header: "Name", sortable: true },
    { field: "email", header: "Email" },
    { field: "created_at", header: "Create date" },
  ],
  searchable: ["name", "email"],
});
const formOption = ref({});

const close = () => {
  router.push({
    name: "userIndex"
  });
  tableRef.value?.loadLazyData();
};
const rowDblClick = (data) => {
  modalRef.value?.openModal(data);
  router.push({
    name:"userDetail",
    params:{
      id:data.id
    }
  })
};
const openModal = () => {
  modalRef.value?.openModal();
};
const deleteRows = () => {
  deleteRef.value.visible = true;
};
const confirmClose = () => {
  deleteRef.value.visible = false;
};
const confirmDelete = () => {
  deleteRef.value.loading = true;
  let ids = tableRef.value.selectedRows.map((item) => {
    return item.id;
  });
  userService
    .delete({ ids: ids })
    .then((res) => {
      let response = res.data;
      toast.add({
        severity: "success",
        summary: "Success",
        detail: response.message,
        life: 3000,
      });
      deleteRef.value.visible = false;
      tableRef.value?.loadLazyData();
    })
    .then(() => {
      tableRef.value?.clearSelectedRows()
    })
    .catch((error) => {
      toast.add({
        severity: "error",
        summary: "Error",
        detail: error.message,
        life: 3000,
      });
    })
    .finally(() => {
      deleteRef.value.loading = false;
    });
};

const handleUrl = () => {
  if (route.params.id) {
    modalRef.value.openModal();
  }
};
onMounted(() => {
  tableRef.value?.loadLazyData();
});
</script>