<script setup lang="ts">
import { onMounted, ref } from "vue";
import PageHeader from "@/components/PageHeader.vue";
import * as collectionService from "@/services/collection.service"
import type { Collections } from "@/types/collection.types";
import SpinComponent from "@/components/SpinComponent.vue";

const currentPage = ref(1);
const collections = ref<Collections | null>(null)
const loading = ref(false)

function fetchList(page: number = 1) {
  loading.value = true
  collectionService.list(page).then((colls) => {
    collections.value = colls
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

function onRemove(index: number, id: number) {
  collectionService.remove(id).then(() => {
    collections.value?.items.splice(index, 1)
    fetchList()
  })
}

function onPaginationChange(page: number) {
  fetchList(page)
}

onMounted(() => {
  fetchList()
})
</script>

<template>
  <PageHeader title="我的收藏" />
  <a-tabs>
    <a-tab-pane key="favorite" tab="文献收藏">
      <SpinComponent :spinning="loading">
        <div class="item-wrap" v-for="(item, index) in collections?.items" :key="index">
          <a-row type="flex" justify="space-between" :gutter="8">
            <a-col>
              <h4>
                <RouterLink :to="'/detail/' + item.paperId" target="_blank">{{ item.title }}</RouterLink>
              </h4>
              <div class="metadata">作者：{{ item.authors }} 机构：{{ item.units }}</div>
            </a-col>
            <a-col>
              <a-popconfirm
                title="确定取消收藏？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="onRemove(index, item.id)"
                placement="topRight"
              >
                <a href="javascript:void(0)">取消收藏</a>
              </a-popconfirm>
            </a-col>
          </a-row>
        </div>
      </SpinComponent>
    </a-tab-pane>
  </a-tabs>
  <div class="pagination" v-if="collections">
    <a-pagination v-model:current="currentPage" :total="collections?.total" @change="onPaginationChange" />
  </div>
</template>

<style scoped lang="scss">
@import "@/assets/base.scss";

.item-wrap {
  margin-top: 8px;
  padding: 8px 16px;
  border: 1px solid $border-color-primary;
  border-radius: 5px;

  &:first-child {
    margin-top: 0;
  }

  &:hover {
    background-color: #fcfcfc;
  }

  .metadata {
    color: gray;
  }
}

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

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