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

import { computed, h, ref, watch } from 'vue';

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

import {
  formatCurrency,
  formatInteger,
  resolveTierTagStyle,
} from '../composables/member-page/helpers';

interface Props {
  canManage: boolean;
  detail: MemberDetailDto | null;
  loading: boolean;
  open: boolean;
  tagSaving: boolean;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'close'): void;
  (event: 'saveTags', tags: string[]): void;
}>();

const localTags = ref<string[]>([]);
const tagInputVisible = ref(false);
const tagInputValue = ref('');

const recentOrderColumns = [
  {
    title: '日期',
    dataIndex: 'orderedAt',
    key: 'orderedAt',
    width: 110,
  },
  {
    title: '订单号',
    dataIndex: 'orderNo',
    key: 'orderNo',
    width: 170,
  },
  {
    title: '金额',
    dataIndex: 'amount',
    key: 'amount',
    width: 120,
    customRender: ({ text }: { text: number }) =>
      formatCurrency(Number(text || 0)),
  },
  {
    title: '状态',
    dataIndex: 'statusText',
    key: 'statusText',
    width: 100,
    customRender: ({ text }: { text: string }) =>
      h(Tag, { color: resolveOrderStatusColor(text) }, () => text || '--'),
  },
  {
    title: '操作',
    key: 'action',
    width: 68,
    customRender: () =>
      h('span', { class: 'mm-order-action-placeholder' }, '详情'),
  },
];

const averageAmount = computed(() => props.detail?.averageAmount ?? 0);

watch(
  () => props.detail?.memberId,
  () => {
    localTags.value = [...(props.detail?.tags ?? [])];
    tagInputVisible.value = false;
    tagInputValue.value = '';
  },
  { immediate: true },
);

function removeTag(tag: string) {
  localTags.value = localTags.value.filter((item) => item !== tag);
}

function handleAddTag() {
  const value = tagInputValue.value.trim();
  if (!value) {
    tagInputVisible.value = false;
    tagInputValue.value = '';
    return;
  }

  if (localTags.value.includes(value)) {
    tagInputVisible.value = false;
    tagInputValue.value = '';
    return;
  }

  localTags.value = [...localTags.value, value];
  tagInputVisible.value = false;
  tagInputValue.value = '';
}

function handleSaveTags() {
  emit('saveTags', localTags.value);
}

function resolveOrderStatusColor(statusText: string) {
  if (statusText === '已完成') {
    return 'success';
  }

  if (statusText === '已取消') {
    return 'default';
  }

  return 'processing';
}
</script>

<template>
  <Drawer
    :open="props.open"
    width="620"
    title="会员详情"
    @close="emit('close')"
  >
    <Spin :spinning="props.loading || props.tagSaving">
      <template v-if="props.detail">
        <div class="mm-detail-head">
          <div
            class="mm-detail-avatar"
            :style="{ background: props.detail.avatarColor || '#1677ff' }"
          >
            {{ props.detail.avatarText }}
          </div>
          <div class="mm-detail-title-wrap">
            <div class="mm-detail-name-row">
              <span class="mm-detail-name">{{ props.detail.name }}</span>
              <Tag
                v-if="props.detail.tierName"
                :style="
                  resolveTierTagStyle(props.detail.tierColorHex || '#999999')
                "
              >
                {{ props.detail.tierName }}
              </Tag>
            </div>
            <div class="mm-detail-meta">
              {{ props.detail.mobileMasked }} | 注册于
              {{ props.detail.joinedAt }}
            </div>
          </div>
        </div>

        <div class="mm-section-title">消费概览</div>

        <div class="mm-overview-grid">
          <div class="mm-overview-item">
            <div class="value primary">
              {{ formatCurrency(props.detail.totalAmount) }}
            </div>
            <div class="label">累计消费</div>
          </div>
          <div class="mm-overview-item">
            <div class="value">
              {{ formatInteger(props.detail.orderCount) }}
            </div>
            <div class="label">消费次数</div>
          </div>
          <div class="mm-overview-item">
            <div class="value">{{ formatCurrency(averageAmount) }}</div>
            <div class="label">平均客单价</div>
          </div>
          <div class="mm-overview-item">
            <div class="value">
              {{ formatCurrency(props.detail.storedBalance) }}
            </div>
            <div class="label">储值余额</div>
            <div class="sub">
              实充 {{ formatCurrency(props.detail.storedRechargeBalance) }} |
              赠金
              {{ formatCurrency(props.detail.storedGiftBalance) }}
            </div>
          </div>
          <div class="mm-overview-item">
            <div class="value">
              {{ formatInteger(props.detail.pointsBalance) }}
            </div>
            <div class="label">积分</div>
          </div>
        </div>

        <div class="mm-section">
          <div class="mm-section-title">最近订单</div>
          <Table
            size="small"
            :columns="recentOrderColumns"
            :data-source="props.detail.recentOrders"
            :pagination="false"
            row-key="orderNo"
            :locale="{ emptyText: '暂无订单记录' }"
          />
        </div>

        <div class="mm-section">
          <div class="mm-section-title">会员标签</div>
          <div class="mm-tag-editor">
            <Tag
              v-for="tag in localTags"
              :key="tag"
              :closable="props.canManage"
              @close="removeTag(tag)"
            >
              {{ tag }}
            </Tag>

            <Input
              v-if="tagInputVisible && props.canManage"
              v-model:value="tagInputValue"
              class="mm-tag-input"
              size="small"
              placeholder="输入标签"
              @press-enter="handleAddTag"
              @blur="handleAddTag"
            />
            <Button
              v-else-if="props.canManage"
              size="small"
              type="dashed"
              @click="tagInputVisible = true"
            >
              + 自定义标签
            </Button>
          </div>
        </div>
      </template>
      <Empty v-else description="暂无详情" />
    </Spin>

    <template #footer>
      <div class="mm-detail-footer">
        <Button @click="emit('close')">关闭</Button>
        <Button
          v-if="props.canManage"
          type="primary"
          :loading="props.tagSaving"
          @click="handleSaveTags"
        >
          保存标签
        </Button>
      </div>
    </template>
  </Drawer>
</template>
