<script setup lang="ts">
import type { TablePaginationConfig, TableProps } from 'ant-design-vue';

/**
 * 文件职责：经营报表列表表格与分页。
 */
import type { FinanceBusinessReportListItemDto } from '#/api/finance';

import { h } from 'vue';

import { Button, Table, Tag } from 'ant-design-vue';

import {
  formatAverageOrderValue,
  formatCurrency,
  formatOrderCount,
  formatPercent,
  resolveReportStatusTagColor,
} from '../composables/report-page/helpers';

interface PaginationState {
  page: number;
  pageSize: number;
  total: number;
}

interface Props {
  canExport: boolean;
  loading: boolean;
  pagination: PaginationState;
  rows: FinanceBusinessReportListItemDto[];
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'downloadExcel', reportId: string): void;
  (event: 'downloadPdf', reportId: string): void;
  (event: 'pageChange', page: number, pageSize: number): void;
  (event: 'preview', reportId: string): void;
}>();

const columns: TableProps['columns'] = [
  {
    title: '日期',
    dataIndex: 'dateText',
    width: 160,
    customRender: ({ text }) => h('span', { class: 'frp-date' }, String(text)),
  },
  {
    title: '营业额',
    dataIndex: 'revenueAmount',
    width: 130,
    align: 'right',
    customRender: ({ record }) =>
      h('span', { class: 'frp-amount' }, formatCurrency(record.revenueAmount)),
  },
  {
    title: '订单数',
    dataIndex: 'orderCount',
    width: 100,
    align: 'right',
    customRender: ({ record }) =>
      h('span', { class: 'frp-value' }, formatOrderCount(record.orderCount)),
  },
  {
    title: '客单价',
    dataIndex: 'averageOrderValue',
    width: 120,
    align: 'right',
    customRender: ({ record }) =>
      h(
        'span',
        { class: 'frp-value' },
        formatAverageOrderValue(record.averageOrderValue),
      ),
  },
  {
    title: '退款率',
    dataIndex: 'refundRatePercent',
    width: 100,
    align: 'right',
    customRender: ({ record }) =>
      h(
        'span',
        { class: 'frp-value' },
        formatPercent(record.refundRatePercent),
      ),
  },
  {
    title: '成本总额',
    dataIndex: 'costTotalAmount',
    width: 130,
    align: 'right',
    customRender: ({ record }) =>
      h('span', { class: 'frp-value' }, formatCurrency(record.costTotalAmount)),
  },
  {
    title: '净利润',
    dataIndex: 'netProfitAmount',
    width: 130,
    align: 'right',
    customRender: ({ record }) => {
      const amount = Number(record.netProfitAmount || 0);
      return h(
        'span',
        {
          class: ['frp-amount', amount >= 0 ? 'is-profit' : 'is-loss'],
        },
        formatCurrency(amount),
      );
    },
  },
  {
    title: '利润率',
    dataIndex: 'profitRatePercent',
    width: 100,
    align: 'right',
    customRender: ({ record }) =>
      h(
        'span',
        { class: 'frp-value' },
        formatPercent(record.profitRatePercent),
      ),
  },
  {
    title: '状态',
    dataIndex: 'statusText',
    width: 96,
    customRender: ({ record }) =>
      h(
        Tag,
        {
          color: resolveReportStatusTagColor(record.status),
        },
        () => String(record.statusText || '--'),
      ),
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 210,
    customRender: ({ record }) => {
      const reportId = String(record.reportId || '');
      const canDownload = props.canExport && Boolean(record.canDownload);

      return h('div', { class: 'frp-action-group' }, [
        h(
          Button,
          {
            type: 'link',
            class: 'frp-action-link',
            onClick: () => emit('preview', reportId),
          },
          () => '预览',
        ),
        h(
          Button,
          {
            type: 'link',
            class: 'frp-action-link',
            disabled: !canDownload,
            onClick: () => emit('downloadPdf', reportId),
          },
          () => '下载PDF',
        ),
        h(
          Button,
          {
            type: 'link',
            class: 'frp-action-link',
            disabled: !canDownload,
            onClick: () => emit('downloadExcel', reportId),
          },
          () => '下载Excel',
        ),
      ]);
    },
  },
];

function handleTableChange(next: TablePaginationConfig) {
  emit('pageChange', Number(next.current || 1), Number(next.pageSize || 20));
}
</script>

<template>
  <div class="frp-table-card">
    <Table
      row-key="reportId"
      :columns="columns"
      :data-source="props.rows"
      :loading="props.loading"
      :pagination="{
        current: props.pagination.page,
        pageSize: props.pagination.pageSize,
        total: props.pagination.total,
        showSizeChanger: true,
        pageSizeOptions: ['20', '50', '100'],
        showTotal: (total: number) => `共 ${total} 条`,
      }"
      @change="handleTableChange"
    />
  </div>
</template>
