<script setup lang="ts">
/**
 * 文件职责：财务概览 TOP10 商品排行表。
 */
import type { FinanceOverviewTopProductItemDto } from '#/api/finance/overview';

import { computed } from 'vue';

import { Table } from 'ant-design-vue';

import {
  calcTopProductBarWidth,
  formatCurrency,
  formatPercent,
} from '../composables/overview-page/helpers';

interface Props {
  items: FinanceOverviewTopProductItemDto[];
  maxPercentage: number;
  periodDays: number;
}

const props = defineProps<Props>();

const columns = [
  {
    title: '排名',
    key: 'rank',
    width: 86,
  },
  {
    title: '商品名称',
    dataIndex: 'productName',
    key: 'productName',
  },
  {
    title: '销量',
    dataIndex: 'salesQuantity',
    key: 'salesQuantity',
    width: 100,
  },
  {
    title: '营收',
    key: 'revenueAmount',
    width: 120,
  },
  {
    title: '占比',
    key: 'percentage',
    width: 190,
  },
];

const dataSource = computed(() => props.items);

function resolveRankClass(rank: number) {
  if (rank === 1) return 'is-top1';
  if (rank === 2) return 'is-top2';
  if (rank === 3) return 'is-top3';
  return 'is-normal';
}
</script>

<template>
  <div class="fo-section-card fo-top-card">
    <div class="fo-section-title">
      TOP10 商品营收排行（近{{ props.periodDays }}天）
    </div>

    <Table
      class="fo-top-table"
      :columns="columns"
      :data-source="dataSource"
      :pagination="false"
      :row-key="(record) => `${record.rank}-${record.productName}`"
      size="middle"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'rank'">
          <span class="fo-rank-num" :class="resolveRankClass(record.rank)">
            {{ record.rank }}
          </span>
        </template>

        <template v-else-if="column.key === 'revenueAmount'">
          <span class="fo-revenue-text">{{
            formatCurrency(record.revenueAmount)
          }}</span>
        </template>

        <template v-else-if="column.key === 'percentage'">
          <div class="fo-percent-wrap">
            <div class="fo-percent-track">
              <div
                class="fo-percent-fill"
                :style="{
                  width: `${calcTopProductBarWidth(record.percentage, props.maxPercentage)}%`,
                }"
              ></div>
            </div>
            <span class="fo-percent-text">{{
              formatPercent(record.percentage)
            }}</span>
          </div>
        </template>
      </template>
    </Table>
  </div>
</template>
