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

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

import { h } from 'vue';

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

import {
  formatCurrencyWithFraction,
  resolveTagColor,
} from '../composables/customer-analysis-page/helpers';

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

interface Props {
  keyword: string;
  loading: boolean;
  open: boolean;
  pagination: PaginationState;
  result: CustomerAnalysisSegmentListResultDto | null;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'detail', customerKey: string): void;
  (event: 'member', customerKey: string): void;
  (event: 'pageChange', page: number, pageSize: number): void;
  (event: 'profile', customerKey: string): void;
  (event: 'search'): void;
  (event: 'update:keyword', value: string): void;
}>();

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

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

  return h(
    'div',
    { class: 'ca-segment-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 CustomerAnalysisSegmentListItemDto),
  },
  {
    title: '累计消费',
    dataIndex: 'totalAmount',
    width: 120,
    customRender: ({ text }) => formatCurrencyWithFraction(Number(text || 0)),
  },
  {
    title: '下单次数',
    dataIndex: 'orderCount',
    width: 100,
  },
  {
    title: '客单价',
    dataIndex: 'averageAmount',
    width: 100,
    customRender: ({ text }) => formatCurrencyWithFraction(Number(text || 0)),
  },
  {
    title: '最近下单',
    dataIndex: 'lastOrderAt',
    width: 120,
  },
  {
    title: '会员等级',
    dataIndex: 'memberTierName',
    width: 110,
    customRender: ({ record }) => {
      const item = record as CustomerAnalysisSegmentListItemDto;
      if (!item.isMember) {
        return '--';
      }
      return item.memberTierName || '会员';
    },
  },
  {
    title: '标签',
    dataIndex: 'tags',
    customRender: ({ record }) =>
      renderTagList((record as CustomerAnalysisSegmentListItemDto).tags),
  },
  {
    title: '操作',
    key: 'action',
    width: 160,
    customRender: ({ record }) => {
      const item = record as CustomerAnalysisSegmentListItemDto;
      const actions = [
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            class: 'ca-segment-action',
            onClick: () => emit('detail', item.customerKey),
          },
          () => '详情',
        ),
        h(
          Button,
          {
            type: 'link',
            size: 'small',
            class: 'ca-segment-action',
            onClick: () => emit('profile', item.customerKey),
          },
          () => '画像',
        ),
      ];

      if (item.isMember) {
        actions.push(
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              class: 'ca-segment-action',
              onClick: () => emit('member', item.customerKey),
            },
            () => '会员',
          ),
        );
      }

      return h('div', { class: 'ca-segment-action-wrap' }, actions);
    },
  },
];

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

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

<template>
  <Drawer
    :open="props.open"
    width="980"
    title="客群明细"
    @close="emit('close')"
  >
    <div class="ca-segment-head">
      <div class="ca-segment-title">
        {{ props.result?.segmentTitle || '客群明细' }}
      </div>
      <div class="ca-segment-desc">
        {{ props.result?.segmentDescription || '--' }}
      </div>
    </div>

    <div class="ca-segment-toolbar">
      <Input
        class="ca-segment-search"
        :value="props.keyword"
        allow-clear
        placeholder="搜索姓名 / 手机号"
        @update:value="(value) => emit('update:keyword', String(value ?? ''))"
        @press-enter="emit('search')"
      />
      <Button type="primary" @click="emit('search')">查询</Button>
    </div>

    <Table
      row-key="customerKey"
      :columns="columns"
      :data-source="props.result?.items || []"
      :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"
      class="ca-segment-table"
      @change="handleTableChange"
    />
  </Drawer>
</template>
