<script setup lang="ts">
/**
 * 文件职责：发票记录表格与分页。
 */
import type { TablePaginationConfig, TableProps } from 'ant-design-vue';

import type { FinanceInvoiceRecordListItemDto } from '#/api/finance';
import type { VNode } from 'vue';

import { h } from 'vue';

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

import {
  formatCurrency,
  isIssuedInvoice,
  isPendingInvoice,
  resolveInvoiceStatusTagColor,
  resolveInvoiceTypeTagColor,
} from '../composables/invoice-page/helpers';

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

interface Props {
  canIssue: boolean;
  canVoid: boolean;
  loading: boolean;
  pagination: PaginationState;
  rows: FinanceInvoiceRecordListItemDto[];
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'detail', recordId: string): void;
  (event: 'issue', row: FinanceInvoiceRecordListItemDto): void;
  (event: 'pageChange', page: number, pageSize: number): void;
  (event: 'void', row: FinanceInvoiceRecordListItemDto): void;
}>();

function renderActionButtons(row: FinanceInvoiceRecordListItemDto) {
  const buttons: VNode[] = [];

  if (isPendingInvoice(row.status)) {
    if (props.canIssue) {
      buttons.push(
        h(
          Button,
          {
            type: 'link',
            class: 'fi-link-action',
            onClick: () => emit('issue', row),
          },
          () => '开票',
        ),
      );
    } else {
      buttons.push(
        h(
          Button,
          {
            type: 'link',
            class: 'fi-link-action',
            onClick: () => emit('detail', row.recordId),
          },
          () => '查看',
        ),
      );
    }

    return h('div', { class: 'fi-action-wrap' }, buttons);
  }

  buttons.push(
    h(
      Button,
      {
        type: 'link',
        class: 'fi-link-action',
        onClick: () => emit('detail', row.recordId),
      },
      () => '查看',
    ),
  );

  if (isIssuedInvoice(row.status) && props.canVoid) {
    buttons.push(
      h(
        Button,
        {
          type: 'link',
          danger: true,
          class: 'fi-link-action',
          onClick: () => emit('void', row),
        },
        () => '作废',
      ),
    );
  }

  return h('div', { class: 'fi-action-wrap' }, buttons);
}

const columns: TableProps['columns'] = [
  {
    title: '发票号码',
    dataIndex: 'invoiceNo',
    width: 190,
    customRender: ({ record }) =>
      h(
        'span',
        {
          class: 'fi-mono',
        },
        String(record.invoiceNo || '--'),
      ),
  },
  {
    title: '申请人 / 公司名',
    dataIndex: 'companyName',
    width: 220,
    customRender: ({ record }) =>
      h('div', { class: 'fi-company-cell' }, [
        h('div', { class: 'fi-applicant' }, String(record.applicantName || '--')),
        h('div', { class: 'fi-company' }, String(record.companyName || '--')),
      ]),
  },
  {
    title: '发票类型',
    dataIndex: 'invoiceTypeText',
    width: 110,
    customRender: ({ record }) =>
      h(
        Tag,
        { color: resolveInvoiceTypeTagColor(String(record.invoiceType || '')) },
        () => String(record.invoiceTypeText || '--'),
      ),
  },
  {
    title: '金额',
    dataIndex: 'amount',
    width: 130,
    align: 'right',
    customRender: ({ record }) =>
      h('span', { class: 'fi-amount' }, formatCurrency(Number(record.amount || 0))),
  },
  {
    title: '关联订单',
    dataIndex: 'orderNo',
    width: 170,
    customRender: ({ text }) =>
      h('span', { class: 'fi-mono' }, String(text || '--')),
  },
  {
    title: '状态',
    dataIndex: 'statusText',
    width: 100,
    customRender: ({ record }) =>
      h(
        Tag,
        { color: resolveInvoiceStatusTagColor(String(record.status || '')) },
        () => String(record.statusText || '--'),
      ),
  },
  {
    title: '申请时间',
    dataIndex: 'appliedAt',
    width: 180,
    customRender: ({ text }) => h('span', { class: 'fi-time' }, String(text || '--')),
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    customRender: ({ record }) => renderActionButtons(record),
  },
];

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

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