<template>
  <!-- 订单详情页面 -->
  <view class="content">
    <!-- 菜品清单 -->
    <view class="card">
      <!-- 店铺信息 -->
      <view class="store-info">
        <view class="store-info-title">{{ orderDetail.storeName || '店铺名称' }}</view>
        <view class="store-info-address">{{ orderDetail.storeAddress || '—' }}</view>
      </view>
      <view class="card-header">
        <view class="card-header-title">菜品详情</view>
      </view>
      <view class="card-content">
        <view class="info-food">
          <view v-for="(item, index) in displayFoodList" :key="item.id || index" class="food-item">
            <image :src="getItemImage(item)" mode="aspectFill" class="food-item__image"></image>

            <!-- 菜品信息 -->
            <view class="food-item__info">
              <view class="food-item__name">{{ item.name }}</view>
              <view class="food-item__desc" v-if="item.tags && item.tags.length > 0">
                <text v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="food-item__tag"
                  :class="tag.type">{{ tag.text }}<text v-if="tagIndex < item.tags.length - 1">,</text>
                </text>
              </view>
            </view>

            <!-- 价格和数量 -->
            <view class="food-item__right">
              <view class="food-item__price">
                <text class="price-main">¥{{ formatPrice(item.price) }}</text>
              </view>
              <view class="food-item__quantity">{{ item.quantity || 1 }}份</view>
            </view>
          </view>
        </view>
      </view>

      <view class="card-header">
        <view class="card-header-title">价格明细</view>
      </view>
      <view class="card-content">
        <view class="info-item">
          <view class="info-item-label">菜品总价</view>
          <view class="info-item-value">¥{{ priceDetail.dishTotal }}</view>
        </view>
        <!-- 本版本不参与服务费
        <view class="info-item">
          <view class="info-item-label">服务费</view>
          <view class="info-item-value">¥{{ priceDetail.serviceFee }}</view>
        </view>
        -->
        <view v-if="showDiscountLine" class="info-item">
          <view class="info-item-label">优惠金额</view>
          <view class="info-item-value">
            <text class="discount-amount-num">{{ discountAmountDisplayText }}</text>
          </view>
        </view>
        <view class="price-line">
          <view class="price-line-label">合计</view>
          <view class="price-line-value">¥{{ formatPrice(displayPayInPriceSection) }}</view>
        </view>
       
      </view>
    </view>
    <!-- 已支付 / 已完成：支付信息（支付方式、支付时间） -->
    <view v-if="showPaidOrderPaymentCard" class="card">
      <view class="card-header">
        <view class="card-header-title">支付信息</view>
      </view>
      <view class="card-content">
        <view class="info-item">
          <view class="info-item-label">支付方式</view>
          <view class="info-item-value">微信支付</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">支付时间</view>
          <view class="info-item-value">{{ payTimeDisplay }}</view>
        </view>
      </view>
    </view>

    <!-- 订单卡片 -->
    <view class="card">
      <view class="card-header">
        <view class="card-header-title">订单信息</view>
      </view>
      <view class="card-content">
        <view class="info-item">
          <view class="info-item-label">订单编号</view>
          <view class="info-item-value">{{ orderDetail.orderNo || '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">就餐桌号</view>
          <view class="info-item-value">{{ orderDetail.tableNo || '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">用餐人数</view>
          <view class="info-item-value">{{ orderDetail.dinerCount != null && orderDetail.dinerCount !== '' ? orderDetail.dinerCount + '人' : '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">下单时间</view>
          <view class="info-item-value">{{ orderDetail.createTime || '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">联系电话</view>
          <view class="info-item-value">{{ orderDetail.contactPhone || '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">备注信息</view>
          <view class="info-item-value">{{ (orderDetail.remark || '').trim() || '无' }}</view>
        </view>
      </view>
    </view>

    <!-- 底部按钮：已完成(3)不显示（与 isOrderCompleted 一致用数值比较，避免字符串 "3" 仍显示按钮） -->
    <view v-if="Number(orderDetail.orderStatus) !== 3" class="bottom-button">
      <view class="bottom-button-text1 " hover-class="hover-active" @click="handleAddFood">去加餐</view>
      <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmPay">去结算</view>
    </view>

  </view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import { getFileUrl } from "@/utils/file.js";
import { navigateToAddFood } from "@/utils/orderAddFoodNavigate.js";
import { GetOrderInfo } from "@/api/dining.js";

const payType = ref('confirmOrder'); // confirmOrder 确认下单 confirmPay 确认支付
/** 当前订单ID，用于「去结算」传参 */
const detailOrderId = ref('');

// 订单详情（店铺、订单信息）
// orderStatus：0 待支付，1 已支付，2 已取消，3 已完成
const orderDetail = ref({
  storeName: '',
  storeAddress: '',
  storeId: '',
  orderNo: '',
  tableId: '', // 桌台主键，加餐/购物车用
  storeTableId: '',
  diningTableId: '',
  tableNo: '', // 桌号展示（tableNumber）
  dinerCount: '',
  createTime: '',
  contactPhone: '',
  remark: '',
  orderStatus: null,
  payType: '', // 支付方式编码，如 wechatPayMininProgram
  /** 支付完成时间 */
  payTime: ''
});

// 价格明细（两位小数）
const priceDetail = ref({
  dishTotal: '0.00',
  serviceFee: '0.00',
  serviceFeeAmount: 0,
  couponDiscount: '0.00',
  discountAmount: 0,
  couponName: '',
  couponType: null,
  nominalValue: null,
  discountRate: null,
  total: '0.00',
  /** 接口实付（元）；已完成订单详情「合计」直接绑定此字段 */
  payAmount: 0
});

/** 订单详情接口已写入价格区（避免首屏初始 0 误展示优惠行） */
const orderPriceSectionReady = ref(false);

// 菜品列表（接口订单明细）
const foodList = ref([]);

// 菜品详情展示（排除特殊占位 id=-1）
const displayFoodList = computed(() =>
  (foodList.value ?? []).filter((it) => Number(it?.id ?? it?.cuisineId) !== -1)
);

// 未支付订单：按明细行累计菜品总价（与 checkout 行小计口径一致）
const calculatedDishTotalFromItems = computed(() => {
  const list = displayFoodList.value;
  let sum = 0;
  for (const it of list) {
    const ls = Number(it?.lineSubtotal);
    // 行小计为 0 时仍可能单价×数量>0（接口占位 0），不要用 0 覆盖真实金额
    if (Number.isFinite(ls) && ls > 0) {
      sum += ls;
      continue;
    }
    const q = Number(it?.quantity) || 1;
    const u = Number(it?.price) || 0;
    sum += u * q;
  }
  return Math.max(0, Math.round(sum * 100) / 100);
});

// 合计/优惠计算用菜品基数：有明细则按行累计，并与接口菜品总价取较大值（避免行数据为 0 时把优惠上限压成 0 导致不展示）
const dishTotalBaseForOrder = computed(() => {
  const fromApi = Number(String(priceDetail.value?.dishTotal ?? '').replace(/,/g, ''));
  const apiNum = Number.isFinite(fromApi) && fromApi > 0 ? fromApi : 0;
  if (displayFoodList.value.length > 0) {
    const fromItems = calculatedDishTotalFromItems.value;
    return Math.max(fromItems, apiNum);
  }
  return apiNum;
});

/** 接口返回后且优惠大于 0 时才展示优惠行（为 0 不展示） */
const showDiscountLine = computed(() => {
  if (!orderPriceSectionReady.value) return false;
  const n = Number(priceDetail.value?.discountAmount);
  return Number.isFinite(n) && n > 0;
});

/** 价格明细「合计」：优先接口 payAmount，缺失时再走计算值 */
const displayPayInPriceSection = computed(() => {
  const p = priceDetail.value?.payAmount;
  if (p != null && p !== '' && Number.isFinite(Number(p)) && Number(p) >= 0) {
    return Math.round(Number(p) * 100) / 100;
  }
  return actualPayAmount.value;
});

/** 优惠金额文案（仅 showDiscountLine 为 true 时使用，即 n > 0） */
const discountAmountDisplayText = computed(() => {
  const n = Number(priceDetail.value?.discountAmount);
  if (!Number.isFinite(n) || n <= 0) return '-¥0.00';
  return `-¥${formatPrice(n)}`;
});

/** 接口 discountAmount（数值化；0 也保留，供展示与推导） */
const rawDiscountFromApi = computed(() => {
  const n = Number(priceDetail.value?.discountAmount);
  if (!Number.isFinite(n) || n < 0) return 0;
  return Math.round(n * 100) / 100;
});

/** 已支付：orderStatus 1 已支付、3 已完成 */
function isPaidOrderStatus(status) {
  const s = Number(status);
  return s === 1 || s === 3;
}

/** 订单已完成 orderStatus === 3 */
const isOrderCompleted = computed(() => Number(orderDetail.value?.orderStatus) === 3);

/** 已取消等不参与「待付场景」优惠推导 */
const isCancelledOrder = computed(() => Number(orderDetail.value?.orderStatus) === 2);

/** 非已完成、非取消：需要展示/推导优惠（含 orderStatus 为字符串或缺失导致 Number 为 NaN 的情况） */
const isOpenOrderForDiscount = computed(
  () => !isOrderCompleted.value && !isCancelledOrder.value
);

/** 接口未回 discountAmount 时，用「菜品基数 + 服务费 − 应付」反推优惠（与合计 payAmount 一致） */
const impliedDiscountFromPay = computed(() => {
  if (!isOpenOrderForDiscount.value) return 0;
  const base = dishTotalBaseForOrder.value;
  const fee = Number(priceDetail.value?.serviceFeeAmount) || 0;
  const pay = Number(priceDetail.value?.payAmount);
  if (!Number.isFinite(pay) || pay < 0 || base <= 0) return 0;
  const diff = base + fee - pay;
  if (diff <= 0.0001) return 0;
  return Math.min(Math.max(0, Math.round(diff * 100) / 100), Math.max(0, base));
});

// 待支付 / 已支付等与已支付一致：优先接口 discountAmount，否则按「菜品基数 + 服务费 − 应付」反推，再按菜品基数上限裁剪
const orderDiscountDisplay = computed(() => {
  if (!isOpenOrderForDiscount.value) return 0;
  const dishBase = dishTotalBaseForOrder.value;
  const explicit = rawDiscountFromApi.value;
  const fromImplied = explicit > 0 ? 0 : impliedDiscountFromPay.value;
  const d = Math.max(explicit, fromImplied);
  const capped = Math.min(Math.max(0, d), Math.max(0, dishBase));
  return Math.max(0, Math.round(capped * 100) / 100);
});

// 合计：已完成用接口 payAmount/total；待支付/已支付等非完成态与已支付一致：优先 payAmount，否则「菜品基数 − 优惠」
const actualPayAmount = computed(() => {
  if (isOrderCompleted.value) {
    const pa = Number(priceDetail.value?.payAmount);
    if (Number.isFinite(pa) && pa >= 0) return Math.round(pa * 100) / 100;
    const t = Number(priceDetail.value?.total);
    return Number.isFinite(t) ? Math.max(0, Math.round(t * 100) / 100) : 0;
  }
  const pa = Number(priceDetail.value?.payAmount);
  if (Number.isFinite(pa) && pa >= 0) return Math.round(pa * 100) / 100;
  const base = dishTotalBaseForOrder.value;
  const d = orderDiscountDisplay.value;
  return Math.max(0, Math.round((base - d) * 100) / 100);
});

// 已支付(1) / 已完成(3) 展示支付信息卡片
const showPaidOrderPaymentCard = computed(() => {
  const s = Number(orderDetail.value?.orderStatus);
  return s === 1 || s === 3;
});

// 支付时间
const payTimeDisplay = computed(() => {
  const t = orderDetail.value?.payTime;
  if (t != null && String(t).trim() !== '') return String(t).trim();
  return '—';
});

// 取第一张图：逗号分隔取首段，数组取首项，对象取 url/path/src（与 orderInfo/index、FoodCard 一致）
function firstImage(val) {
  if (val == null || val === '') return '';
  if (Array.isArray(val)) {
    const first = val[0];
    if (first != null && first !== '') {
      if (typeof first === 'object' && first !== null) return first.url ?? first.path ?? first.src ?? first.link ?? '';
      return String(first).split(/[,，]/)[0].trim();
    }
    return '';
  }
  if (typeof val === 'object') return val.url ?? val.path ?? val.src ?? val.link ?? '';
  const str = String(val).trim();
  return str ? str.split(/[,，]/)[0].trim() : '';
}

function getItemImage(item) {
  const raw = item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? item?.pic ?? item?.cover ?? item?.images ?? '';
  const url = firstImage(raw) || (typeof raw === 'string' ? raw.split(/[,，]/)[0]?.trim() : '');
  if (url && typeof url === 'string' && (url.startsWith('http') || url.startsWith('//'))) return url;
  return getFileUrl(url || 'img/icon/shop.png');
}

// 金额保留两位小数
const formatPrice = (price) => {
  if (price === '' || price === null || price === undefined) return '0.00';
  const num = Number(price);
  return Number.isNaN(num) ? '0.00' : num.toFixed(2);
};

// 将 tags 统一为 [{ text, type }] 格式
function normalizeTags(raw) {
  if (raw == null) return [];
  let arr = [];
  if (Array.isArray(raw)) arr = raw;
  else if (typeof raw === 'string') {
    const t = raw.trim();
    if (t.startsWith('[')) { try { arr = JSON.parse(t); if (!Array.isArray(arr)) arr = []; } catch { arr = t ? [t] : []; } }
    else arr = t ? t.split(/[,，、\s]+/).map(s => s.trim()).filter(Boolean) : [];
  } else if (raw && typeof raw === 'object') arr = Array.isArray(raw.list) ? raw.list : Array.isArray(raw.items) ? raw.items : [];
  return arr.map((it) => {
    if (it == null) return { text: '', type: '' };
    if (typeof it === 'string') return { text: it, type: '' };
    if (typeof it === 'number') return { text: String(it), type: '' };
    return { text: it.text ?? it.tagName ?? it.name ?? it.label ?? it.title ?? '', type: it.type ?? it.tagType ?? '' };
  }).filter((t) => t.text !== '' && t.text != null);
}

// 将接口订单项转为列表项（图片取首张；行小计与 checkout 一致，便于未支付订单合计按明细计算）
function normalizeOrderItem(item) {
  const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
  const rawImg = item?.images ?? item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? item?.pic ?? item?.cover ?? '';
  const imageUrl = firstImage(rawImg) || (typeof rawImg === 'string' ? rawImg.split(/[,，]/)[0]?.trim() : '') || 'img/icon/shop.png';
  const qty = Number(item?.quantity ?? 1) || 1;
  let lineSubtotal = 0;
  if (item?.subtotalAmount != null && item.subtotalAmount !== '') {
    lineSubtotal = Number(item.subtotalAmount) || 0;
  } else if (item?.totalPrice != null && item.totalPrice !== '') {
    lineSubtotal = Number(item.totalPrice) || 0;
  } else {
    const unit = Number(item?.unitPrice ?? item?.price ?? item?.salePrice ?? 0) || 0;
    lineSubtotal = unit * qty;
  }
  // 接口可能把小计写成 0，但单价/数量有效，回退为单价×数量，与列表展示一致
  if (lineSubtotal <= 0) {
    const unit = Number(item?.unitPrice ?? item?.price ?? item?.salePrice ?? 0) || 0;
    const fallback = unit * qty;
    if (fallback > 0) lineSubtotal = fallback;
  }
  const unitForDisplay =
    Number(item?.unitPrice ?? item?.price ?? 0) ||
    (qty > 0 ? lineSubtotal / qty : 0);
  return {
    id: item?.id ?? item?.cuisineId ?? item?.orderItemId ?? item?.skuId,
    name:
      item?.cuisineName ??
      item?.name ??
      item?.goodsName ??
      item?.skuName ??
      item?.productName ??
      '',
    price: unitForDisplay,
    lineSubtotal,
    image: imageUrl,
    quantity: qty,
    tags: normalizeTags(rawTags)
  };
}

// 从接口数据填充 orderDetail、priceDetail、foodList
function pickFirstDefined(...vals) {
  for (const v of vals) {
    if (v != null && v !== '') return v;
  }
  return undefined;
}

function applyOrderData(data) {
  orderPriceSectionReady.value = false;
  const root = data?.data ?? data ?? {};
  const nested = root?.order && typeof root.order === 'object' ? root.order : {};
  const deepData =
    root?.data && typeof root.data === 'object' && !Array.isArray(root.data) ? root.data : {};
  const raw = root;
  const store = raw?.storeInfo ?? raw?.store ?? {};
  const tableInfo = raw?.tableInfo ?? nested?.tableInfo ?? deepData?.tableInfo ?? {};
  const storeTableIdVal =
    raw?.storeTableId ??
    nested?.storeTableId ??
    deepData?.storeTableId ??
    raw?.store_table_id ??
    nested?.store_table_id ??
    tableInfo?.storeTableId ??
    '';
  const diningTableIdVal =
    raw?.diningTableId ??
    nested?.diningTableId ??
    deepData?.diningTableId ??
    tableInfo?.diningTableId ??
    '';
  const tableIdVal =
    pickFirstDefined(
      raw?.tableId,
      nested?.tableId,
      deepData?.tableId,
      storeTableIdVal,
      diningTableIdVal,
      tableInfo?.tableId,
      tableInfo?.id,
      raw?.table?.id,
      nested?.table?.id
    ) ?? '';
  orderDetail.value = {
    storeName: store?.storeName ?? raw?.storeName ?? '',
    storeAddress: store?.storeAddress ?? store?.address ?? raw?.storeAddress ?? raw?.address ?? '',
    storeId: store?.storeId ?? store?.id ?? raw?.storeId ?? raw?.store_id ?? nested?.storeId ?? deepData?.storeId ?? '',
    orderNo: raw?.orderNo ?? raw?.orderId ?? nested?.orderNo ?? '',
    tableId: tableIdVal,
    storeTableId: storeTableIdVal,
    diningTableId: diningTableIdVal,
    tableNo:
      raw?.tableNumber ??
      raw?.tableNo ??
      nested?.tableNumber ??
      nested?.tableNo ??
      deepData?.tableNumber ??
      tableInfo?.tableNumber ??
      tableInfo?.tableNo ??
      raw?.tableName ??
      '',
    dinerCount: raw?.dinerCount ?? nested?.dinerCount ?? deepData?.dinerCount ?? '',
    createTime: raw?.createdTime ?? raw?.createTime ?? raw?.orderTime ?? '',
    contactPhone: raw?.contactPhone ?? raw?.phone ?? '',
    remark: raw?.remark ?? '',
    orderStatus: raw?.orderStatus ?? nested?.orderStatus ?? raw?.status ?? nested?.status ?? null,
    payType: raw?.payType ?? raw?.payMethod ?? '',
    payTime:
      raw?.payTime ??
      raw?.paymentTime ??
      raw?.paidTime ??
      raw?.payFinishTime ??
      raw?.paySuccessTime ??
      ''
  };
  const couponInfo = raw?.couponInfo ?? raw?.coupon ?? nested?.couponInfo ?? nested?.coupon ?? {};
  const dishTotal =
    raw?.totalAmount ??
    nested?.totalAmount ??
    deepData?.totalAmount ??
    raw?.dishTotal ??
    nested?.dishTotal ??
    deepData?.dishTotal ??
    raw?.orderAmount ??
    nested?.orderAmount ??
    raw?.foodAmount ??
    nested?.foodAmount ??
    0;
  const couponDiscount =
    raw?.couponAmount ??
    nested?.couponAmount ??
    deepData?.couponAmount ??
    raw?.couponDiscount ??
    nested?.couponDiscount ??
    0;
  /** 优惠金额：不能用「首个有限数字」合并 couponAmount，否则接口 couponAmount=0 会截断后面的 discountAmount（待支付常见） */
  const discountPrimaryPick = pickFirstDefined(
    raw.discountAmount,
    nested.discountAmount,
    deepData.discountAmount,
    raw.discount_amount,
    nested.discount_amount,
    deepData.discount_amount,
    raw.data?.discountAmount,
    nested.data?.discountAmount,
    raw.priceDetail?.discountAmount,
    nested.priceDetail?.discountAmount,
    deepData.priceDetail?.discountAmount,
    raw.totalDiscountAmount,
    nested.totalDiscountAmount,
    deepData.totalDiscountAmount,
    raw.totalDiscount,
    nested.totalDiscount,
    raw.couponDiscountAmount,
    nested.couponDiscountAmount,
    raw.couponDiscount,
    nested.couponDiscount
  );
  const discountSecondaryPick = pickFirstDefined(
    couponInfo.discountAmount,
    couponInfo.amount,
    couponInfo.nominalValue,
    raw.couponAmount,
    nested.couponAmount,
    deepData.couponAmount
  );
  const discountPick = discountPrimaryPick ?? discountSecondaryPick;
  const discountAmountVal =
    discountPick != null && discountPick !== '' ? Number(discountPick) || 0 : 0;
  const totalFallback =
    Number(
      raw?.totalAmount ??
        nested?.totalAmount ??
        deepData?.totalAmount ??
        raw?.totalPrice ??
        nested?.totalPrice ??
        raw?.orderAmount ??
        nested?.orderAmount ??
        raw?.foodAmount ??
        nested?.foodAmount ??
        0
    ) || 0;
  const payPick = pickFirstDefined(
    raw.payAmount,
    nested.payAmount,
    deepData.payAmount,
    raw.waitPayAmount,
    nested.waitPayAmount,
    deepData.waitPayAmount,
    raw.needPayAmount,
    nested.needPayAmount,
    deepData.needPayAmount,
    raw.unpaidAmount,
    nested.unpaidAmount,
    raw.pay_amount,
    nested.pay_amount,
    deepData.pay_amount,
    raw.realPayAmount,
    nested.realPayAmount,
    deepData.realPayAmount,
    raw.real_pay_amount,
    nested.real_pay_amount,
    raw.paidAmount,
    nested.paidAmount,
    deepData.paidAmount
  );
  const payAmountNum =
    payPick != null && payPick !== '' ? Number(payPick) || 0 : totalFallback;
  const serviceFeeRaw =
    Number(raw?.serviceFee ?? raw?.serviceCharge ?? raw?.tablewareFee ?? 0) || 0;
  const rawDiscountRate =
    raw?.discountRate ??
    nested?.discountRate ??
    couponInfo?.discountRate ??
    raw?.coupon?.discountRate ??
    nested?.coupon?.discountRate;
  const discountRateVal = rawDiscountRate != null && rawDiscountRate !== '' ? (Number(rawDiscountRate) || 0) / 10 : null;
  priceDetail.value = {
    dishTotal: formatPrice(dishTotal),
    serviceFee: formatPrice(serviceFeeRaw),
    serviceFeeAmount: serviceFeeRaw,
    couponDiscount: formatPrice(couponDiscount),
    discountAmount: discountAmountVal,
    couponName:
      raw?.couponName ?? nested?.couponName ?? couponInfo?.couponName ?? couponInfo?.name ?? '',
    couponType: raw?.couponType ?? nested?.couponType ?? couponInfo?.couponType ?? null,
    nominalValue:
      raw?.nominalValue ?? nested?.nominalValue ?? couponInfo?.nominalValue ?? couponInfo?.amount ?? null,
    discountRate: discountRateVal,
    total: formatPrice(payAmountNum),
    payAmount: payAmountNum
  };
  const list =
    raw?.orderItemList ??
    nested?.orderItemList ??
    raw?.orderItems ??
    nested?.orderItems ??
    raw?.orderLines ??
    nested?.orderLines ??
    raw?.orderLineList ??
    nested?.orderLineList ??
    raw?.detailList ??
    nested?.detailList ??
    raw?.order?.orderItemList ??
    raw?.order?.orderItems ??
    (Array.isArray(raw?.items) ? raw.items : []);
  foodList.value = (Array.isArray(list) ? list : []).map(normalizeOrderItem);
  orderPriceSectionReady.value = true;
}

// 去加餐（与订单列表页同一套逻辑，见 utils/orderAddFoodNavigate.js）
const handleAddFood = () => navigateToAddFood(orderDetail.value);

// 去结算：跳转确认订单页，携带订单ID、订单号、桌号、就餐人数、订单金额（用于调起支付）
const handleConfirmPay = () => {
  const orderId = detailOrderId.value || '';
  const orderNo = orderDetail.value?.orderNo ?? '';
  const tableId = orderDetail.value?.tableId || orderDetail.value?.tableNo || '';
  const tableNumber = orderDetail.value?.tableNo ?? orderDetail.value?.tableNumber ?? '';
  const diners = orderDetail.value?.dinerCount ?? '';
  const totalAmount = formatPrice(displayPayInPriceSection.value);
  const remark = (orderDetail.value?.remark ?? '').trim().slice(0, 30);
  const q = [];
  if (orderId !== '') q.push(`orderId=${encodeURIComponent(String(orderId))}`);
  if (orderNo !== '') q.push(`orderNo=${encodeURIComponent(String(orderNo))}`);
  if (tableId !== '') q.push(`tableId=${encodeURIComponent(String(tableId))}`);
  if (tableNumber !== '') q.push(`tableNumber=${encodeURIComponent(String(tableNumber))}`);
  if (diners !== '') q.push(`diners=${encodeURIComponent(String(diners))}`);
  if (totalAmount !== '' && totalAmount != null) q.push(`totalAmount=${encodeURIComponent(String(totalAmount))}`);
  if (remark !== '') q.push(`remark=${encodeURIComponent(remark)}`);
  uni.navigateTo({ url: q.length ? `/pages/checkout/index?${q.join('&')}` : '/pages/checkout/index' });
};

/** 列表进详情时 URL 携带的桌台/门店信息（详情接口未回 tableId 时用于加餐） */
function mergeRouteOrderMeta(options) {
  if (!options || typeof options !== 'object') return;
  const routeTableId = String(options.tableId ?? options.tableid ?? '').trim();
  const routeStoreId = String(options.storeId ?? options.storeid ?? '').trim();
  const routeDiners = options.dinerCount ?? options.diners ?? '';
  const od = orderDetail.value;
  if (routeTableId && !String(od.tableId ?? '').trim()) {
    od.tableId = routeTableId;
    if (!String(od.storeTableId ?? '').trim()) od.storeTableId = routeTableId;
  }
  if (routeStoreId && !String(od.storeId ?? '').trim()) od.storeId = routeStoreId;
  if (routeDiners !== '' && routeDiners != null && !String(od.dinerCount ?? '').trim()) {
    od.dinerCount = routeDiners;
  }
}

onLoad(async (e) => {
  if (e.payType) payType.value = e.payType;
  const orderId = e?.orderId ?? e?.id ?? '';
  detailOrderId.value = orderId;
  if (!orderId) {
    uni.showToast({ title: '缺少订单ID', icon: 'none' });
    return;
  }
  try {
    orderPriceSectionReady.value = false;
    const res = await GetOrderInfo(orderId);
    applyOrderData(res);
    mergeRouteOrderMeta(e);
  } catch (err) {
    orderPriceSectionReady.value = false;
    console.error('订单详情加载失败:', err);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
});
</script>

<style lang="scss" scoped>
.content {
  padding: 0 30rpx 300rpx;
}

.card {
  background-color: #fff;
  border-radius: 24rpx;
  padding: 30rpx 0;
  margin-top: 20rpx;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30rpx;
    height: 40rpx;
    position: relative;
    font-size: 27rpx;
    color: #151515;
    font-weight: bold;
  }

  .tag {
    width: 10rpx;
    height: 42rpx;
    background: linear-gradient(35deg, #FCB73F 0%, #FC733D 100%);
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    position: absolute;
    left: 0;
    top: 0;
  }

  .card-content {
    padding: 0 30rpx;
  }

  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    font-size: 27rpx;

    .info-item-label {
      color: #666666;
    }

    .info-item-value {
      color: #151515;

      .discount-amount-num {
        color: #e61f19;
      }
    }
  }

  .info-item-textarea {
    width: 100%;
    height: 115rpx;
    border-radius: 8rpx;
    border: 1rpx solid #F2F2F2;
    margin-top: 20rpx;
    font-size: 23rpx;
    color: #AAAAAA;
    box-sizing: border-box;
    padding: 20rpx;
  }

  .info-food {
    margin-top: 20rpx;
  }

  .food-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;

    &:last-child {
      border-bottom: none;
    }

    &__image {
      width: 118rpx;
      height: 118rpx;
      border-radius: 8rpx;
      flex-shrink: 0;
      background-color: #f5f5f5;
    }

    &__info {
      flex: 1;
      margin-left: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
    }

    &__name {
      font-size: 28rpx;
      font-weight: bold;
      color: #151515;
      margin-bottom: 8rpx;
    }

    &__desc {
      font-size: 24rpx;
      color: #666666;
      line-height: 1.5;
    }

    &__tag {
      font-size: 24rpx;
      color: #666666;
      &.signature {
        color: #FC793D;
      }
      &.spicy {
        color: #2E2E2E;
      }
    }

    &__right {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: center;
      margin-left: 20rpx;
    }

    &__price {
      display: flex;
      align-items: baseline;
      color: #151515;
      font-weight: bold;
      margin-bottom: 8rpx;

      .price-symbol {
        font-size: 20rpx;
        margin-right: 2rpx;
      }

      .price-main {
        font-size: 28rpx;
      }

      .price-decimal {
        font-size: 24rpx;
      }
    }

    &__quantity {
      font-size: 24rpx;
      color: #797979;
    }
  }

  .price-line {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    font-size: 27rpx;
    color: #151515;
    border-top: 1rpx solid rgba(170, 170, 170, 0.15);
    font-weight: bold;
    padding-top: 20rpx;
  }

}

.bottom-button {
  width: 100%;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  padding-bottom: env(safe-area-inset-bottom);
  box-shadow: 0rpx -11rpx 46rpx 0rpx rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .bottom-button-text1 {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
    width: 324rpx;
    height: 80rpx;
    border-radius: 23rpx 23rpx 23rpx 23rpx;
    border: 2rpx solid #F47D1F;
    display: flex;
    align-items: center;
    color: #F47D1F;
    justify-content: center;
  }

  .bottom-button-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #fff;
    background: linear-gradient(90deg, #FCB73F 0%, #FC743D 100%);
    border-radius: 23rpx 23rpx 23rpx 23rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 324rpx;
    height: 80rpx;
  }
}

.store-info {
  border-bottom: 1rpx solid rgba(170, 170, 170, 0.15);
  box-sizing: border-box;
  margin: 0 30rpx 30rpx;

  .store-info-title {
    font-size: 27rpx;
    color: #151515;
    font-weight: bold;
    margin-bottom: 10rpx;
  }

  .store-info-address {
    font-size: 23rpx;
    color: #AAAAAA;
    margin-bottom: 30rpx;
  }
}
</style>
