<script lang="ts" setup>
/**
 * 顶栏 VIP 徽标：点击弹出诊所端风格会员气泡卡
 * 展示等级名（不展示 CUSTOM/V1 等编码）、开通信息、已开功能，并可查看开通记录
 */
import { computed, ref, watch } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

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

import { useAuthStore } from '#/store';

import VipBadgeCombo from './VipBadgeCombo.vue';
import VipStoreRecordsModal from './VipStoreRecordsModal.vue';

const userStore = useUserStore();
const authStore = useAuthStore();
const popoverOpen = ref(false);
const refreshing = ref(false);

const vip = computed(() => (userStore.userInfo as any)?.vip || null);
const storeId = computed(() => Number((userStore.userInfo as any)?.store_id || 0));
const storeName = computed(
  () =>
    String(
      (userStore.userInfo as any)?.store_name ||
        (userStore.userInfo as any)?.store?.name ||
        '',
    ),
);

const show = computed(() => !!vip.value);

/** 只展示等级名称，不展示 CUSTOM/V1 等编码 */
const levelName = computed(
  () => String(vip.value?.level_name || '').trim() || '普通会员',
);

const durationLabel = computed(
  () => String(vip.value?.duration_label || '').trim() || '普通会员',
);

/** 当前等级已开功能列表 */
const features = computed(() => {
  const list = vip.value?.features;
  return Array.isArray(list) ? list : [];
});

/** 到期文案 */
const expireText = computed(() => {
  const v = vip.value;
  if (!v) return '默认会员';
  if (v.is_lifetime) return '永久有效';
  const expireAt = Number(v.expire_at || 0);
  if (!expireAt) {
    if ((v.level_code || 'V0') === 'V0') return '默认会员';
    return '永久有效';
  }
  if (typeof v.expire_at === 'string' && String(v.expire_at).includes('-')) {
    return `有效期至 ${v.expire_at}`;
  }
  const d = new Date(expireAt * 1000);
  const pad = (n: number) => String(n).padStart(2, '0');
  return `有效期至 ${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
});

/** 开通时间文案（opened_at 为时间戳）；无数据返回空串 */
const openedAtText = computed(() => {
  const ts = Number(vip.value?.opened_at || 0);
  if (!ts) return '';
  const d = new Date(ts * 1000);
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
});

const openTypeText = computed(() =>
  String(vip.value?.open_type_txt || '').trim(),
);
const operatorText = computed(() => {
  const name = String(vip.value?.operator_name || '').trim();
  if (name) return name;
  const id = Number(vip.value?.operator_id || 0);
  if (id > 0) return `管理员#${id}`;
  return '';
});

/** 是否有开通流水信息：无则整块隐藏，避免展示「—」占位 */
const hasOpenInfo = computed(() => {
  const v = vip.value;
  if (!v) return false;
  return !!(
    openTypeText.value ||
    operatorText.value ||
    Number(v.opened_at || 0) > 0 ||
    Number(v.open_record_id || 0) > 0
  );
});

const hasVipVisual = computed(
  () => !!(vip.value?.badge_url || vip.value?.duration_badge_url),
);

const [RecordsModalComp, recordsModalApi] = useVbenModal({
  connectedComponent: VipStoreRecordsModal,
});

/**
 * 打开气泡时刷新 my-info
 * 为什么：登录态里的 vip 可能是旧缓存，缺少开通人/开通方式
 */
watch(popoverOpen, async (open) => {
  if (!open || refreshing.value) return;
  refreshing.value = true;
  try {
    await authStore.fetchUserInfo();
  } catch {
    // 刷新失败仍展示本地缓存
  } finally {
    refreshing.value = false;
  }
});

/** 打开本门店开通记录弹窗 */
function openRecords() {
  if (!storeId.value) return;
  popoverOpen.value = false;
  recordsModalApi.setData({
    store_id: storeId.value,
    store_name: storeName.value,
  });
  recordsModalApi.open();
}
</script>

<template>
  <div v-if="show" class="mr-2 flex items-center">
    <Popover
      v-model:open="popoverOpen"
      trigger="click"
      placement="bottomRight"
      overlay-class-name="header-vip-popover"
      :overlay-inner-style="{ padding: '0', background: 'transparent', boxShadow: 'none' }"
    >
      <template #content>
        <div class="header-vip-bubble">
          <!-- 黑金会员卡头图：与诊所设置/小程序会员卡同一视觉语言 -->
          <div class="header-vip-hero">
            <div class="header-vip-hero__glow"></div>
            <VipBadgeCombo
              v-if="hasVipVisual"
              size="lg"
              :badge-url="vip?.badge_url"
              :duration-badge-url="vip?.duration_badge_url"
              :level-name="levelName"
              :duration-label="durationLabel"
            />
            <div v-else class="header-vip-hero__placeholder">V</div>
            <div class="header-vip-hero__info">
              <div class="header-vip-hero__title-row">
                <span class="header-vip-hero__title">{{ levelName }}</span>
                <span class="header-vip-hero__chip">{{ durationLabel }}</span>
              </div>
              <div class="header-vip-hero__expire">{{ expireText }}</div>
            </div>
          </div>
          <div class="header-vip-body">
            <div v-if="hasOpenInfo" class="header-vip-rows">
              <div v-if="openTypeText" class="header-vip-row">
                <span class="header-vip-row__label">开通方式</span>
                <span class="header-vip-row__value">{{ openTypeText }}</span>
              </div>
              <div v-if="operatorText" class="header-vip-row">
                <span class="header-vip-row__label">开通人</span>
                <span class="header-vip-row__value">{{ operatorText }}</span>
              </div>
              <div v-if="openedAtText" class="header-vip-row">
                <span class="header-vip-row__label">开通时间</span>
                <span class="header-vip-row__value">{{ openedAtText }}</span>
              </div>
            </div>
            <div
              class="header-vip-features"
              :class="{ 'header-vip-features--alone': !hasOpenInfo }"
            >
              <div class="header-vip-features__title">已开功能</div>
              <div v-if="features.length" class="header-vip-features__list">
                <span
                  v-for="item in features"
                  :key="item.code"
                  class="header-vip-feature-tag"
                  :title="item.description || item.name"
                >
                  {{ item.name }}
                </span>
              </div>
              <div v-else class="header-vip-features__empty">暂无开通功能</div>
            </div>
            <Button
              v-if="storeId > 0 && hasOpenInfo"
              type="primary"
              block
              size="small"
              class="mt-3"
              @click="openRecords"
            >
              查看开通记录
            </Button>
          </div>
        </div>
      </template>
      <div
        class="header-vip-trigger"
        role="button"
        tabindex="0"
        @keydown.enter.prevent="popoverOpen = !popoverOpen"
      >
        <VipBadgeCombo
          size="sm"
          :badge-url="vip.badge_url"
          :duration-badge-url="vip.duration_badge_url"
          :level-name="levelName"
          :duration-label="durationLabel"
        />
      </div>
    </Popover>
    <RecordsModalComp />
  </div>
</template>

<style scoped>
.header-vip-trigger {
  cursor: pointer;
  border-radius: 8px;
  padding: 2px;
  transition: background 0.15s ease;
}
.header-vip-trigger:hover {
  background: hsl(var(--primary) / 0.1);
}
.header-vip-bubble {
  width: 320px;
  border-radius: 14px;
  overflow: hidden;
  border: 1px solid hsl(var(--border));
  background: hsl(var(--card, var(--background)));
  box-shadow: 0 8px 24px hsl(var(--foreground) / 0.12);
}
/* 黑金卡头：深色卡面亮暗主题通用 */
.header-vip-hero {
  position: relative;
  display: flex;
  align-items: center;
  gap: 14px;
  padding: 16px 18px;
  overflow: hidden;
  background:
    radial-gradient(120% 160% at 100% 0%, rgba(212, 175, 55, 0.22) 0%, rgba(212, 175, 55, 0) 45%),
    linear-gradient(135deg, #23201a 0%, #12100c 55%, #1f1a12 100%);
  border-bottom: 1px solid rgba(220, 186, 110, 0.3);
}
.header-vip-hero__glow {
  position: absolute;
  top: -50px;
  right: -40px;
  width: 160px;
  height: 160px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(240, 217, 168, 0.26) 0%, rgba(240, 217, 168, 0) 70%);
  pointer-events: none;
}
.header-vip-hero__placeholder {
  width: 72px;
  height: 72px;
  border-radius: 50%;
  background: radial-gradient(circle, rgba(212, 175, 55, 0.16) 0%, rgba(212, 175, 55, 0.04) 100%);
  border: 1px solid rgba(220, 186, 110, 0.4);
  color: #f0d9a8;
  text-shadow: 0 2px 8px rgba(212, 175, 55, 0.4);
  font-size: 28px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}
.header-vip-hero__info {
  position: relative;
  min-width: 0;
}
.header-vip-hero__title-row {
  display: flex;
  align-items: center;
  gap: 8px;
}
.header-vip-hero__title {
  font-size: 18px;
  font-weight: 700;
  line-height: 1.3;
  color: #f5e3bd;
  letter-spacing: 1px;
  text-shadow: 0 2px 6px rgba(0, 0, 0, 0.35);
}
.header-vip-hero__chip {
  flex-shrink: 0;
  padding: 0 8px;
  font-size: 11px;
  line-height: 18px;
  color: #e8cf9a;
  background: rgba(212, 175, 55, 0.1);
  border: 1px solid rgba(232, 207, 154, 0.5);
  border-radius: 999px;
}
.header-vip-hero__expire {
  margin-top: 6px;
  font-size: 12px;
  color: rgba(240, 224, 190, 0.75);
}
.header-vip-body {
  padding: 12px 14px 14px;
}
.header-vip-rows {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.header-vip-row {
  display: flex;
  justify-content: space-between;
  gap: 12px;
  font-size: 12px;
  line-height: 1.4;
}
.header-vip-row__label {
  flex-shrink: 0;
  color: hsl(var(--muted-foreground));
}
.header-vip-row__value {
  text-align: right;
  color: hsl(var(--foreground));
  word-break: break-all;
}
.header-vip-features {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid hsl(var(--border));
}
.header-vip-features--alone {
  margin-top: 0;
  padding-top: 0;
  border-top: none;
}
.header-vip-features__title {
  font-size: 12px;
  font-weight: 600;
  color: hsl(var(--foreground));
  margin-bottom: 8px;
}
.header-vip-features__list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.header-vip-feature-tag {
  display: inline-flex;
  align-items: center;
  padding: 2px 8px;
  border-radius: 999px;
  font-size: 11px;
  color: hsl(var(--primary));
  background: hsl(var(--primary) / 0.12);
  border: 1px solid hsl(var(--primary) / 0.25);
}
.header-vip-features__empty {
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
</style>
