<script setup lang="ts">
import { useAuthStore } from "@/stores/auth.store";
import { ref, onMounted, type Ref } from "vue";
import SearcHistoryList from "./components/SearchHistoryList.vue";
import HistoryToolbar from "./components/HistoryToolbar.vue";
import * as userService from "@/services/user.service"
import type { SearchHistoryRecord } from "@/types/user.types"
import SpinComponent from "@/components/SpinComponent.vue";

const authStore = useAuthStore();

const records: Ref<SearchHistoryRecord[]> = ref([]);

const currentPage = ref(1);

const page = ref(1);

const total = ref(0);

const filterValue = ref("3");

const loading = ref(false)

function fetchHistory() {
  loading.value = true
  const currentUser = JSON.stringify(authStore.currentUser)
  userService.fetchHistory(currentUser, currentPage.value, 10, Number(filterValue.value)).then((resp) => {
    const respData = resp.data.data;
    records.value = respData.records;
    total.value = respData.total;
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function handleDelete(id: number) {
  const currentUser = JSON.stringify(authStore.currentUser)
  userService.delHistory(currentUser, id).then(() => {
    fetchHistory()
  })
}

function onfilterChange(value: string) {
  filterValue.value = value
  fetchHistory()
}

function ondeleteAll() {
  const currentUser = JSON.stringify(authStore.currentUser)
  userService.delAllHistory(currentUser).then(() => {
    fetchHistory()
  })
}

function onPaginationChange(p: number) {
  page.value = p
  fetchHistory()
}

onMounted(() => {
  fetchHistory();
});
</script>

<template>
  <HistoryToolbar @filterChange="onfilterChange" @deleteAll="ondeleteAll" />
  <SpinComponent :spinning="loading">
    <SearcHistoryList :data="records" @delete="handleDelete" class="history-list-wrap" />
  </SpinComponent>
  <div class="pagination">
    <a-pagination v-model:current="currentPage" :total="total" @change="onPaginationChange" />
  </div>
</template>

<style scoped lang="scss">
.history-list-wrap {
  margin-top: 16px;
}

.pagination {
  margin-top: 16px;
  text-align: right;

  :deep(.ant-pagination) {
    height: 32px;
  }
}
</style>
