<template>
  <!-- 下单页面 -->
  <view class="content">
    <!-- 订单卡片 -->
    <view class="card">
      <view class="card-header">
        <view class='tag'></view>
        <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">{{ orderInfo.tableNumber || orderInfo.tableId || '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">用餐人数</view>
          <view class="info-item-value">{{ orderInfo.diners || '—' }}人</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">联系电话</view>
          <view class="info-item-value">{{ orderInfo.contactPhone || '—' }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">备注信息</view>
        </view>
        <textarea
          v-model="orderInfo.remark"
          placeholder="请输入特殊需求，如少辣、不要香菜等（最多30字）"
          class="info-item-textarea"
          maxlength="30"
        ></textarea>
      </view>
    </view>

    <!-- 菜品清单 -->
    <view class="card">
      <view class="card-header">
        <view class='tag'></view>
        <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 || item.cuisineId || index" class="food-item">
            <!-- 菜品图片：兼容 cuisineImage/image，逗号分隔取首图 -->
            <image :src="getItemImage(item)" mode="aspectFill" class="food-item__image"></image>

            <!-- 菜品信息 -->
            <view class="food-item__info">
              <view class="food-item__name">{{ item.name || item.cuisineName }}</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(getItemPrice(item)) }}</text>
              </view>
              <view class="food-item__quantity">{{ item.quantity || 1 }}份</view>
            </view>
          </view>
        </view>
      </view>
    </view>


    <!-- 总价 -->
    <view class="card">
      <view class="card-header">
        <view class='tag'></view>
        <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">¥{{ formatPrice(dishTotal) }}</view>
        </view>
        <view class="info-item">
          <view class="info-item-label">餐具费</view>
          <view class="info-item-value">¥{{ formatPrice(orderInfo.utensilFee ?? 0) }}</view>
        </view>

        <view class="price-line">
          <view class="price-line-label">应付金额</view>
          <view class="price-line-value">¥{{ formatPrice(orderInfo.payAmount ?? orderInfo.totalAmount) }}</view>
        </view>
      </view>
    </view>

    <!-- 底部按钮：确认下单（去结算请走 pages/checkout/index） -->
    <view class="bottom-button">
      <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmOrder">确认下单</view>
    </view>

  </view>
</template>

<script setup>
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import { ref, computed } from "vue";
import { go } from "@/utils/utils.js";
import { getFileUrl } from "@/utils/file.js";
import { useUserStore } from "@/store/user.js";
import * as diningApi from "@/api/dining.js";

// 订单信息（从购物车带过来或 URL 参数）
const orderInfo = ref({
  orderNo: '',
  tableId: '',
  tableNumber: '',
  diners: '',
  contactPhone: '',
  remark: '',
  totalAmount: 0,
  dishTotal: null,
  utensilFee: 0,
  discountAmount: 0,
  payAmount: 0,
  couponId: null
});

// 菜品列表（从购物车带过来）
const foodList = ref([]);

// 菜品清单展示：排除餐具（id/cuisineId === -1）
const displayFoodList = computed(() => {
  return (foodList.value ?? []).filter((it) => Number(it?.id ?? it?.cuisineId) !== -1);
});

// 菜品总价（不含餐具费）：仅按菜品清单中非餐具项汇总，不包含餐具费
const dishTotal = computed(() => {
  const list = displayFoodList.value ?? [];
  const sum = list.reduce((s, it) => {
    const qty = Number(it?.quantity) || 0;
    const price = Number(it?.unitPrice ?? it?.price ?? it?.totalPrice ?? it?.salePrice ?? 0) || 0;
    return s + qty * price;
  }, 0);
  return Math.max(0, sum);
});

// 菜品图片：餐具（id/cuisineId=-1）固定用本地 /static/utensilFee.png，其他取接口图
function getItemImage(item) {
  const id = item?.id ?? item?.cuisineId;
  if (Number(id) === -1) return '/static/utensilFee.png';
  const raw = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
  const url = typeof raw === 'string' ? raw.split(',')[0].trim() : raw;
  return url ? getFileUrl(url) : '';
}

// 单品单价：列表展示用 unitPrice/price
function getItemPrice(item) {
  const p = item?.unitPrice ?? item?.price ?? item?.totalPrice ?? item?.salePrice ?? 0;
  return Number(p) || 0;
}

function formatPrice(price) {
  const num = Number(price);
  return Number.isNaN(num) ? '0.00' : num.toFixed(2);
}

// 根据菜品总价（不含餐具）、餐具费计算应付金额（优惠券在结算页选择，确认订单页不选券）
const updatePayAmount = () => {
  const dish = dishTotal.value;
  const utensil = Number(orderInfo.value.utensilFee) || 0;
  orderInfo.value.payAmount = Math.max(0, dish + utensil);
};

// 将 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);
}

// 将存储的购物车项转为确认页展示格式（兼容 cuisineName/cuisineImage/unitPrice/tags 等）
function normalizeCartItem(item) {
  const image = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
  const url = typeof image === 'string' ? image.split(',')[0].trim() : image;
  const rawTags = item?.tags ?? item?.tagList ?? item?.tagNames ?? item?.labels ?? item?.tag;
  return {
    id: item?.id ?? item?.cuisineId,
    name: item?.name ?? item?.cuisineName,
    cuisineName: item?.cuisineName,
    price: item?.unitPrice ?? item?.price,
    image: url,
    cuisineImage: item?.cuisineImage,
    quantity: Number(item?.quantity) || 0,
    tags: normalizeTags(rawTags),
    subtotalAmount: item?.subtotalAmount,
    remark: item?.remark
  };
}

const handleConfirmOrder = async () => {
  const tableId = orderInfo.value.tableId;
  const contactPhone = orderInfo.value.contactPhone ?? '';
  const dinerCount = Number(orderInfo.value.diners) || 0;
  if (!tableId) {
    uni.showToast({ title: '请先选择桌号', icon: 'none' });
    return;
  }
  if (!contactPhone) {
    uni.showToast({ title: '请先填写联系电话', icon: 'none' });
    return;
  }
  const remark = (orderInfo.value.remark ?? '').trim().slice(0, 30);
  uni.showLoading({ title: '提交中...' });
  try {
    const tablewareFee = Number(orderInfo.value.utensilFee) || 0;
    const payAmount = Number((Number(orderInfo.value.payAmount) ?? 0).toFixed(2));
    const totalAmount = Number((Number(dishTotal.value) ?? 0).toFixed(2));
    const createParams = {
      tableId,
      contactPhone,
      totalAmount,
      tablewareFee,
      payAmount,
      dinerCount: dinerCount || undefined,
      immediatePay: 0,
      remark: remark || undefined
    };
    const res = await diningApi.PostOrderCreate(createParams);
    uni.hideLoading();
    const orderId = res?.id ?? res?.orderId ?? res?.data?.id ?? res?.data?.orderId;
    const orderNo = res?.orderNo ?? res?.data?.orderNo ?? orderId ?? '';
    const total = orderInfo.value.payAmount ?? orderInfo.value.totalAmount ?? 0;
    // 结果页「去结算」需带 orderId/orderNo/金额/备注，用于确认支付
    uni.setStorageSync('lastPlaceOrderInfo', JSON.stringify({
      orderId: orderId ?? undefined,
      orderNo: orderNo ?? undefined,
      tableId: orderInfo.value.tableId,
      tableNumber: orderInfo.value.tableNumber,
      diners: orderInfo.value.diners,
      totalAmount: total,
      remark: (orderInfo.value.remark ?? '').trim().slice(0, 30)
    }));
    // 确认下单成功后即将跳转，此时页面不会触发 onUnload，需主动调用解锁
    const unlockFn = diningApi.PostOrderUnlock || diningApi.postOrderUnlock;
    if (typeof unlockFn === 'function' && tableId) {
      unlockFn({ tableId }).catch((err) => console.warn('解锁订单失败:', err));
    }
    if (orderId != null) {
      go(`/pages/result/index?id=${encodeURIComponent(orderId)}`);
    } else {
      go('/pages/result/index');
    }
  } catch (e) {
    uni.hideLoading();
    uni.showToast({ title: e?.message || '下单失败', icon: 'none' });
  }
};

onLoad((options) => {
  const userStore = useUserStore();
  const contactPhone = userStore.getUserInfo?.phone ?? userStore.getUserInfo?.contactPhone ?? userStore.getUserInfo?.mobile ?? '';
  orderInfo.value.contactPhone = contactPhone;
  const raw = uni.getStorageSync('placeOrderCart');
  if (raw) {
    try {
      const data = JSON.parse(raw);
      const list = Array.isArray(data.list) ? data.list : [];
      foodList.value = list.map(normalizeCartItem).filter((item) => (item.quantity || 0) > 0);
      if (data.tableId != null) orderInfo.value.tableId = data.tableId;
      if (data.tableNumber != null) orderInfo.value.tableNumber = data.tableNumber;
      if (data.diners != null) orderInfo.value.diners = data.diners;
      if (data.remark != null) orderInfo.value.remark = data.remark;
      const total = Number(data.totalAmount) || 0;
      orderInfo.value.totalAmount = total;
      if (data.dishTotal != null && data.dishTotal !== '') orderInfo.value.dishTotal = Number(data.dishTotal) || 0;
      const fee = data.utensilFee ?? data.tablewareFee;
      if (fee != null && fee !== '') orderInfo.value.utensilFee = Number(fee) || 0;
      updatePayAmount();
    } catch (e) {
      console.error('解析购物车数据失败:', e);
    }
  }
  if (orderInfo.value.tableId) uni.setStorageSync('currentTableId', String(orderInfo.value.tableId));
  // 不再主动调用 userOwnedByStore，优惠券在点击「优惠券」行打开弹窗时再拉取
});


// 每次进入页面（含从其他页返回）都调用锁定订单接口
onShow(() => {
  const tableId = orderInfo.value?.tableId;
  if (tableId) {
    (diningApi.PostOrderLock || diningApi.postOrderLock)({ tableId }).catch((err) => {
      console.warn('锁定订单失败:', err);
    });
  }
});

// 离开页面时调用解锁订单接口
onUnload(() => {
  const tableId = orderInfo.value?.tableId;
  if (tableId && typeof (diningApi.PostOrderUnlock || diningApi.postOrderUnlock) === 'function') {
    (diningApi.PostOrderUnlock || diningApi.postOrderUnlock)({ tableId }).catch((err) => {
      console.warn('解锁订单失败:', err);
    });
  }
});
</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;
    }

    &--clickable {
      cursor: pointer;
    }

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

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

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