<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.tablewareFee }}</view>
        </view>
        <view class="info-item info-item--coupon">
          <view class="info-item-label">优惠券</view>
          <view class="info-item-value coupon-value">
            <text v-if="couponDisplayText !== '—'" class="coupon-amount">{{ couponDisplayText }}</text>
            <text v-else class="coupon-placeholder">—</text>
          </view>
        </view>
        <view v-if="(priceDetail.discountAmount ?? 0) > 0" class="info-item info-item--coupon">
          <view class="info-item-label">优惠金额</view>
          <view class="info-item-value coupon-value">
            <text class="coupon-amount">-¥{{ formatPrice(priceDetail.discountAmount) }}</text>
          </view>
        </view>
        <view class="price-line">
          <view class="price-line-label">合计</view>
          <view class="price-line-value">¥{{ priceDetail.total }}</view>
        </view>
       
      </view>
    </view>
    <!-- 已完成订单显示支付信息 -->
    <view v-if="orderDetail.orderStatus === 3" 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">{{ payMethodText }}</view>
          <view class="info-item-value">¥{{ priceDetail.total }}</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 || '—' }}</view>
        </view>
      </view>
    </view>

    <!-- 底部按钮：已完成(3)不显示 -->
    <view v-if="orderDetail.orderStatus !== 3" class="bottom-button">
      <view class="bottom-button-text1 " hover-class="hover-active" @click="handleConfirmOrder">去加餐</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 { 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: '',   // 桌号ID，用于跳转加餐
  tableNo: '',    // 桌号展示（tableNumber）
  dinerCount: '',
  createTime: '',
  contactPhone: '',
  remark: '',
  orderStatus: null,
  payType: ''  // 支付方式，如 wechatPayMininProgram
});

// 价格明细（两位小数）
const priceDetail = ref({
  dishTotal: '0.00',
  tablewareFee: '0.00',
  couponDiscount: '0.00',
  discountAmount: 0,
  couponName: '',
  couponType: null,
  nominalValue: null,
  discountRate: null,
  total: '0.00'
});

// 支付方式展示：根据 payType 转为中文
const payMethodText = computed(() => {
  const t = orderDetail.value?.payType ?? '';
  if (/wechat|微信/i.test(t)) return '微信支付';
  if (/alipay|支付宝/i.test(t)) return '支付宝';
  return t || '微信支付';
});

// 优惠券展示：满减券显示 nominalValue+元，折扣券显示 discountRate+折，否则显示 couponName 或 已使用优惠券（与 checkout 一致）
const couponDisplayText = computed(() => {
  const p = priceDetail.value;
  const amount = Number(p.discountAmount ?? p.couponDiscount ?? 0) || 0;
  if (amount <= 0) return '—';
  const type = Number(p.couponType);
  if (type === 1 && (p.nominalValue != null && p.nominalValue !== '')) {
    const val = Number(p.nominalValue);
    return Number.isNaN(val) ? (p.couponName || '已使用优惠券') : val + '元';
  }
  if (type === 2 && (p.discountRate != null && p.discountRate !== '')) {
    const rate = Number(p.discountRate);
    return Number.isNaN(rate) ? (p.couponName || '已使用优惠券') : rate + '折';
  }
  return p.couponName || '已使用优惠券';
});

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

// 菜品详情展示：包含所有项（含餐具 id/cuisineId === -1）
const displayFoodList = computed(() => foodList.value ?? []);

// 菜品图片：餐具（id/cuisineId=-1）用本地图
function getItemImage(item) {
  if (Number(item?.id ?? item?.cuisineId) === -1) return '/static/utensilFee.png';
  const raw = item?.image ?? item?.cuisineImage ?? item?.imageUrl ?? '';
  if (typeof raw === 'string' && (raw.startsWith('http') || raw.startsWith('//'))) return raw;
  return getFileUrl(raw || '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);
}

// 将接口订单项转为列表项
function normalizeOrderItem(item) {
  const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
  const images = item?.images ?? item?.image;
  const imageUrl = Array.isArray(images) ? images[0] : images;
  return {
    id: item?.id ?? item?.cuisineId,
    name: item?.cuisineName ?? item?.name ?? '',
    price: item?.totalPrice ?? item?.unitPrice ?? item?.price ?? 0,
    image: imageUrl ?? item?.image ?? item?.cuisineImage ?? 'img/icon/shop.png',
    quantity: item?.quantity ?? 1,
    tags: normalizeTags(rawTags)
  };
}

// 从接口数据填充 orderDetail、priceDetail、foodList
function applyOrderData(data) {
  const raw = data?.data ?? data ?? {};
  const store = raw?.storeInfo ?? raw?.store ?? {};
  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 ?? '',
    orderNo: raw?.orderNo ?? raw?.orderId ?? '',
    tableId: raw?.tableId ?? raw?.tableNumber ?? '',  // 加餐跳转用
    tableNo: raw?.tableNumber ?? raw?.tableNo ?? raw?.tableName ?? '',
    dinerCount: raw?.dinerCount ?? '',
    createTime: raw?.createdTime ?? raw?.createTime ?? raw?.orderTime ?? '',
    contactPhone: raw?.contactPhone ?? raw?.phone ?? '',
    remark: raw?.remark ?? '',
    orderStatus: raw?.orderStatus ?? raw?.status ?? null,
    payType: raw?.payType ?? raw?.payMethod ?? ''
  };
  const dishTotal = raw?.totalAmount ?? raw?.dishTotal ?? raw?.orderAmount ?? raw?.foodAmount ?? 0;
  const tablewareFee = raw?.tablewareFee ?? raw?.tablewareAmount ?? 0;
  const couponDiscount = raw?.couponAmount ?? raw?.couponDiscount ?? 0;
  const discountAmountVal = Number(raw?.discountAmount ?? raw?.couponAmount ?? raw?.couponDiscount ?? 0) || 0;
  const total = raw?.payAmount ?? raw?.totalAmount ?? raw?.totalPrice ?? 0;
  const rawDiscountRate = raw?.discountRate ?? raw?.couponInfo?.discountRate ?? raw?.coupon?.discountRate;
  const discountRateVal = rawDiscountRate != null && rawDiscountRate !== '' ? (Number(rawDiscountRate) || 0) / 10 : null;
  priceDetail.value = {
    dishTotal: formatPrice(dishTotal),
    tablewareFee: formatPrice(tablewareFee),
    couponDiscount: formatPrice(couponDiscount),
    discountAmount: discountAmountVal,
    couponName: raw?.couponName ?? '',
    couponType: raw?.couponType ?? null,
    nominalValue: raw?.nominalValue ?? null,
    discountRate: discountRateVal,
    total: formatPrice(total)
  };
  const list = raw?.orderItemList ?? raw?.orderItems ?? raw?.items ?? raw?.detailList ?? [];
  foodList.value = (Array.isArray(list) ? list : []).map(normalizeOrderItem);
}

// 去加餐：跳转点餐页，携带桌号与就餐人数
const handleConfirmOrder = () => {
  const tableid = uni.getStorageSync('currentTableId');
  const diners = orderDetail.value?.dinerCount ?? '';
  const storeId = orderDetail.value?.storeId ?? '';
  if (!tableid) {
    uni.showToast({ title: '订单缺少桌号信息，无法加餐', icon: 'none' });
    return;
  }
  const q = [];
  q.push(`tableid=${encodeURIComponent(String(tableid))}`);
  if (diners !== '' && diners != null) q.push(`diners=${encodeURIComponent(String(diners))}`);
  if (storeId !== '' && storeId != null) q.push(`storeId=${encodeURIComponent(String(storeId))}`);
  uni.navigateTo({ url: `/pages/orderFood/index?${q.join('&')}` });
};

// 去结算：跳转确认订单页，携带订单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 = priceDetail.value?.total ?? '';
  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' });
};

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 {
    const res = await GetOrderInfo(orderId);
    applyOrderData(res);
  } catch (err) {
    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;
    }

    &--coupon .coupon-value {
      display: flex;
      align-items: center;
      gap: 8rpx;
    }
    .coupon-amount {
      color: #E61F19;
    }
    .coupon-placeholder {
      color: #999999;
    }
  }

  .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>
