<script lang="ts" setup>
/**
 * 周期总结定制视图（分受众版本 + 毛玻璃视觉）
 * 后端 action_payload.audience 区分 平台/诊所/药店/供应商/配送仓库 五个版本，
 * 各受众一套指标卡配置驱动渲染（不复制五份模板）；
 * 旧数据无 audience 字段时按平台版兼容展示
 */
import { computed, ref } from 'vue';

import { IconifyIcon as VbenIcon } from '@vben/icons';

const props = defineProps<{
  notice: Record<string, any>;
}>();

/** 单个指标瓷砖配置：取值 key + 展示样式 */
type MetricTile = {
  /** money 时值加 ¥ 前缀 */
  format?: 'money';
  icon: string;
  /** metrics 里的字段名 */
  key: string;
  label: string;
  /** normal 常规 / ok 正向 / warn 需关注 */
  tone: 'normal' | 'ok' | 'warn';
};

/** 受众元信息：徽标文案/图标 + 指标瓷砖布局 */
type AudienceMeta = {
  icon: string;
  kicker: string;
  label: string;
  tiles: MetricTile[];
};

/**
 * 五套受众配置：每个受众关心的指标不同
 * 平台看全局运营，诊所看挂号/处方，药店看订单/发货，供应商看结算，仓库看包裹
 */
const AUDIENCE_META: Record<string, AudienceMeta> = {
  platform: {
    label: '平台',
    icon: 'lucide:globe',
    kicker: '平台运营总结',
    tiles: [
      { key: 'active_store_count', label: '活跃门店', icon: 'lucide:store', tone: 'normal' },
      { key: 'register_total', label: '挂号总数', icon: 'lucide:stethoscope', tone: 'normal' },
      { key: 'rx_total', label: '处方总数', icon: 'lucide:file-text', tone: 'normal' },
      { key: '_rx_split', label: '线上 / 线下', icon: 'lucide:split', tone: 'normal' },
      { key: 'rx_pending', label: '待审处方', icon: 'lucide:hourglass', tone: 'warn' },
      { key: 'rx_passed', label: '已通过', icon: 'lucide:check-circle', tone: 'ok' },
      { key: 'rx_rejected', label: '已驳回', icon: 'lucide:x-circle', tone: 'warn' },
      { key: 'expire_soon', label: '临期待审', icon: 'lucide:alarm-clock', tone: 'warn' },
    ],
  },
  clinic: {
    label: '诊所',
    icon: 'lucide:stethoscope',
    kicker: '诊所运营总结',
    tiles: [
      { key: 'register_total', label: '挂号总数', icon: 'lucide:clipboard-list', tone: 'normal' },
      { key: 'register_completed', label: '已完成挂号', icon: 'lucide:check-circle', tone: 'ok' },
      { key: 'rx_total', label: '处方总数', icon: 'lucide:file-text', tone: 'normal' },
      { key: 'rx_pending', label: '当前待审', icon: 'lucide:hourglass', tone: 'warn' },
      { key: 'settled_amount', label: '已结算金额', icon: 'lucide:banknote', tone: 'ok', format: 'money' },
      { key: 'pending_amount', label: '待结算金额', icon: 'lucide:wallet', tone: 'warn', format: 'money' },
    ],
  },
  pharmacy: {
    label: '药店',
    icon: 'lucide:pill',
    kicker: '药店运营总结',
    tiles: [
      { key: 'order_total', label: '有效订单', icon: 'lucide:shopping-cart', tone: 'normal' },
      { key: 'order_amount', label: '营业额', icon: 'lucide:banknote', tone: 'ok', format: 'money' },
      { key: 'wait_delivery', label: '当前待发货', icon: 'lucide:package', tone: 'warn' },
      { key: 'refunding', label: '退款处理中', icon: 'lucide:rotate-ccw', tone: 'warn' },
      { key: 'settled_amount', label: '已结算金额', icon: 'lucide:circle-check-big', tone: 'ok', format: 'money' },
      { key: 'pending_amount', label: '待结算金额', icon: 'lucide:wallet', tone: 'warn', format: 'money' },
    ],
  },
  supplier: {
    label: '供应商',
    icon: 'lucide:factory',
    kicker: '供应商结算总结',
    tiles: [
      { key: 'ledger_count', label: '分账笔数', icon: 'lucide:receipt', tone: 'normal' },
      { key: 'settled_amount', label: '已结算金额', icon: 'lucide:banknote', tone: 'ok', format: 'money' },
      { key: 'pending_amount', label: '待结算金额', icon: 'lucide:wallet', tone: 'warn', format: 'money' },
    ],
  },
  warehouse: {
    label: '配送仓库',
    icon: 'lucide:warehouse',
    kicker: '配送仓运营总结',
    tiles: [
      { key: 'shipment_new', label: '新增包裹', icon: 'lucide:package-plus', tone: 'normal' },
      { key: 'shipment_sent', label: '已发货', icon: 'lucide:truck', tone: 'ok' },
      { key: 'shipment_wait', label: '当前待发货', icon: 'lucide:package', tone: 'warn' },
      { key: 'settled_amount', label: '已结算金额', icon: 'lucide:banknote', tone: 'ok', format: 'money' },
      { key: 'pending_amount', label: '待结算金额', icon: 'lucide:wallet', tone: 'warn', format: 'money' },
    ],
  },
};

const payload = computed(() => props.notice?.action_payload || {});
const metrics = computed(() => payload.value?.metrics || {});
const period = computed(() => payload.value?.period || {});
/** 旧数据无 audience 时兜底平台版，保证历史消息可读 */
const meta = computed(
  () => AUDIENCE_META[String(payload.value?.audience || 'platform')] || AUDIENCE_META.platform!,
);
/** 报告主体名称（诊所/药店/供应商/仓库名，平台为空不展示） */
const subjectName = computed(() => {
  const name = String(payload.value?.subject?.name || '');
  return name === '平台' ? '' : name;
});

/** 周期粒度徽标：日报/周报/月报/年报 */
const grainLabel = computed(() => {
  const grain = String(period.value?.grain || '');
  const map: Record<string, string> = {
    day: '日报',
    week: '周报',
    month: '月报',
    year: '年报',
  };
  return map[grain] || '总结';
});

/**
 * 指标瓷砖取值：money 格式加 ¥；平台版「线上/线下」是拼接虚拟字段特殊处理
 */
function tileValue(tile: MetricTile): string {
  const m = metrics.value;
  if (tile.key === '_rx_split') {
    return `${m.rx_online || 0} / ${m.rx_offline || 0}`;
  }
  const raw = m[tile.key];
  const val = raw === undefined || raw === null ? 0 : raw;
  return tile.format === 'money' ? `¥${val}` : String(val);
}

/** Markdown 摘要折叠状态：默认收起，指标卡已表达核心信息 */
const summaryOpen = ref(false);
</script>

<template>
  <div class="report-view">
    <!-- Hero：受众徽标 + 周期 + 主体名称，毛玻璃底 + 主色光斑 -->
    <div class="hero">
      <div class="hero__orb hero__orb--a"></div>
      <div class="hero__orb hero__orb--b"></div>
      <div class="hero__inner">
        <div class="hero__icon">
          <VbenIcon :icon="meta.icon" />
        </div>
        <div class="hero__meta">
          <div class="hero__badges">
            <span class="badge badge--audience">{{ meta.label }}</span>
            <span class="badge badge--grain">{{ grainLabel }}</span>
          </div>
          <div class="hero__label">{{ period.label || notice.detail || '-' }}</div>
          <div v-if="subjectName" class="hero__subject">{{ subjectName }}</div>
        </div>
        <div class="hero__kicker">{{ meta.kicker }}</div>
      </div>
    </div>

    <!-- 指标瓷砖：毛玻璃质感，按受众配置驱动 -->
    <div class="grid">
      <div
        v-for="tile in meta.tiles"
        :key="tile.key"
        class="metric"
        :class="[`metric--${tile.tone}`]"
      >
        <div class="metric-head">
          <span class="metric-icon">
            <VbenIcon :icon="tile.icon" />
          </span>
          <span class="metric-label">{{ tile.label }}</span>
        </div>
        <div class="metric-value">{{ tileValue(tile) }}</div>
      </div>
    </div>

    <!-- Markdown 摘要：折叠玻璃面板，默认收起（指标卡已表达核心信息） -->
    <div v-if="notice.content" class="summary">
      <button type="button" class="summary__toggle" @click="summaryOpen = !summaryOpen">
        <VbenIcon
          icon="lucide:chevron-right"
          class="summary__chevron"
          :class="{ 'is-open': summaryOpen }"
        />
        <span>文字摘要</span>
      </button>
      <div v-if="summaryOpen" class="summary__body whitespace-pre-wrap">
        {{ notice.content }}
      </div>
    </div>
  </div>
</template>

<style scoped>
.report-view {
  padding: 2px 0 8px;
}

/* ===== Hero：毛玻璃 + 双光斑 ===== */
.hero {
  position: relative;
  margin-bottom: 16px;
  overflow: hidden;
  border: 1px solid hsl(var(--border) / 0.8);
  border-radius: 18px;
  background: linear-gradient(
    165deg,
    hsl(var(--muted) / 0.45),
    hsl(var(--card, var(--background)))
  );
}

/* 柔和光斑：主色低透明度大半径模糊，撑起高级氛围 */
.hero__orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(38px);
  pointer-events: none;
}

.hero__orb--a {
  top: -70px;
  left: -40px;
  width: 220px;
  height: 220px;
  background: hsl(var(--primary) / 0.22);
}

.hero__orb--b {
  right: -60px;
  bottom: -90px;
  width: 240px;
  height: 240px;
  background: hsl(var(--primary) / 0.1);
}

/* 毛玻璃层：内容压在光斑上再 blur，形成磨砂质感 */
.hero__inner {
  position: relative;
  display: flex;
  gap: 14px;
  align-items: flex-start;
  padding: 18px 20px;
  backdrop-filter: blur(18px);
  -webkit-backdrop-filter: blur(18px);
}

.hero__icon {
  display: grid;
  flex-shrink: 0;
  place-items: center;
  width: 46px;
  height: 46px;
  border: 1px solid hsl(var(--primary) / 0.25);
  border-radius: 14px;
  background: hsl(var(--primary) / 0.12);
  color: hsl(var(--primary));
  box-shadow: inset 0 1px 0 hsl(var(--background) / 0.5);
}

.hero__icon :deep(svg) {
  width: 22px;
  height: 22px;
}

.hero__meta {
  flex: 1;
  min-width: 0;
}

.hero__badges {
  display: flex;
  gap: 6px;
  align-items: center;
}

.badge {
  padding: 2px 9px;
  border-radius: 999px;
  font-size: 11px;
  font-weight: 650;
  line-height: 17px;
  letter-spacing: 0.02em;
}

.badge--audience {
  border: 1px solid hsl(var(--primary) / 0.3);
  background: hsl(var(--primary) / 0.1);
  color: hsl(var(--primary));
}

.badge--grain {
  border: 1px solid hsl(var(--border));
  background: hsl(var(--muted) / 0.5);
  color: hsl(var(--muted-foreground));
}

.hero__label {
  margin-top: 8px;
  font-size: 18px;
  font-weight: 720;
  letter-spacing: -0.02em;
  color: hsl(var(--foreground));
}

.hero__subject {
  margin-top: 3px;
  overflow: hidden;
  font-size: 13px;
  color: hsl(var(--muted-foreground));
  text-overflow: ellipsis;
  white-space: nowrap;
}

.hero__kicker {
  flex-shrink: 0;
  font-size: 11px;
  font-weight: 700;
  letter-spacing: 0.08em;
  color: hsl(var(--primary) / 0.75);
  text-transform: uppercase;
  writing-mode: horizontal-tb;
}

/* ===== 指标瓷砖网格 ===== */
.grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 10px;
}

@media (min-width: 640px) {
  .grid {
    grid-template-columns: repeat(3, minmax(0, 1fr));
  }
}

/* 玻璃瓷砖：半透明底 + blur + 顶部内侧高光细线 */
.metric {
  position: relative;
  padding: 13px 14px;
  border: 1px solid hsl(var(--border) / 0.55);
  border-radius: 14px;
  background: hsl(var(--card, var(--background)) / 0.55);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  box-shadow:
    inset 0 1px 0 hsl(var(--background) / 0.6),
    0 1px 2px hsl(var(--foreground) / 0.03);
  transition:
    border-color 0.2s ease,
    transform 0.2s ease,
    box-shadow 0.2s ease;
}

.metric:hover {
  transform: translateY(-1px);
  border-color: hsl(var(--primary) / 0.3);
  box-shadow:
    inset 0 1px 0 hsl(var(--background) / 0.6),
    0 8px 24px hsl(var(--primary) / 0.08);
}

.metric--warn {
  border-color: hsl(var(--warning, 38 92% 50%) / 0.35);
  background:
    linear-gradient(
      150deg,
      hsl(var(--warning, 38 92% 50%) / 0.09),
      transparent 55%
    ),
    hsl(var(--card, var(--background)) / 0.55);
}

.metric--ok {
  border-color: hsl(var(--success) / 0.35);
  background:
    linear-gradient(
      150deg,
      hsl(var(--success) / 0.1),
      transparent 55%
    ),
    hsl(var(--card, var(--background)) / 0.55);
}

.metric-head {
  display: flex;
  gap: 7px;
  align-items: center;
}

.metric-icon {
  display: grid;
  place-items: center;
  width: 22px;
  height: 22px;
  border-radius: 7px;
  background: hsl(var(--primary) / 0.1);
  color: hsl(var(--primary));
}

.metric--warn .metric-icon {
  background: hsl(var(--warning, 38 92% 50%) / 0.14);
  color: hsl(var(--warning, 38 92% 40%));
}

.metric--ok .metric-icon {
  background: hsl(var(--success) / 0.14);
  color: hsl(var(--success));
}

.metric-icon :deep(svg) {
  width: 13px;
  height: 13px;
}

.metric-label {
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}

.metric-value {
  margin-top: 8px;
  overflow: hidden;
  font-size: 22px;
  font-weight: 700;
  letter-spacing: -0.03em;
  color: hsl(var(--foreground));
  text-overflow: ellipsis;
  white-space: nowrap;
  font-variant-numeric: tabular-nums;
}

.metric--warn .metric-value {
  color: hsl(var(--warning, 38 92% 40%));
}

/* 正向色走主题 --success 变量：亮/暗自适应，禁止 :global 泄漏全局 */
.metric--ok .metric-value {
  color: hsl(var(--success));
}

/* ===== Markdown 摘要折叠面板 ===== */
.summary {
  margin-top: 14px;
  overflow: hidden;
  border: 1px solid hsl(var(--border) / 0.55);
  border-radius: 14px;
  background: hsl(var(--card, var(--background)) / 0.55);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
}

.summary__toggle {
  display: flex;
  gap: 6px;
  align-items: center;
  width: 100%;
  padding: 11px 14px;
  border: none;
  background: transparent;
  font-size: 13px;
  font-weight: 600;
  color: hsl(var(--foreground));
  cursor: pointer;
  transition: background 0.15s ease;
}

.summary__toggle:hover {
  background: hsl(var(--muted) / 0.35);
}

.summary__chevron {
  width: 14px;
  height: 14px;
  color: hsl(var(--muted-foreground));
  transition: transform 0.2s ease;
}

.summary__chevron.is-open {
  transform: rotate(90deg);
}

.summary__body {
  padding: 12px 14px 14px;
  font-size: 13px;
  line-height: 1.8;
  color: hsl(var(--muted-foreground));
  border-top: 1px solid hsl(var(--border) / 0.4);
}

@media (prefers-reduced-motion: reduce) {
  .metric,
  .summary__chevron {
    transition: none;
  }

  .metric:hover {
    transform: none;
  }
}
</style>
