<script setup lang="ts">
import type { CustomerDetailDto } from '#/api/customer';

import { computed } from 'vue';

import { Button, Drawer, Empty, Spin, Tag } from 'ant-design-vue';

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

interface Props {
  detail: CustomerDetailDto | null;
  loading: boolean;
  open: boolean;
  showMemberAction?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  showMemberAction: false,
});

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'member', customerKey: string): void;
  (event: 'profile', customerKey: string): void;
  (event: 'profilePage', customerKey: string): void;
}>();

const trendMaxAmount = computed(() =>
  Math.max(0, ...(props.detail?.trend.map((item) => item.amount) ?? [])),
);

function resolveAvatarText() {
  const name = props.detail?.name || '';
  return name ? name.slice(0, 1) : '客';
}

function resolveTrendHeight(amount: number) {
  if (trendMaxAmount.value <= 0) {
    return '0px';
  }

  const ratio = amount / trendMaxAmount.value;
  return `${Math.max(14, Math.round(ratio * 86))}px`;
}

function handleOpenProfile() {
  const customerKey = props.detail?.customerKey || '';
  if (!customerKey) {
    return;
  }

  emit('profile', customerKey);
}

function handleOpenProfilePage() {
  const customerKey = props.detail?.customerKey || '';
  if (!customerKey) {
    return;
  }

  emit('profilePage', customerKey);
}

function handleOpenMember() {
  const customerKey = props.detail?.customerKey || '';
  if (!customerKey) {
    return;
  }

  emit('member', customerKey);
}
</script>

<template>
  <Drawer
    :open="props.open"
    width="560"
    title="客户详情"
    @close="emit('close')"
  >
    <Spin :spinning="props.loading">
      <template v-if="props.detail">
        <div class="cl-detail-head">
          <div class="cl-detail-avatar">{{ resolveAvatarText() }}</div>
          <div class="cl-detail-title-wrap">
            <div class="cl-detail-name">{{ props.detail.name }}</div>
            <div class="cl-detail-meta">
              {{ props.detail.phoneMasked }} · 注册于
              {{ props.detail.registeredAt }}
            </div>
          </div>
          <div class="cl-detail-tags">
            <Tag
              v-for="tag in props.detail.tags"
              :key="`${tag.code}-${tag.label}`"
              :color="resolveTagColor(tag.tone)"
            >
              {{ tag.label }}
            </Tag>
          </div>
        </div>

        <div class="cl-overview-grid">
          <div class="cl-overview-item">
            <div class="label">累计下单</div>
            <div class="value">{{ props.detail.totalOrders }} 次</div>
          </div>
          <div class="cl-overview-item">
            <div class="label">累计消费</div>
            <div class="value primary">
              {{ formatCurrency(props.detail.totalAmount) }}
            </div>
          </div>
          <div class="cl-overview-item">
            <div class="label">复购率</div>
            <div class="value success">
              {{ formatPercent(props.detail.repurchaseRatePercent) }}
            </div>
          </div>
          <div class="cl-overview-item">
            <div class="label">会员等级</div>
            <div class="value">
              {{
                props.detail.member.isMember
                  ? props.detail.member.tierName || '会员'
                  : '未入会'
              }}
            </div>
          </div>
        </div>

        <div class="cl-drawer-section">
          <div class="cl-drawer-section-title">消费偏好</div>

          <div class="cl-preference-tags">
            <template
              v-if="props.detail.preference.preferredCategories.length > 0"
            >
              <Tag
                v-for="category in props.detail.preference.preferredCategories"
                :key="category"
                color="blue"
              >
                {{ category }}
              </Tag>
            </template>
            <span v-else class="cl-empty-text">暂无偏好品类</span>
          </div>

          <div class="cl-preference-list">
            <div class="cl-preference-row">
              <span>偏好下单时段</span>
              <span>{{
                props.detail.preference.preferredOrderPeaks || '--'
              }}</span>
            </div>
            <div class="cl-preference-row">
              <span>平均客单价</span>
              <span>{{ formatCurrency(props.detail.averageAmount) }}</span>
            </div>
            <div class="cl-preference-row">
              <span>常用配送方式</span>
              <span>{{
                props.detail.preference.preferredDelivery || '--'
              }}</span>
            </div>
          </div>
        </div>

        <div class="cl-drawer-section">
          <div class="cl-drawer-section-title">常购商品 TOP5</div>
          <div class="cl-top-product-list">
            <template v-if="props.detail.topProducts.length > 0">
              <div
                v-for="product in props.detail.topProducts"
                :key="`${product.rank}-${product.productName}`"
                class="cl-top-product-item"
              >
                <span class="rank">{{ product.rank }}</span>
                <span class="name">{{ product.productName }}</span>
                <span class="count">{{ product.count }}次</span>
              </div>
            </template>
            <Empty v-else description="暂无商品偏好" />
          </div>
        </div>

        <div class="cl-drawer-section">
          <div class="cl-drawer-section-title">近6月消费趋势</div>
          <div v-if="props.detail.trend.length > 0" class="cl-trend-bar-group">
            <div
              v-for="point in props.detail.trend"
              :key="point.label"
              class="cl-trend-bar-item"
            >
              <div class="amount">{{ formatCurrency(point.amount) }}</div>
              <div
                class="bar"
                :style="{ height: resolveTrendHeight(point.amount) }"
              ></div>
              <div class="month">{{ point.label }}</div>
            </div>
          </div>
          <Empty v-else description="暂无趋势数据" />
        </div>

        <div class="cl-drawer-section">
          <div class="cl-drawer-section-title">最近订单</div>
          <div
            v-if="props.detail.recentOrders.length > 0"
            class="cl-recent-orders"
          >
            <div
              v-for="order in props.detail.recentOrders"
              :key="order.orderNo"
              class="cl-recent-order-item"
            >
              <div class="left">
                <div class="summary">{{ order.itemsSummary }}</div>
                <div class="meta">
                  {{ order.orderedAt }} · {{ order.deliveryType }}
                </div>
              </div>
              <div class="amount">{{ formatCurrency(order.amount) }}</div>
            </div>
          </div>
          <Empty v-else description="暂无订单记录" />
        </div>
      </template>
      <Empty v-else description="暂无详情" />
    </Spin>

    <template #footer>
      <div class="cl-detail-footer">
        <Button @click="emit('close')">关闭</Button>
        <Button @click="handleOpenProfilePage">进入画像页</Button>
        <Button
          v-if="props.showMemberAction && props.detail?.member.isMember"
          @click="handleOpenMember"
        >
          会员详情
        </Button>
        <Button type="primary" @click="handleOpenProfile">查看完整画像</Button>
      </div>
    </template>
  </Drawer>
</template>
