<template>
  <DataTable
    :value="rows"
    lazy
    paginator
    removableSort
    :first="first"
    :rows="10"
    v-model:filters="filters"
    ref="dt"
    dataKey="id"
    :totalRecords="totalRecords"
    :loading="loading"
    :globalFilterFields="dataTable.searchable"
    @page="onPage($event)"
    @sort="onSort($event)"
    @filter="onFilter($event)"
    sortMode="multiple"
    filterDisplay="menu"
    v-model:selection="selectedRows"
    :selectAll="selectAll"
    @select-all-change="onSelectAllChange"
    @row-select="onRowSelect"
    @row-click="onRowClick"
    @row-dblclick="rowDblClick"
    @row-unselect="onRowUnselect"
    tableStyle="min-width: 75rem"
    :rowsPerPageOptions="[10, 25, 50, 100, 500, 1000]"
    paginatorPosition="bottom"
    selectionMode="multiple"
    paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
    currentPageReportTemplate="Showing {first} to {last} of {totalRecords} users"
  >
    <template #header>
      <div
        class="flex flex-column md:flex-row gap-2 md:justify-content-between md:align-items-center"
      >
        <div class="align-item-start">
          <Button
            type="button"
            icon="pi pi-filter-slash"
            label="Clear"
            outlined
            @click="clearFilter($event)"
          />
        </div>
        <div class="align-items-end">
          <InputGroup class="float-right">
            <InputText placeholder="Keyword" v-model="filters.global.value" />
            <Button icon="pi pi-search" @click="onFilter()" severity="info" />
          </InputGroup>
        </div>
      </div>
    </template>
    <template #empty> <p class="text-center">No data found.</p> </template>
    <Column
      v-for="col of dataTable.columns"
      :key="col.field"
      :field="col.field"
      :header="col.header"
      :sortable="col.sortable"
    >
      <template v-if="col.type === 'image'" #body="slotProps">
        <img :src="`${slotProps.data.image_url}`" alt="" class="w-4rem border-round" />
      </template>
    </Column>
  </DataTable>
</template>
<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";

const props = defineProps(["dataTable"]);
const emit = defineEmits(["update:modelValue", "handleDblClick"]);
const dataTable = ref({
  dataUrl: props.dataTable.dataUrl,
  columns: props.dataTable.columns,
  searchable: props.dataTable.searchable,
});

const dt = ref();
const loading = ref(false);
const totalRecords = ref(0);
const rows = ref([]);
const selectedRows = ref([]);
const selectAll = ref(false);
const first = ref(0);
const filters = ref();
const lazyParams = ref({
  first: 0,
  rows: 10,
  sortField: null,
  sortOrder: null,
  searchable: dataTable.value.searchable,
  filters: filters.value,
});

const loadLazyData = (event) => {
  loading.value = true;
  lazyParams.value = {
    ...lazyParams.value,
    first: event?.first || first.value,
  };
  setTimeout(() => {
    axios
      .get(dataTable.value.dataUrl, {
        params: { lazyEvent: JSON.stringify(lazyParams.value) },
      })
      .then((res) => {
        let response = res.data;
        rows.value = response.data;
        totalRecords.value = response.total;
        loading.value = false;
      });
  }, 500);
};
onMounted(() => {
  loading.value = true;
});

const clearFilter = (event) => {
  initFilters();
  onFilter();
};
const initFilters = () => {
  filters.value = {
    global: { value: null, matchMode: "contains" },
    name: { value: null, matchMode: "contains" },
    email: { value: null, matchMode: "contains" },
    created_at: { value: null, matchMode: "contains" },
  };
};
initFilters();
const onPage = (event) => {
  lazyParams.value = event;
  loadLazyData(event);
};
const onSort = (event) => {
  lazyParams.value = {
    ...lazyParams.value,
    event: event,
  };
  loadLazyData(event);
};
const onFilter = (event) => {
  lazyParams.value.filters = filters.value;
  loadLazyData(event);
};
const onSelectAllChange = (event) => {
  selectAll.value = event.checked;

  if (selectAll) {
    axios.get(dataTable.value.dataUrl).then((res) => {
      let response = res.data;
      selectAll.value = true;
      selectedRows.value = response.data;
    });
  } else {
    selectAll.value = false;
    selectedRows.value = [];
  }
};
const onRowSelect = (event) => {
  selectAll.value = selectedRows.value.length === totalRecords.value;
  emit("update:modelValue", selectedRows.value);
};
const onRowUnselect = () => {
  selectAll.value = false;
  emit("update:modelValue", selectedRows.value);
};
const openNew = () => {
  formOption.value.visible = true;
};
const confirmDeleteSelected = () => {};
const close = () => {
  formOption.value.visible = false;
  formOption.value.loading = false;
  loadLazyData();
};
const rowDblClick = (event) => {
  let data = event.data;
  emit("handleDblClick", data);
};
const clearSelectedRows = () => {
  selectedRows.value = []
}
const onRowClick = (event) => {};
defineExpose({
  loadLazyData,
  selectedRows,
  clearSelectedRows
});
</script>