<script lang='ts' setup>
import type { InfiniteScrollCustomEvent, RefresherCustomEvent } from "@ionic/vue";
import type { AssetRecordBody, AssetRecordData } from "@/api/types";
import IconParkOutlineTransaction from "~icons/icon-park-outline/transaction";
import { client, safeClient } from "@/api";

const props = defineProps<{ code: string }>();
const [query, resetQuery] = useResetRef<AssetRecordBody>({
  limit: 20,
  offset: 0,
  assetCode: props.code,
});

const data = ref<AssetRecordData[]>([]);
const isFinished = ref(false);

async function fetchData() {
  const { data: record } = await safeClient(client.api.ledger.entries.get({
    query: query.value,
  }));
  data.value.push(...(record.value?.data || []));
  isFinished.value = (record.value?.data.length || 0) < query.value.limit!;
}

function reset() {
  resetQuery();
  data.value = [];
  isFinished.value = false;
}

async function handleRefresh(event: RefresherCustomEvent) {
  reset();
  await fetchData();
  setTimeout(() => {
    event.target.complete();
  }, 500);
}

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);
}

function isIncome(item: AssetRecordData): boolean {
  return Number(item.amount) > 0;
}

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

<template>
  <ion-page>
    <ion-header class="ion-no-border">
      <ion-toolbar class="ion-toolbar">
        <ui-back-button slot="start" />
        <ion-title>{{ code }}</ion-title>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true">
      <ion-refresher slot="fixed" @ion-refresh="handleRefresh($event)">
        <ion-refresher-content />
      </ion-refresher>

      <div class="ion-padding-horizontal text-md font-semibold my-4">
        资产记录
      </div>

      <!-- 资产记录列表 -->
      <div v-if="data.length > 0" class="space-y-2 pb-4">
        <div v-for="item in data" :key="item.id" class="ion-padding-horizontal">
          <div class="bg-gray-50 rounded-lg p-4">
            <div class="flex items-center justify-between mb-3">
              <div class="flex items-center space-x-3">
                <div>
                  <div class="text-sm font-semibold">
                    {{ item.accountType }}
                  </div>
                  <div class="text-xs text-text-500 mt-0.5">
                    {{ useDateFormat(item.createdAt, 'YYYY/MM/DD HH:mm:ss') }}
                  </div>
                </div>
              </div>
              <div class="text-right">
                <div
                  class="text-base font-bold"
                  :class="isIncome(item) ? 'text-success' : 'text-danger'"
                >
                  {{ isIncome(item) ? '+' : '' }}{{ Number(item.amount).toFixed(2) }}
                </div>
                <div class="text-xs text-text-500 mt-0.5">
                  {{ code }}
                </div>
              </div>
            </div>

            <div class="flex items-center justify-between text-xs">
              <div class="flex items-center space-x-6">
                <div>
                  <span class="text-text-500">余额</span>
                  <span class="ml-2 font-medium">{{ Number(item.availableAfter).toFixed(2) }}</span>
                </div>
              </div>
            </div>

            <div class="pt-3">
              <div class="text-xs text-text-500">
                <span>备注：</span>
                <span>{{ item.memo }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="!isFinished" class="flex items-center justify-center py-20">
        <ion-spinner name="crescent" />
      </div>
      <div v-else class="flex flex-col items-center justify-center py-20 text-text-500">
        <IconParkOutlineTransaction class="text-6xl mb-4 opacity-30" />
        <div class="text-sm">
          暂无资产记录
        </div>
      </div>

      <ion-infinite-scroll threshold="100px" @ion-infinite="handleInfinite">
        <ion-infinite-scroll-content
          loading-spinner="bubbles"
          loading-text="加载更多中..."
        />
      </ion-infinite-scroll>
    </ion-content>
  </ion-page>
</template>

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