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

import type { CustomerListItemDto, CustomerTagDto } from '#/api/customer';

import { h } from 'vue';

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

import {
  formatCurrency,
  resolveTagColor,
} from '../composables/customer-list-page/helpers';

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

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

const props = defineProps<Props>();

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

function renderCustomerCell(record: CustomerListItemDto) {
  return h('div', { class: 'cl-customer-cell' }, [
    h(
      'span',
      {
        class: 'cl-avatar',
        style: {
          background: record.avatarColor || '#1677ff',
        },
      },
      record.avatarText || record.name.slice(0, 1) || '客',
    ),
    h('div', { class: 'cl-customer-main' }, [
      h('div', { class: 'cl-customer-name' }, record.name || '--'),
      h('div', { class: 'cl-customer-phone' }, record.phoneMasked || '--'),
    ]),
  ]);
}

function renderOrderCountCell(record: CustomerListItemDto) {
  return h('div', { class: 'cl-order-count-cell' }, [
    h('span', { class: 'cl-order-count-value' }, String(record.orderCount)),
    h('span', {
      class: 'cl-order-count-bar',
      style: {
        width: `${Math.max(4, Math.min(100, record.orderCountBarPercent))}%`,
      },
    }),
  ]);
}

function renderTags(tags: CustomerTagDto[]) {
  if (tags.length === 0) {
    return '--';
  }

  return h(
    'div',
    { class: 'cl-tag-list' },
    tags.map((tag) =>
      h(
        Tag,
        {
          color: resolveTagColor(tag.tone),
        },
        () => tag.label,
      ),
    ),
  );
}

const columns: TableProps['columns'] = [
  {
    title: '客户信息',
    dataIndex: 'name',
    width: 220,
    customRender: ({ record }) =>
      renderCustomerCell(record as CustomerListItemDto),
  },
  {
    title: '下单次数',
    dataIndex: 'orderCount',
    width: 170,
    customRender: ({ record }) =>
      renderOrderCountCell(record as CustomerListItemDto),
  },
  {
    title: '累计消费',
    dataIndex: 'totalAmount',
    width: 130,
    customRender: ({ text }) =>
      h('span', { class: 'cl-amount' }, formatCurrency(Number(text || 0))),
  },
  {
    title: '客单价',
    dataIndex: 'averageAmount',
    width: 120,
    customRender: ({ text }) =>
      h(
        'span',
        { class: 'cl-average-amount' },
        formatCurrency(Number(text || 0)),
      ),
  },
  {
    title: '最近下单',
    dataIndex: 'lastOrderAt',
    width: 130,
  },
  {
    title: '客户标签',
    dataIndex: 'tags',
    customRender: ({ record }) =>
      renderTags((record as CustomerListItemDto).tags),
  },
  {
    title: '操作',
    key: 'action',
    width: 90,
    customRender: ({ record }) =>
      h(
        Button,
        {
          type: 'link',
          class: 'cl-detail-action',
          onClick: () =>
            emit('detail', String((record as CustomerListItemDto).customerKey)),
        },
        () => '查看',
      ),
  },
];

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

function resolveRowClassName(record: CustomerListItemDto) {
  return record.isDimmed ? 'cl-row-dimmed' : '';
}
</script>

<template>
  <div class="cl-table-card">
    <Table
      row-key="customerKey"
      :columns="columns"
      :data-source="props.rows"
      :loading="props.loading"
      :pagination="{
        current: props.pagination.page,
        pageSize: props.pagination.pageSize,
        total: props.pagination.total,
        showSizeChanger: false,
        showTotal: (total: number) => `共 ${total} 条`,
      }"
      :row-class-name="resolveRowClassName"
      @change="handleTableChange"
    />
  </div>
</template>
