<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"
          :disabled="fromCheckout"
          :readonly="fromCheckout"
        ></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">
                  {{ 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(orderInfo.totalAmount) }}</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="info-item">
          <view class="info-item-label">优惠券</view>
          <view class="info-item-value">¥{{ formatPrice(orderInfo.discountAmount ?? 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>

    <!-- 底部按钮：带金额(来自去结算)显示「确认支付」且备注不可改；不带金额显示「确认下单」且备注可改 -->
    <view class="bottom-button">
      <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmPay" v-if="fromCheckout">确认支付 ¥{{ formatPrice(orderInfo.payAmount ?? orderInfo.totalAmount) }}</view>
      <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmOrder" v-else>确认下单</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 { useUserStore } from "@/store/user.js";
import { PostOrderCreate, PostOrderPay } from "@/api/dining.js";

const payType = ref('confirmOrder'); // confirmOrder 确认下单 confirmPay 确认支付
/** 仅当从订单列表/结果页等「去结算」进入时为 true，底部显示确认支付 */
const fromCheckout = ref(false);
/** 待支付订单ID，确认支付时用于调起微信支付 */
const payOrderId = ref('');

// 订单信息（从购物车带过来或 URL 参数）
const orderInfo = ref({
  orderNo: '',
  tableId: '',      // 桌号ID，接口入参用
  tableNumber: '',  // 桌号展示（如 2），优先显示
  diners: '',
  contactPhone: '',
  remark: '',
  totalAmount: 0,
  utensilFee: 0,
  discountAmount: 0,
  payAmount: 0
});

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

// 菜品图片：兼容 cuisineImage/image，逗号分隔取首图
function getItemImage(item) {
  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);
}

// 将存储的购物车项转为确认页展示格式（兼容 cuisineName/cuisineImage/unitPrice 等）
function normalizeCartItem(item) {
  const image = item?.cuisineImage ?? item?.image ?? item?.imageUrl ?? '';
  const url = typeof image === 'string' ? image.split(',')[0].trim() : image;
  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: item?.tags ?? [],
    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 res = await PostOrderCreate({
      tableId,
      contactPhone,
      couponId: null,
      dinerCount: dinerCount || undefined,
      immediatePay: 0,
      remark: remark || undefined
    });
    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)
    }));
    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' });
  }
};

// 确认支付：调起微信支付
const handleConfirmPay = async () => {
  const orderId = payOrderId.value || '';
  if (!orderId) {
    uni.showToast({ title: '缺少订单ID', icon: 'none' });
    return;
  }
  const userStore = useUserStore();
  const openid = userStore.getOpenId || '';
  if (!openid) {
    uni.showToast({ title: '请先登录', icon: 'none' });
    return;
  }
  const priceAmount = Number(orderInfo.value.payAmount ?? orderInfo.value.totalAmount ?? 0) || 0;
  if (priceAmount <= 0) {
    uni.showToast({ title: '订单金额异常', icon: 'none' });
    return;
  }
  const orderNo = orderInfo.value.orderNo || '';
  if (!orderNo) {
    uni.showToast({ title: '缺少订单号', icon: 'none' });
    return;
  }
  // 后端要求金额乘 100 传入（分）
  const price = Math.round(priceAmount * 100);
  uni.showLoading({ title: '拉起支付...' });
  try {
    const res = await PostOrderPay({
      orderNo,
      payer: openid,
      price,
      subject: '订单支付'
    });
    uni.hideLoading();
   console.log(res)
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp:res.timestamp,
      nonceStr:res.nonce,
      package:res.prepayId,
      signType:res.signType,
      paySign:res.sign,
      success: () => {
        uni.showToast({ title: '支付成功', icon: 'success' });
        const payType = 'wechatPayMininProgram';
        const transactionId = orderNo;
        const q = [`id=${encodeURIComponent(orderId)}`, `payType=${encodeURIComponent(payType)}`, `transactionId=${encodeURIComponent(transactionId)}`];
        setTimeout(() => go(`/pages/paymentSuccess/index?${q.join('&')}`), 1500);
      },
      fail: (err) => {
        const msg = err?.errMsg ?? err?.message ?? '支付失败';
        if (String(msg).includes('cancel')) {
          uni.showToast({ title: '已取消支付', icon: 'none' });
        } else {
          uni.showToast({ title: msg || '支付失败', icon: 'none' });
        }
      }
    });
  } catch (e) {
    uni.hideLoading();
    uni.showToast({ title: e?.message ?? '获取支付参数失败', icon: 'none' });
  }
};

onLoad((options) => {
  if (options?.payType) payType.value = options.payType;
  const userStore = useUserStore();
  const contactPhone = userStore.getUserInfo?.phone ?? userStore.getUserInfo?.contactPhone ?? userStore.getUserInfo?.mobile ?? '';
  orderInfo.value.contactPhone = contactPhone;
  if (options?.orderId != null && options?.orderId !== '') payOrderId.value = options.orderId;
  if (options?.orderNo != null && options?.orderNo !== '') orderInfo.value.orderNo = options.orderNo;
  if (options?.tableId) orderInfo.value.tableId = options.tableId;
  if (options?.tableNumber != null && options?.tableNumber !== '') orderInfo.value.tableNumber = options.tableNumber;
  if (options?.diners) orderInfo.value.diners = options.diners;
  if (options?.remark != null && options?.remark !== '') orderInfo.value.remark = decodeURIComponent(options.remark);
  if (options?.totalAmount != null && options?.totalAmount !== '') {
    fromCheckout.value = true;
    const total = Number(options.totalAmount) || 0;
    orderInfo.value.totalAmount = total;
    orderInfo.value.payAmount = total;
  }
  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;
      orderInfo.value.payAmount = total;
    } catch (e) {
      console.error('解析购物车数据失败:', e);
    }
  }
  if (orderInfo.value.tableId) uni.setStorageSync('currentTableId', String(orderInfo.value.tableId));
});
</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);

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