<script lang='ts' setup>
import type { Treaty } from "@elysiajs/eden";
import type { InfiniteScrollCustomEvent } from "@ionic/vue";
import type { TreatyQuery } from "@/api/types";
import { client, safeClient } from "@/api";
import { tradeEvent } from "@/events";
import OrderCard from "./order-card.vue";

type Item = Treaty.Data<typeof client.api.spot_order.list.get>["data"][number];
type Body = TreatyQuery<typeof client.api.spot_order.list.get>;

const props = defineProps<{ symbol: string; status: Body["status"]; showCancel?: boolean }>();

const data = ref<Item[]>([]);
const isFinished = ref(false);
const [query] = useResetRef<Body>({
  symbol: props.symbol,
  limit: 20,
  offset: 0,
});

async function fetchData() {
  const { data: responseData } = await safeClient(client.api.spot_order.list.get({
    query: {
      ...query.value,
      status: props.status,
    },
  }));
  data.value.push(...(responseData.value?.data || []));
  isFinished.value = (responseData.value?.data.length || 0) < query.value.limit!;
}
function resetRwaData() {
  query.value.offset = 0;
  data.value = [];
  isFinished.value = false;
}
async function handleRefresh() {
  resetRwaData();
  await fetchData();
}
async function handleInfinite(event: InfiniteScrollCustomEvent) {
  if (isFinished.value) {
    event.target.complete();
    event.target.disabled = true;
    return;
  }
  query.value.offset! += query.value.limit!;
  await fetchData();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}

tradeEvent.on(() => {
  resetRwaData();
  fetchData();
});

onBeforeMount(() => {
  fetchData();
});
</script>

<template>
  <ui-empty v-if="data.length === 0" title="当前暂无委托" />
  <template v-else>
    <div v-for="item in data" :key="item.id" class="bg-faint rounded-xl p-3 mb-3">
      <OrderCard :item="item" :show-cancel="props.showCancel" @refresh="handleRefresh" />
    </div>
    <ion-infinite-scroll threshold="100px" @ion-infinite="handleInfinite">
      <ion-infinite-scroll-content
        loading-spinner="bubbles"
        loading-text="加载中..."
      />
    </ion-infinite-scroll>
  </template>
</template>

<style lang='css' scoped></style>
