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

const authStore = useAuthStore();

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

const currentPage = ref(1);

const page = ref(1);

const total = ref(0);

const filterValue = ref("3");

function fetchBrowsing() {
  const currentUser = JSON.stringify(authStore.currentUser)
  userService.fetchBrowsing(currentUser, page.value, 10, Number(filterValue.value)).then((resp) => {
    const respData = resp.data.data;
    records.value = respData.records;
    total.value = respData.total;
  })
}

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

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

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

function onNext() {
  page.value = currentPage.value + 1;
  fetchBrowsing();
}

function onPrev() {
  page.value = currentPage.value - 1;
  fetchBrowsing();
}

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

<template>
  <HistoryToolbar @filterChange="onfilterChange" @deleteAll="ondeleteAll" />
  <HistoryList :data="records" @delete="handleDelete" class="history-list-wrap" />
  <div class="pagination">
    <a-pagination v-model:current="currentPage" simple :total="total">
      <template #itemRender="{ type, originalElement }">
        <a-button v-if="type === 'prev'" size="small" @click="onPrev()"> 上一页</a-button>
        <a-button v-else-if="type === 'next'" size="small" @click="onNext()">下一页</a-button>
        <component :is="originalElement" v-else></component>
      </template>
    </a-pagination>
  </div>
</template>

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

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

  .ant-pagination {
    height: 28px;
  }
}
</style>
