<script lang="ts" setup>
/**
 * 商品订单卡片看板（C 端紧凑排版 + Apple 毛玻璃）：与列表视图展示同一批字段，仅排版不同
 *
 * 排版语言参考 C 端 App 订单列表（外卖/电商）：
 * - 多列自适应网格（minmax 自动 1-3 列），单卡窄而紧凑，减少纵向占用
 * - 卡片：毛玻璃 + 14px 圆角 + hairline 细边框；状态用「彩点 + 彩字」
 * - 商品行右侧直接放合计金额（C 端惯例），人员/收货信息压成内联小字行
 * - 语义标签：tinted 小胶囊（同色低透明度底，无边框）
 *
 * 数据自取：props.formValues 变化时重置到第 1 页，触底自动加载下一页。
 * 行操作复用父级 buildRowActions（与列表 #action 槽同一份定义）。
 */
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';

import { Button, Empty, Image, message, Spin, Switch } from 'ant-design-vue';

import { CardActions } from '#/components/table-action';
import SensitiveText from '#/components/sensitive-text/SensitiveText.vue';
import { pillStyle, tagColorHex } from '#/utils/tagColor';

import { getOrderList } from '../api';
import {
  IS_ONLINE_FALLBACK,
  IS_ONLINE_MAP,
  ORDER_STATUS_MAP,
  ORDER_TYPE_MAP,
  PRESCRIPTION_TYPE_MAP,
} from '../config/constants';

const props = defineProps<{
  /** 顶部统一搜索条件（含 search_time / patient_keyword / doctor_keyword 等） */
  formValues?: Record<string, any>;
  /** 父级构造行操作（与列表 #action 槽同一份定义） */
  buildRowActions: (row: Record<string, any>) => {
    actions: any[];
    dropDownActions: any[];
  };
  /** 金额是否可点调价（与列表 price-info 槽一致） */
  canPercentAdjust?: (row: Record<string, any>) => boolean;
}>();

const emit = defineEmits<{
  openStore: [storeId: number];
  openDoctor: [row: Record<string, any>];
  openUserPatients: [payload: { userId: number; nickname: string; avatarurl: string }];
  openPatient: [payload: { upId: number; patientName: string }];
  openWarehouse: [row: Record<string, any>, wh: { id: number; name: string }];
  toggleFreeShipping: [row: Record<string, any>, checked: boolean];
  percentAdjust: [row: Record<string, any>];
  goRegister: [row: Record<string, any>];
}>();

const items = ref<any[]>([]);
const page = ref(1);
const pageCount = ref(1);
const loading = ref(false);
const loadingMore = ref(false);
/** 请求序号：只应用最后一次响应，避免快速改筛选时旧结果覆盖新列表 */
let requestSeq = 0;
/** 已手动展开商品明细的订单 id 集合 */
const expandedIds = ref<Set<number>>(new Set());

const scrollEl = ref<HTMLElement | null>(null);
const sentinelEl = ref<HTMLElement | null>(null);
let observer: IntersectionObserver | null = null;

const hasMore = computed(() => page.value < pageCount.value);

/** 处方类型元数据（全量 0-7，含特色方），无处方类型时返回 null */
function prescriptionTypeMeta(row: Record<string, any>) {
  const type = Number(row?.prescription_type);
  return Number.isFinite(type) ? (PRESCRIPTION_TYPE_MAP[type] ?? null) : null;
}

/** 状态元数据 */
function statusMeta(row: Record<string, any>) {
  return ORDER_STATUS_MAP[Number(row?.status)] ?? null;
}

/** 就诊来源元数据（0/未知兜底线下） */
function isOnlineMeta(row: Record<string, any>) {
  return IS_ONLINE_MAP[Number(row?.is_online)] ?? IS_ONLINE_FALLBACK;
}

/** 非处方订单（order_type=2/3）显示订单类型 */
function orderTypeMeta(row: Record<string, any>) {
  return ORDER_TYPE_MAP[Number(row?.order_type)] ?? null;
}

/** 卡片主类型胶囊：与列表 delivery-method 槽同口径——仅预约购药（order_type=2）显示订单类型，其余显示处方类型 */
function headTypeMeta(row: Record<string, any>) {
  if (Number(row?.order_type) === 2) {
    return orderTypeMeta(row);
  }
  return prescriptionTypeMeta(row);
}

/** 首个商品（商品区首图/首名展示用） */
function firstItem(row: Record<string, any>) {
  return Array.isArray(row.product_order_items) ? row.product_order_items[0] : null;
}

/** 商品总件数（中药按剂量折算与明细 chips 同口径） */
function totalPieces(row: Record<string, any>) {
  const list = Array.isArray(row.product_order_items) ? row.product_order_items : [];
  return list.reduce((sum: number, item: any) => {
    const factor =
      Number(row.prescription_type) === 1 && Number(item.dosage) > 0
        ? Number(item.dosage)
        : 1;
    return sum + Number(item.number || 0) * factor;
  }, 0);
}

/** 收货地址拼装（与列表 formatExpressAddress 同口径） */
function expressAddress(row: Record<string, any>) {
  if (Number(row.delivery_method) === 1) {
    return row.store?.position || row.store?.name || '到店自提';
  }
  const region = row.address?.region || row.express_region || '';
  const detail = row.address?.detail_address || row.express_address || '';
  return [region, detail].filter(Boolean).join(' ') || '—';
}

/** 挂号金额（与列表 formatRegisterAmount 同口径） */
function registerAmount(row: Record<string, any>) {
  if (row.register_id == null || row.register_id === '') return '—';
  const n = Number(row.register_price);
  return Number.isFinite(n) ? `¥${n.toFixed(2)}` : '—';
}

/* ---- 人员内联行解析（与列表 OrderUserInfoCell 同口径，卡片用紧凑内联行省高度） ---- */

/** 下单微信用户 ID */
function resolveUserId(row: Record<string, any>) {
  return Number(row.user?.id || row.user_id || 0);
}

/** 就诊人 ID */
function resolveUpId(row: Record<string, any>) {
  return Number(row.up_id || row.user_patient?.id || row.userPatient?.id || 0);
}

/** 就诊人姓名（多来源兜底） */
function patientNameOf(row: Record<string, any>) {
  return row.user_patient?.name || row.userPatient?.name || row.patient || '—';
}

/** 是否有代付信息（有付款人 ID 或至少有付款人类型） */
function hasPayUser(row: Record<string, any>) {
  const payUserId = Number(row.pay_user_id || row.pay_user?.id || 0);
  return payUserId > 0 || Number(row.pay_user_type || 0) > 0;
}

/** 代付展示文案：[类型]名字（医生代付回落医生名，就诊人代付回落就诊人名） */
function payUserText(row: Record<string, any>) {
  const t = Number(row.pay_user_type || 0);
  const typeLabel = t === 2 ? '医生' : t === 3 ? '就诊人' : t === 1 ? '用户' : '—';
  const nick = String(row.pay_user?.nickname || '').trim();
  let name = nick;
  if (!name && t === 2 && row.doctor?.name) name = String(row.doctor.name);
  if (!name && t === 3) name = String(patientNameOf(row));
  return `[${typeLabel}] ${name || '—'}`;
}

/** 点击就诊人：打开详情弹窗 */
function onPatientClick(row: Record<string, any>) {
  const upId = resolveUpId(row);
  if (!upId) return;
  emit('openPatient', { upId, patientName: String(patientNameOf(row)) });
}

/** 点击下单用户：打开该用户就诊人列表 */
function onUserClick(row: Record<string, any>) {
  const userId = resolveUserId(row);
  if (!userId) return;
  emit('openUserPatients', {
    userId,
    nickname: String(row.user?.nickname || ''),
    avatarurl: String(row.user?.avatarurl || ''),
  });
}

/** 切换某订单的商品明细展开态 */
function toggleExpand(row: Record<string, any>) {
  const id = Number(row.id);
  const next = new Set(expandedIds.value);
  if (next.has(id)) {
    next.delete(id);
  } else {
    next.add(id);
  }
  expandedIds.value = next;
}

/**
 * 拉取一页数据；reset 时清空列表并回到第 1 页
 * 用 requestSeq 丢弃过期响应，防止筛选连点时旧条件结果覆盖新条件
 */
async function fetchPage(targetPage: number, reset = false) {
  const seq = ++requestSeq;
  if (reset) {
    loading.value = true;
  } else {
    loadingMore.value = true;
  }
  try {
    const res = await getOrderList({
      page: targetPage,
      pageSize: 12,
      ...(props.formValues || {}),
    });
    if (seq !== requestSeq) return;
    items.value = reset ? (res?.items ?? []) : [...items.value, ...(res?.items ?? [])];
    page.value = res?.page ?? targetPage;
    pageCount.value = res?.page_count ?? 1;
  } catch (error) {
    if (seq !== requestSeq) return;
    console.error(error);
    message.error('加载订单列表失败');
  } finally {
    if (seq === requestSeq) {
      loading.value = false;
      loadingMore.value = false;
    }
  }
}

/** 筛选条件变化：重置回第 1 页 */
async function reload() {
  page.value = 1;
  items.value = [];
  await fetchPage(1, true);
}

/**
 * 操作成功后的原地刷新：保留当前页码，避免退款/发货后跳回第 1 页
 * 卡片是累积加载的，这里折衷为按已加载条数一次性重拉（页码 1、pageSize=已加载数）
 */
async function refreshKeepPage() {
  const loaded = Math.max(items.value.length, 12);
  const seq = ++requestSeq;
  loading.value = true;
  try {
    const res = await getOrderList({
      page: 1,
      pageSize: loaded,
      ...(props.formValues || {}),
    });
    if (seq !== requestSeq) return;
    items.value = res?.items ?? [];
    // 折算页数：保持触底加载能继续接在后面
    page.value = Math.ceil((res?.items?.length ?? 0) / 12) || 1;
    pageCount.value = Math.ceil((res?.total ?? 0) / 12) || 1;
  } catch (error) {
    if (seq === requestSeq) console.error(error);
  } finally {
    if (seq === requestSeq) loading.value = false;
  }
}

defineExpose({ reload, refreshKeepPage });

async function loadMore() {
  if (!hasMore.value || loading.value || loadingMore.value) return;
  await fetchPage(page.value + 1, false);
}

/** 触底哨兵：滚动到底部附近自动加载下一页 */
function setupObserver() {
  observer?.disconnect();
  if (!sentinelEl.value) return;
  observer = new IntersectionObserver(
    (entries) => {
      if (entries.some((e) => e.isIntersecting)) {
        void loadMore();
      }
    },
    { root: scrollEl.value, rootMargin: '120px' },
  );
  observer.observe(sentinelEl.value);
}

watch(
  () => props.formValues,
  () => {
    void reload();
  },
  { deep: true },
);

onMounted(async () => {
  await reload();
  await nextTick();
  setupObserver();
});

onBeforeUnmount(() => {
  observer?.disconnect();
  observer = null;
});
</script>

<template>
  <div ref="scrollEl" class="po-card-scroll">
    <Spin :spinning="loading">
      <div v-if="items.length" class="po-card-grid">
        <div v-for="row in items" :key="row.id" class="po-card">
          <!-- 角落径向荧光（与提现管理统计岛同款质感装饰） -->
          <div class="po-card__glow" />
          <!-- 行1 头部：诊所名（可点）+ 状态彩点 -->
          <div class="po-card__head">
            <button
              v-if="row.store?.id"
              type="button"
              class="po-card__store"
              @click="emit('openStore', row.store.id)"
            >
              <span class="po-card__store-name">{{ row.store?.name || '—' }}</span>
              <span class="po-card__store-arrow">›</span>
            </button>
            <span v-else class="po-card__store-name">{{ row.store?.name || '—' }}</span>
            <span
              v-if="statusMeta(row)"
              class="po-card__status"
              :style="{ color: tagColorHex(statusMeta(row)!.color) }"
            >
              <i
                class="po-card__status-dot"
                :style="{ background: tagColorHex(statusMeta(row)!.color) }"
              ></i>
              {{ statusMeta(row)!.label }}
            </span>
          </div>
          <!-- 行2 单号/时间 + 语义胶囊同一行（紧凑：小灰字在左，胶囊接排换行） -->
          <div class="po-card__meta">
            <span class="truncate">{{ row.order_no }}</span>
            <span class="po-card__dot">·</span>
            <span class="shrink-0">{{ row.created_at || '—' }}</span>
          </div>
          <div class="po-card__pills">
            <span v-if="headTypeMeta(row)" class="po-pill" :style="pillStyle(headTypeMeta(row)!.color)">
              {{ headTypeMeta(row)!.label }}
            </span>
            <span class="po-pill" :style="pillStyle(isOnlineMeta(row).color)">
              {{ isOnlineMeta(row).label }}
            </span>
            <span
              v-if="row.is_proxy_pay || Number(row.pay_user_type) === 2"
              class="po-pill"
              :style="pillStyle('magenta')"
            >
              代支付
            </span>
            <span v-if="row.delivery_method === 1" class="po-pill" :style="pillStyle('blue')">
              到店自提
            </span>
            <span v-else-if="row.delivery_method === 0" class="po-pill" :style="pillStyle('green')">
              上门快递
            </span>
            <span class="po-pill" :style="pillStyle(row.is_sync_erp === 1 ? 'green' : 'red')">
              {{ row.is_sync_erp === 1 ? 'Erp已同步' : 'Erp未同步' }}
            </span>
            <template
              v-if="Array.isArray(row.delivery_warehouses) && row.delivery_warehouses.length"
            >
              <button
                v-for="wh in row.delivery_warehouses"
                :key="wh.id"
                type="button"
                class="po-pill po-pill--action"
                :style="pillStyle('processing')"
                @click="emit('openWarehouse', row, wh)"
              >
                {{ wh.name }} ›
              </button>
            </template>
          </div>
          <!-- 行3 商品行（C 端惯例：左图文右合计金额），点击展开全部明细 -->
          <div class="po-card__goods" role="button" @click="toggleExpand(row)">
            <div v-if="firstItem(row)" class="po-card__goods-thumb">
              <Image
                v-if="firstItem(row)?.drug_image"
                :src="firstItem(row).drug_image"
                :preview="false"
                width="100%"
                height="100%"
              />
              <span v-else class="po-card__goods-placeholder">
                {{ prescriptionTypeMeta(row)?.label?.slice(0, 2) || '商品' }}
              </span>
            </div>
            <div class="min-w-0 flex-1">
              <div class="po-card__goods-name">
                {{
                  firstItem(row)
                    ? firstItem(row).display_drug_name || firstItem(row).drug_name
                    : '无商品明细'
                }}
              </div>
              <div v-if="firstItem(row)" class="po-card__goods-count">
                {{ row.product_order_items.length }} 种 · 共 {{ totalPieces(row) }} 件
                <span class="po-card__goods-toggle">
                  {{ expandedIds.has(Number(row.id)) ? '收起' : '展开' }}
                  <i :class="expandedIds.has(Number(row.id)) ? 'up' : ''">›</i>
                </span>
              </div>
            </div>
            <div class="po-card__amount" @click.stop>
              <span
                v-if="props.canPercentAdjust?.(row)"
                class="po-card__amount-value po-card__amount-value--link"
                role="button"
                @click="emit('percentAdjust', row)"
              >
                <i>¥</i>{{ row.total_pay_price ?? '0.00' }}
              </span>
              <span v-else class="po-card__amount-value">
                <i>¥</i>{{ row.total_pay_price ?? '0.00' }}
              </span>
            </div>
          </div>
          <!-- 展开后的全部商品 chips -->
          <div
            v-if="expandedIds.has(Number(row.id)) && Array.isArray(row.product_order_items) && row.product_order_items.length"
            class="po-card__chips"
          >
            <span
              v-for="(item, idx) in row.product_order_items"
              :key="idx"
              class="po-card__drug-chip"
            >
              {{ item.display_drug_name || item.drug_name }}
              ×{{
                Number(row.prescription_type) === 1
                  ? item.number * (item.dosage > 0 ? item.dosage : 1)
                  : item.number
              }}
            </span>
          </div>
          <!-- 行4 人员内联行：用户/医生/就诊人/代付（与列表 OrderUserInfoCell 同口径、可点） -->
          <div class="po-card__people">
            <span class="po-kv">
              <i>用户</i>
              <button
                v-if="resolveUserId(row)"
                type="button"
                class="po-link"
                @click="onUserClick(row)"
              >
                {{ row.user?.nickname || '—' }}
              </button>
              <em v-else>{{ row.user?.nickname || '—' }}</em>
            </span>
            <span class="po-kv">
              <i>医生</i>
              <button
                v-if="row.doctor?.name"
                type="button"
                class="po-link"
                @click="emit('openDoctor', row)"
              >
                {{ row.doctor.name }}
              </button>
              <em v-else>—</em>
            </span>
            <span class="po-kv">
              <i>就诊人</i>
              <button
                v-if="resolveUpId(row)"
                type="button"
                class="po-link"
                @click="onPatientClick(row)"
              >
                {{ patientNameOf(row) }}
              </button>
              <em v-else>{{ patientNameOf(row) }}</em>
            </span>
            <span v-if="hasPayUser(row)" class="po-kv">
              <i>代付</i>
              <em>{{ payUserText(row) }}</em>
            </span>
          </div>
          <!-- 行5 收货内联行：收件人 + 电话 + 地址一行截断 -->
          <div class="po-card__express">
            <i>收货</i>
            <span class="truncate">
              {{ row.address?.name || row.express_name || row.patient || '—' }}
              <SensitiveText
                :record="row.address"
                field="mobile"
                :fallback="{ record: row, field: 'patient_mobile' }"
              />
              · {{ expressAddress(row) }}
            </span>
          </div>
          <!-- 行6 推广员内联行（有则显示） -->
          <div v-if="row.salesperson?.id" class="po-card__express po-card__salesperson">
            <i>推广</i>
            <Image
              :src="row.salesperson.avatar || '/img/user-default-avatar.png'"
              :width="16"
              :height="16"
              :preview="false"
              class="shrink-0 rounded-full object-cover"
            />
            <span class="truncate">{{ row.salesperson.nick_name || '—' }}</span>
            <span class="po-card__salesperson-status">
              {{ row.salesperson.commission_status_text || '—' }}
            </span>
            <span class="shrink-0 font-medium text-orange-500">
              ¥{{ row.salesperson.commission_amount || '0.00' }}
            </span>
          </div>
          <!-- 弹性占位：高度富余时把 footer 推到底（同行等高卡对齐），紧凑时保底 8px 间距 -->
          <div class="po-card__spacer"></div>
          <!-- 行7 footer：左分项金额/包邮开关，右操作按钮 -->
          <div class="po-card__footer">
            <div class="po-card__amount-parts">
              <span>
                药品
                <Button
                  v-if="props.canPercentAdjust?.(row)"
                  class="!h-auto !px-0 !py-0 !text-xs"
                  type="link"
                  @click="emit('percentAdjust', row)"
                >
                  ¥{{ row.items_price ?? '0.00' }}
                </Button>
                <template v-else>¥{{ row.items_price ?? '0.00' }}</template>
              </span>
              <span>
                挂号
                <Button
                  v-if="row.register_order_no"
                  class="!h-auto !px-0 !py-0 !text-xs"
                  type="link"
                  @click="emit('goRegister', row)"
                >
                  {{ registerAmount(row) }}
                </Button>
                <template v-else>{{ registerAmount(row) }}</template>
              </span>
              <Switch
                :checked="row.is_free_shipping === 1"
                checked-children="包邮"
                un-checked-children="不包邮"
                size="small"
                @change="(checked: any) => emit('toggleFreeShipping', row, Boolean(checked))"
              />
            </div>
            <!-- 卡片交互与列表解耦：只露出「详情」主操作，其余收进「···」菜单，避免按钮堆叠 -->
            <CardActions
              :actions="props.buildRowActions(row).actions"
              :drop-down-actions="props.buildRowActions(row).dropDownActions"
            />
          </div>
        </div>
      </div>
      <Empty v-else-if="!loading" description="暂无订单" />
    </Spin>
    <div ref="sentinelEl" class="h-8"></div>
    <div v-if="loadingMore" class="py-3 text-center text-xs text-[hsl(var(--muted-foreground))]">
      加载中…
    </div>
    <div
      v-else-if="items.length && !hasMore"
      class="py-3 text-center text-xs text-[hsl(var(--muted-foreground))]"
    >
      没有更多了
    </div>
  </div>
</template>

<style scoped>
.po-card-scroll {
  height: 100%;
  /* 左右留 6px：卡片 hover 阴影不被容器裁出切边 */
  padding: 4px 6px 20px;
  overflow: auto;
}

/* 多列自适应网格：单卡最窄 400px，宽屏自动 2-3 列（C 端紧凑卡片密度）；
   min(400px, 100%) 防止窄容器（分屏）时轨道小于容器导致横向滚动 */
.po-card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(400px, 100%), 1fr));
  gap: 10px;
}

/* 玻璃质感紧凑卡片（与提现管理统计岛同款）：主色渐变玻璃底 + 12px 圆角 + 1px 边框 */
.po-card {
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: linear-gradient(
    135deg,
    hsl(var(--primary) / 4%),
    hsl(var(--card, var(--background)))
  );
  backdrop-filter: blur(8px);
  border: 1px solid hsl(var(--border));
  border-radius: 12px;
  transition:
    transform 0.2s ease,
    box-shadow 0.2s ease,
    border-color 0.2s ease;
}

.po-card:hover {
  border-color: hsl(var(--primary) / 40%);
  box-shadow:
    0 8px 20px hsl(var(--primary) / 14%),
    0 2px 6px rgb(0 0 0 / 6%);
  transform: translateY(-3px);
}

/* 角落径向荧光：右上角淡主色光斑，hover 增强 */
.po-card__glow {
  position: absolute;
  top: -40px;
  right: -40px;
  width: 110px;
  height: 110px;
  pointer-events: none;
  background: radial-gradient(circle, hsl(var(--primary) / 18%) 0%, transparent 70%);
  opacity: 0.4;
  transition: opacity 0.2s ease;
}

.po-card:hover .po-card__glow {
  opacity: 1;
}

/* 行1 头部：店铺 + 状态彩点 */
.po-card__head {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 10px 12px 0;
}

.po-card__store {
  display: inline-flex;
  min-width: 0;
  align-items: center;
  gap: 2px;
  padding: 0;
  cursor: pointer;
  background: none;
  border: none;
}

.po-card__store-name {
  overflow: hidden;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: -0.2px;
  color: hsl(var(--foreground));
  text-overflow: ellipsis;
  white-space: nowrap;
}

.po-card__store:hover .po-card__store-name {
  color: hsl(var(--primary));
}

.po-card__store-arrow {
  flex-shrink: 0;
  font-size: 14px;
  color: hsl(var(--muted-foreground));
}

.po-card__status {
  display: inline-flex;
  flex-shrink: 0;
  gap: 4px;
  align-items: center;
  margin-left: auto;
  font-size: 12px;
  font-weight: 600;
}

.po-card__status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

/* 行2 单号/时间小灰字 */
.po-card__meta {
  display: flex;
  gap: 4px;
  align-items: center;
  padding: 1px 12px 0;
  font-size: 11px;
  color: hsl(var(--muted-foreground));
}

.po-card__dot {
  flex-shrink: 0;
}

/* tinted 胶囊行（紧凑小号） */
.po-card__pills {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 6px 12px 0;
}

.po-pill {
  display: inline-flex;
  align-items: center;
  padding: 1px 7px;
  font-size: 10px;
  font-weight: 500;
  line-height: 16px;
  border: none;
  border-radius: 999px;
}

.po-pill--action {
  cursor: pointer;
  transition: filter 0.15s ease;
}

.po-pill--action:hover {
  filter: brightness(1.08) saturate(1.2);
}

/* 行3 商品行：左图文右合计（C 端订单卡惯例） */
.po-card__goods {
  display: flex;
  gap: 10px;
  align-items: center;
  padding: 7px 10px;
  margin: 8px 12px 0;
  cursor: pointer;
  background: hsl(var(--muted) / 30%);
  border-radius: 10px;
  transition: background-color 0.2s ease;
}

.po-card__goods:hover {
  background: hsl(var(--muted) / 45%);
}

.po-card__goods-thumb {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  overflow: hidden;
  background: hsl(var(--card, var(--background)));
  border-radius: 8px;
  box-shadow: 0 1px 2px rgb(0 0 0 / 6%);
}

.po-card__goods-thumb :deep(img) {
  object-fit: cover;
}

.po-card__goods-placeholder {
  font-size: 11px;
  font-weight: 600;
  color: hsl(var(--muted-foreground));
}

.po-card__goods-name {
  overflow: hidden;
  font-size: 13px;
  font-weight: 500;
  color: hsl(var(--foreground));
  text-overflow: ellipsis;
  white-space: nowrap;
}

.po-card__goods-count {
  display: flex;
  gap: 6px;
  align-items: center;
  margin-top: 1px;
  font-size: 11px;
  color: hsl(var(--muted-foreground));
}

.po-card__goods-toggle {
  display: inline-flex;
  flex-shrink: 0;
  gap: 1px;
  align-items: center;
  font-size: 11px;
  color: hsl(var(--primary));
}

.po-card__goods-toggle i {
  font-style: normal;
  transform: rotate(90deg);
  transition: transform 0.2s ease;
}

.po-card__goods-toggle i.up {
  transform: rotate(-90deg);
}

/* 合计金额（商品行右侧） */
.po-card__amount {
  flex-shrink: 0;
  margin-left: auto;
}

.po-card__amount-value {
  /* DIN 等宽数字：与提现管理统计岛金额同款字体质感 */
  font-family: 'DIN Alternate', ui-monospace, SFMono-Regular, Menlo, monospace;
  font-size: 16px;
  font-weight: 700;
  letter-spacing: -0.3px;
  color: hsl(var(--foreground));
}

.po-card__amount-value i {
  margin-right: 1px;
  font-size: 11px;
  font-style: normal;
  font-weight: 600;
}

.po-card__amount-value--link {
  color: hsl(var(--primary));
  cursor: pointer;
}

.po-card__chips {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  padding: 6px 12px 0;
}

.po-card__drug-chip {
  padding: 1px 8px;
  font-size: 11px;
  color: hsl(var(--muted-foreground));
  background: hsl(var(--muted) / 35%);
  border-radius: 999px;
}

/* 行4 人员内联行：label 小灰字 + 可点链接，一行自动换行 */
.po-card__people {
  display: flex;
  flex-wrap: wrap;
  gap: 2px 14px;
  padding: 7px 12px 0;
  font-size: 12px;
  line-height: 1.6;
}

.po-kv {
  display: inline-flex;
  gap: 4px;
  align-items: baseline;
  min-width: 0;
}

.po-kv > i {
  flex-shrink: 0;
  font-size: 11px;
  font-style: normal;
  color: hsl(var(--muted-foreground) / 75%);
}

.po-kv > em {
  overflow: hidden;
  font-style: normal;
  color: hsl(var(--foreground));
  text-overflow: ellipsis;
  white-space: nowrap;
}

.po-link {
  max-width: 140px;
  padding: 0;
  overflow: hidden;
  font-size: 12px;
  color: hsl(var(--primary));
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
  background: none;
  border: none;
}

.po-link:hover {
  text-decoration: underline;
}

/* 行5/6 收货、推广员内联行：label + 单行截断 */
.po-card__express {
  display: flex;
  gap: 6px;
  align-items: center;
  min-width: 0;
  padding: 4px 12px 0;
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}

.po-card__express > i {
  flex-shrink: 0;
  font-size: 11px;
  font-style: normal;
  color: hsl(var(--muted-foreground) / 75%);
}

.po-card__salesperson-status {
  flex-shrink: 0;
  padding: 0 7px;
  font-size: 10px;
  line-height: 16px;
  color: hsl(var(--muted-foreground));
  background: hsl(var(--muted) / 40%);
  border-radius: 999px;
}

/* 弹性占位：吃掉剩余高度让 footer 吸底 */
.po-card__spacer {
  flex: 1 1 auto;
  min-height: 8px;
}

/* 行7 footer：左分项/包邮，右操作按钮；hairline 分隔 */
.po-card__footer {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 10px;
  align-items: center;
  justify-content: space-between;
  padding: 4px 6px 4px 12px;
  border-top: 1px solid hsl(var(--border) / 50%);
}

.po-card__amount-parts {
  display: flex;
  gap: 10px;
  align-items: center;
  font-size: 11px;
  color: hsl(var(--muted-foreground));
}
</style>
