<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 foodList" :key="item.id || index" class="food-item">
            <!-- 菜品图片 -->
            <image :src="getFileUrl(item.image)" 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">
                  {{ 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">
          <view class="info-item-label">优惠券</view>
          <view class="info-item-value">¥{{ priceDetail.couponDiscount }}</view>
        </view>
        <view class="price-line">
          <view class="price-line-label">合计</view>
          <view class="price-line-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 ?? '—' }}</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>

    <!-- 底部按钮 -->
    <view 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 } from "vue";
import { go } from "@/utils/utils.js";
import { getFileUrl } from "@/utils/file.js";
import { GetOrderInfo } from "@/api/dining.js";

const payType = ref('confirmOrder'); // confirmOrder 确认下单 confirmPay 确认支付

// 订单详情（店铺、订单信息）
const orderDetail = ref({
  storeName: '',
  storeAddress: '',
  orderNo: '',
  tableId: '',   // 桌号ID，用于跳转加餐
  tableNo: '',    // 桌号展示（tableNumber）
  dinerCount: '',
  createTime: '',
  contactPhone: '',
  remark: ''
});

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

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

// 金额保留两位小数
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);
};

// 将接口订单项转为列表项
function normalizeOrderItem(item) {
  const tags = item?.tags ?? [];
  const tagArr = Array.isArray(tags) ? tags : [];
  const images = item?.images;
  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: tagArr.map((t) => (typeof t === 'string' ? { text: t } : { text: t?.text ?? t?.tagName ?? '' }))
  };
}

// 从接口数据填充 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 ?? '',
    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 ?? ''
  };
  const dishTotal = raw?.dishTotal ?? raw?.orderAmount ?? raw?.foodAmount ?? 0;
  const tablewareFee = raw?.tablewareFee ?? raw?.tablewareAmount ?? 0;
  const couponDiscount = raw?.couponAmount ?? raw?.couponDiscount ?? 0;
  const total = raw?.totalAmount ?? raw?.totalPrice ?? raw?.payAmount ?? 0;
  priceDetail.value = {
    dishTotal: formatPrice(dishTotal),
    tablewareFee: formatPrice(tablewareFee),
    couponDiscount: formatPrice(couponDiscount),
    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 = orderDetail.value?.tableId || orderDetail.value?.tableNo || '';
  const diners = orderDetail.value?.dinerCount ?? '';
  const q = [];
  if (tableid !== '') q.push(`tableid=${encodeURIComponent(String(tableid))}`);
  if (diners !== '') q.push(`diners=${encodeURIComponent(String(diners))}`);
  go(q.length ? `/pages/orderFood/index?${q.join('&')}` : '/pages/orderFood/index');
};

// 去结算：跳转确认订单页，携带桌号、就餐人数、订单金额
const handleConfirmPay = () => {
  const tableId = orderDetail.value?.tableId || orderDetail.value?.tableNo || '';
  const diners = orderDetail.value?.dinerCount ?? '';
  const totalAmount = priceDetail.value?.total ?? '';
  const q = [];
  if (tableId !== '') q.push(`tableId=${encodeURIComponent(String(tableId))}`);
  if (diners !== '') q.push(`diners=${encodeURIComponent(String(diners))}`);
  if (totalAmount !== '' && totalAmount != null) q.push(`totalAmount=${encodeURIComponent(String(totalAmount))}`);
  go(q.length ? `/pages/placeOrder/index?${q.join('&')}` : '/pages/placeOrder/index');
};

onLoad(async (e) => {
  if (e.payType) payType.value = e.payType;
  const orderId = e?.orderId ?? e?.id ?? '';
  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;
    }
  }

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

    &__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>
