<script setup lang="ts">
import { Card, Progress, Skeleton, Statistic, Table, Tag } from 'ant-design-vue';
import { computed, onMounted } from 'vue';

import { useFinanceStore } from '#/store/finance';

import { STATUS_CONFIG, formatStatus } from './status';

defineOptions({ name: 'FinanceReimbursementStatistics' });

const financeStore = useFinanceStore();

const loading = computed(() => financeStore.loading.reimbursements);

const statusSummary = computed(() => {
  const summary = new Map<
    string,
    { count: number; baseAmount: number }
  >();
  (Object.keys(STATUS_CONFIG) as Array<keyof typeof STATUS_CONFIG>).forEach(
    (status) => {
      summary.set(status, { count: 0, baseAmount: 0 });
    },
  );
  financeStore.reimbursements.forEach((item) => {
    const key = summary.get(item.status);
    if (!key) return;
    key.count += 1;
    key.baseAmount += item.amountInBase ?? 0;
  });
  const totalCount = Array.from(summary.values()).reduce(
    (acc, cur) => acc + cur.count,
    0,
  );
  return Array.from(summary.entries()).map(([status, value]) => ({
    status,
    count: value.count,
    baseAmount: value.baseAmount,
    percentage: totalCount === 0 ? 0 : Math.round((value.count / totalCount) * 100),
  }));
});

const monthlySummary = computed(() => {
  const map = new Map<
    string,
    { total: number; baseAmount: number; approved: number; pending: number }
  >();
  financeStore.reimbursements.forEach((item) => {
    const month = item.transactionDate.slice(0, 7);
    if (!map.has(month)) {
      map.set(month, { total: 0, baseAmount: 0, approved: 0, pending: 0 });
    }
    const target = map.get(month)!;
    target.total += item.amount;
    target.baseAmount += item.amountInBase ?? 0;
    if (item.status === 'approved' || item.status === 'paid') {
      target.approved += item.amountInBase ?? 0;
    }
    if (item.status === 'draft' || item.status === 'pending') {
      target.pending += item.amountInBase ?? 0;
    }
  });
  return Array.from(map.entries())
    .map(([month, value]) => ({
      month,
      ...value,
    }))
    .sort((a, b) => (a.month < b.month ? 1 : -1))
    .slice(0, 12);
});

const projectSummary = computed(() => {
  const map = new Map<
    string,
    { count: number; baseAmount: number }
  >();
  financeStore.reimbursements.forEach((item) => {
    const key = item.project || '未指定项目';
    if (!map.has(key)) {
      map.set(key, { count: 0, baseAmount: 0 });
    }
    const target = map.get(key)!;
    target.count += 1;
    target.baseAmount += item.amountInBase ?? 0;
  });
  return Array.from(map.entries())
    .map(([project, value]) => ({
      project,
      ...value,
    }))
    .sort((a, b) => b.baseAmount - a.baseAmount)
    .slice(0, 10);
});

onMounted(() => {
  if (financeStore.reimbursements.length === 0) {
    financeStore.fetchReimbursements();
  }
});
</script>

<template>
  <div class="p-6 space-y-4">
    <Card title="状态分布">
      <Skeleton :loading="loading" active>
        <div class="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          <div
            v-for="item in statusSummary"
            :key="item.status"
            class="border rounded-md p-4 space-y-3"
          >
            <div class="flex items-center justify-between">
              <Tag :color="formatStatus(item.status).color">
                {{ formatStatus(item.status).label }}
              </Tag>
              <span class="text-sm text-gray-500">
                {{ formatStatus(item.status).description }}
              </span>
            </div>
            <Statistic title="单据数量" :value="item.count" />
            <Statistic
              title="折合金额 (CNY)"
              :precision="2"
              :value="item.baseAmount"
            />
            <Progress :percent="item.percentage" />
          </div>
        </div>
      </Skeleton>
    </Card>

    <Card title="按月统计（最近12个月）">
      <Skeleton :loading="loading" active>
        <Table
          :data-source="monthlySummary"
          :pagination="false"
          row-key="month"
          size="small"
          bordered
        >
          <Table.Column title="月份" dataIndex="month" key="month" />
          <Table.Column
            title="原币合计"
            key="total"
            customRender="total"
          >
            <template #bodyCell="{ record }">
              {{ record.total.toFixed(2) }}
            </template>
          </Table.Column>
          <Table.Column
            title="折合CNY"
            key="baseAmount"
            customRender="baseAmount"
          >
            <template #bodyCell="{ record }">
              {{ record.baseAmount.toFixed(2) }}
            </template>
          </Table.Column>
          <Table.Column
            title="已批准金额 (CNY)"
            key="approved"
            customRender="approved"
          >
            <template #bodyCell="{ record }">
              {{ record.approved.toFixed(2) }}
            </template>
          </Table.Column>
          <Table.Column
            title="待审批金额 (CNY)"
            key="pending"
            customRender="pending"
          >
            <template #bodyCell="{ record }">
              {{ record.pending.toFixed(2) }}
            </template>
          </Table.Column>
        </Table>
      </Skeleton>
    </Card>

    <Card title="项目费用 Top 10">
      <Skeleton :loading="loading" active>
        <Table
          :data-source="projectSummary"
          :pagination="false"
          row-key="project"
          size="small"
          bordered
        >
          <Table.Column title="项目" dataIndex="project" key="project" />
          <Table.Column title="单据数量" dataIndex="count" key="count" />
          <Table.Column
            title="折合金额 (CNY)"
            key="baseAmount"
            customRender="baseAmount"
          >
            <template #bodyCell="{ record }">
              {{ record.baseAmount.toFixed(2) }}
            </template>
          </Table.Column>
        </Table>
      </Skeleton>
    </Card>
  </div>
</template>
