<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 class="info-item-value remark-text">{{ orderInfo.remark || '—' }}</view>
        </view>
      </view>
    </view>

    <view class="card" v-if="displayFoodList.length > 0">
      <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 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>

    <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="info-item info-item--coupon">
          <view class="info-item-label">优惠券</view>
          <view class="info-item-value coupon-value">
            <text v-if="(orderInfo.discountAmount ?? 0) > 0" class="coupon-amount">{{ couponDisplayText }}</text>
            <text v-else class="coupon-placeholder">—</text>
          </view>
        </view>
        <view v-if="(orderInfo.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(orderInfo.discountAmount) }}</text>
          </view>
        </view>
        <view class="price-line">
          <view class="price-line-label">应付金额</view>
          <view class="price-line-value">¥{{ formatPrice(orderInfo.payAmount ?? 0) }}</view>
        </view>
      </view>
    </view>

    <view class="bottom-button">
      <view class="bottom-button-text" hover-class="hover-active" @click="handleConfirmPay">确认支付 ¥{{ formatPrice(orderInfo.payAmount ?? 0) }}</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';

const orderId = ref('');
const orderInfo = ref({
  orderNo: '',
  storeId: '',
  tableId: '',
  tableNumber: '',
  diners: '',
  contactPhone: '',
  remark: '',
  totalAmount: 0,
  dishTotal: null,
  utensilFee: 0,
  couponId: null,
  couponName: '',
  couponType: null,   // 1 满减 2 折扣
  discountRate: null, // 折扣券力度，如 5.5 表示 5.5折
  nominalValue: null, // 满减券面额
  discountAmount: 0,
  payAmount: 0
});

const foodList = ref([]);

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

// 菜品总价：绑定 totalAmount
const dishTotal = computed(() => {
  const total = Number(orderInfo.value.totalAmount) || 0;
  return Math.max(0, total);
});

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

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

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');
}

// 将 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 ?? '',
    quantity: item?.quantity ?? 1,
    tags: normalizeTags(rawTags)
  };
}

const fetchOrderDetail = async () => {
  const id = orderId.value || '';
  if (!id) return;
  try {
    const res = await diningApi.GetOrderInfo(id);
    const raw = res?.data ?? res ?? {};
    orderInfo.value.orderNo = raw?.orderNo ?? raw?.orderId ?? '';
    orderInfo.value.storeId = raw?.storeId ?? raw?.store_id ?? '';
    orderInfo.value.tableId = raw?.tableId ?? raw?.tableNumber ?? '';
    orderInfo.value.tableNumber = raw?.tableNumber ?? raw?.tableNo ?? '';
    orderInfo.value.diners = raw?.dinerCount ?? '';
    orderInfo.value.contactPhone = raw?.contactPhone ?? raw?.phone ?? '';
    orderInfo.value.remark = raw?.remark ?? '';
    const total = Number(raw?.totalAmount ?? raw?.orderAmount ?? raw?.foodAmount ?? 0) || 0;
    orderInfo.value.totalAmount = total;
    orderInfo.value.dishTotal = raw?.dishTotal != null ? Number(raw.dishTotal) : null;
    orderInfo.value.utensilFee = Number(raw?.tablewareFee ?? raw?.tablewareAmount ?? 0) || 0;
    orderInfo.value.couponId = raw?.couponId ?? null;
    orderInfo.value.couponName = raw?.couponName ?? '';
    orderInfo.value.couponType = raw?.couponType ?? null;
    const rawRate = raw?.discountRate;
    orderInfo.value.discountRate = rawRate != null && rawRate !== '' ? (Number(rawRate) || 0) / 10 : null;
    orderInfo.value.nominalValue = raw?.nominalValue ?? null;
    orderInfo.value.discountAmount = Number(raw?.discountAmount ?? raw?.couponAmount ?? raw?.couponDiscount ?? 0) || 0;
    orderInfo.value.payAmount = Number(raw?.payAmount ?? raw?.totalAmount ?? raw?.totalPrice ?? 0) || 0;
    const list = raw?.orderItemList ?? raw?.orderItems ?? raw?.items ?? raw?.detailList ?? [];
    foodList.value = (Array.isArray(list) ? list : []).map(normalizeOrderItem);
  } catch (err) {
    console.error('获取订单详情失败:', err);
    uni.showToast({ title: '加载失败', icon: 'none' });
  }
};

const handleConfirmPay = async () => {
  const id = orderId.value || '';
  if (!id) {
    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 ?? 0) || 0;
  if (priceAmount <= 0) {
    uni.showToast({ title: '订单金额异常', icon: 'none' });
    return;
  }
  const orderNo = orderInfo.value.orderNo || '';
  if (!orderNo) {
    uni.showToast({ title: '缺少订单号', icon: 'none' });
    return;
  }
  const price = Math.round(priceAmount * 100);
  uni.showLoading({ title: '拉起支付...' });
  try {
    const storeId = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
    const res = await diningApi.PostOrderPay({
      orderNo,
      payer: openid,
      price,
      subject: '订单支付',
      storeId: storeId || undefined
    });
    uni.hideLoading();
    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 oid = orderId.value || '';
        if (oid) {
          diningApi.PostOrderSettlementUnlock({ orderId: oid }).catch((e) => console.warn('解锁订单失败:', e));
        }
        const payType = 'wechatPayMininProgram';
        const transactionId = orderNo;
        const sid = orderInfo.value.storeId || uni.getStorageSync('currentStoreId') || '';
        const q = [`id=${encodeURIComponent(oid)}`, `payType=${encodeURIComponent(payType)}`, `transactionId=${encodeURIComponent(transactionId)}`];
        if (sid) q.push(`storeId=${encodeURIComponent(sid)}`);
        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(async (options) => {
  const id = options?.orderId ?? options?.id ?? '';
  orderId.value = id;
  if (options?.orderNo) orderInfo.value.orderNo = options.orderNo;
  if (options?.tableId) orderInfo.value.tableId = options.tableId;
  if (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 !== '') {
    orderInfo.value.payAmount = Number(options.totalAmount) || 0;
  }
  if (id) {
    await fetchOrderDetail();
  }
});

onShow(() => {
  const id = orderId.value || '';
  if (id) {
    diningApi.PostOrderSettlementLock({ orderId: id }).catch((e) => console.warn('锁定订单失败:', e));
  }
});

onUnload(() => {
  const id = orderId.value || '';
  if (id) {
    diningApi.PostOrderSettlementUnlock({ orderId: id }).catch((e) => console.warn('解锁订单失败:', e));
  }
});
</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;
    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: 0;
    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;

      &.remark-text {
        flex: 1;
        text-align: right;
        word-break: break-all;
      }
    }

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

  .price-line {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 24rpx;
    padding-top: 24rpx;
    border-top: 1rpx solid #f0f0f0;
    font-size: 28rpx;
    font-weight: bold;

    .price-line-label {
      color: #151515;
    }

    .price-line-value {
      color: #E61F19;
    }
  }

  .info-food {
    .food-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;

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

      &__image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 12rpx;
        flex-shrink: 0;
        background: #f5f5f5;
      }

      &__info {
        flex: 1;
        margin-left: 24rpx;
        min-width: 0;
      }

      &__name {
        font-size: 28rpx;
        color: #151515;
        font-weight: 500;
      }

      &__desc {
        font-size: 22rpx;
        color: #999;
        margin-top: 6rpx;
      }

      &__tag {
        margin-right: 4rpx;
        &.signature {
          color: #FC793D;
        }
        &.spicy {
          color: #2E2E2E;
        }
      }

      &__right {
        flex-shrink: 0;
        text-align: right;
      }

      &__price .price-main {
        font-size: 28rpx;
        color: #151515;
        font-weight: 600;
      }

      &__quantity {
        font-size: 24rpx;
        color: #999;
        margin-top: 6rpx;
      }
    }
  }
}

.bottom-button {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);

  .bottom-button-text {
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    background: linear-gradient(90deg, #FCB73F 0%, #FC733D 100%);
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    border-radius: 44rpx;
  }

  .hover-active {
    opacity: 0.9;
  }
}
</style>
