<template>
  <view class="hotel-customer-theme oc-page">
    <!-- 配送信息 -->
    <view class="oc-section">
      <view class="oc-section-title">📋 配送信息</view>
      <view class="oc-info-line">
        <text class="oc-label">房间号</text>
        <text class="oc-value">{{ roomNo }} {{ roomTypeName }}</text>
      </view>
      <view class="oc-info-line">
        <text class="oc-label">联系人</text>
        <input class="oc-input" v-model="contactName" placeholder="请输入姓名" />
      </view>
      <view class="oc-info-line">
        <text class="oc-label">联系电话</text>
        <input class="oc-input" v-model="contactPhone" placeholder="请输入手机号" type="number" :maxlength="11" />
      </view>
    </view>

    <!-- 送达时间 -->
    <view class="oc-section">
      <view class="oc-section-title">🕐 送达时间</view>
      <view class="oc-time-options">
        <view
          v-for="opt in timeOptions"
          :key="opt.value"
          class="oc-time-opt"
          :class="{ 'oc-time-opt--active': deliveryTimeType === opt.value }"
          @click="deliveryTimeType = opt.value"
        >{{ opt.label }}</view>
      </view>
      <view class="oc-time-hint">预计 {{ estimatedTime }} 左右送达</view>
    </view>

    <!-- 订单明细 -->
    <view class="oc-section">
      <view class="oc-section-title">📝 订单明细</view>
      <view v-for="(item, i) in cartItems" :key="i" class="oc-dish-mini">
        <text class="oc-dm-name">{{ item.dishName }} ×{{ item.quantity }}</text>
        <text class="oc-dm-price">¥{{ (item.unitPrice * item.quantity).toFixed(2) }}</text>
      </view>
      <view v-if="cartItems.length && (cartItems[0].specs?.length || cartItems[0].additions?.length)"
        class="oc-dish-spec-line">
        {{ formatSpecs(cartItems[0]) }}
      </view>
      <view class="oc-divider" />
      <view class="oc-info-line">
        <text class="oc-label">配送费</text>
        <text class="oc-value" style="color: var(--h-succ);">
          {{ deliveryFee > 0 ? '¥' + deliveryFee : '免配送费' }}
        </text>
      </view>
      <view class="oc-total-bar">
        <text class="oc-total-label">合计</text>
        <text class="oc-total-price">¥{{ grandTotal }}</text>
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="oc-submit-btn" @click="submitOrder">确认支付 ¥{{ grandTotal }}</view>
  </view>
</template>

<script setup>
import { computed, ref, onMounted } from 'vue'
import { useHotelOrderStore } from '@/store'
import api from '@/api'

const orderStore = useHotelOrderStore()

const roomNo = computed(() => orderStore.roomInfo?.roomNo || '')
const roomTypeName = computed(() => orderStore.roomInfo?.roomTypeName || '')
const cartItems = computed(() => orderStore.cartItems)
const deliveryFee = computed(() => orderStore.deliveryFee)
const grandTotal = computed(() => (orderStore.cartTotal + deliveryFee.value).toFixed(2))

// 从 Store 读取授权信息，自动填入
const contactName = ref(orderStore.contactName || '')
const contactPhone = ref(orderStore.contactPhone || '')
const deliveryTimeType = ref('ASAP')
const submitting = ref(false)

const timeOptions = [
  { label: '立即送达', value: 'ASAP' },
  { label: '30分钟后', value: 'DELAY_30' },
  { label: '1小时后', value: 'DELAY_60' },
]

const estimatedTime = computed(() => {
  const now = new Date()
  let minutes = 25
  if (deliveryTimeType.value === 'DELAY_30') minutes = 55
  else if (deliveryTimeType.value === 'DELAY_60') minutes = 85
  now.setMinutes(now.getMinutes() + minutes)
  const h = String(now.getHours()).padStart(2, '0')
  const m = String(now.getMinutes()).padStart(2, '0')
  return `${h}:${m}`
})

function formatSpecs(item) {
  const parts = []
  if (item.specs?.length) parts.push(item.specs.map(s => s.optionName).join('·'))
  if (item.additions?.length) parts.push(item.additions.map(a => '+' + a.name).join('·'))
  return parts.join(' / ')
}

async function submitOrder() {
  if (!contactName.value.trim()) {
    uni.showToast({ title: '请输入联系人姓名', icon: 'none' })
    return
  }
  if (!contactPhone.value.trim() || contactPhone.value.length < 11) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return
  }
  if (submitting.value) return
  submitting.value = true

  try {
    const orderData = {
      roomNo: orderStore.roomInfo?.roomNo,
      roomId: orderStore.roomInfo?.roomId,
      contactName: contactName.value,
      contactPhone: contactPhone.value,
      deliveryFee: deliveryFee.value,
      deliveryTimeType: deliveryTimeType.value,
      note: orderStore.orderNote,
      items: cartItems.value.map(item => ({
        dishId: item.dishId,
        dishName: item.dishName,
        specDesc: item.specs?.map(s => s.optionName).join('·') || '',
        additionsDesc: item.additions?.map(a => a.name).join('·') || '',
        quantity: item.quantity,
        unitPrice: item.unitPrice,
        subtotal: item.unitPrice * item.quantity,
        note: item.note || '',
      })),
    }

    const res = await api.hotelOrderCreate(orderData, orderStore.tenantId)
    const orderId = res?.data || res

    // 清空购物车（订单已创建，进入支付流程）
    orderStore.clearCart()

    // 跳转到支付页
    uni.redirectTo({
      url: `/pages/hotel/customer/pay?orderId=${orderId}&amount=${grandTotal.value}&orderNo=${orderData.roomNo}`,
    })
  } catch (err) {
    uni.showToast({ title: err?.message || '下单失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}
</script>

<style lang="scss" scoped>
.oc-page {
  min-height: 100vh;
  background: var(--h-bg, #F7F7F7);
  padding: 24rpx 28rpx;
  padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.oc-section {
  background: #fff;
  border-radius: var(--h-rad, 20rpx);
  padding: 28rpx 24rpx;
  margin-bottom: 20rpx;
  box-shadow: var(--h-shd, 0 2rpx 8rpx rgba(0, 0, 0, 0.04));
}

.oc-section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--h-pri, #2D5016);
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid var(--h-bdr-lt, #F5F5F5);
}

.oc-info-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  font-size: 26rpx;
}

.oc-label {
  color: var(--h-txt-sub, #666);
  flex-shrink: 0;
  width: 160rpx;
}

.oc-value {
  color: var(--h-txt, #1A1A1A);
  font-weight: 500;
}

.oc-input {
  flex: 1;
  text-align: right;
  border: none;
  font-size: 26rpx;
  color: var(--h-txt, #1A1A1A);
  background: transparent;
}

/* 送达时间 */
.oc-time-options {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.oc-time-opt {
  padding: 16rpx 32rpx;
  border: 1rpx solid var(--h-bdr, #eee);
  border-radius: 40rpx;
  font-size: 24rpx;
  color: var(--h-txt-sub, #666);
  background: #fff;
}

.oc-time-opt--active {
  background: var(--h-acc-lt, #E8F0E3);
  border-color: var(--h-pri, #2D5016);
  color: var(--h-pri, #2D5016);
  font-weight: 600;
}

.oc-time-hint {
  font-size: 22rpx;
  color: var(--h-txt-light, #999);
  margin-top: 16rpx;
}

/* 订单明细 */
.oc-dish-mini {
  display: flex;
  justify-content: space-between;
  padding: 8rpx 0;
  font-size: 26rpx;
}

.oc-dm-name {
  flex: 1;
  color: var(--h-txt, #1A1A1A);
}

.oc-dm-price {
  color: var(--h-txt-sub, #666);
}

.oc-dish-spec-line {
  font-size: 22rpx;
  color: var(--h-txt-light, #999);
  padding: 0 0 12rpx;
}

.oc-divider {
  border-top: 1rpx dashed var(--h-bdr, #eee);
  margin: 12rpx 0;
}

.oc-total-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 8rpx;
}

.oc-total-label {
  font-size: 26rpx;
  color: var(--h-txt-sub, #666);
}

.oc-total-price {
  font-size: 44rpx;
  font-weight: 700;
  color: var(--h-warn, #D97706);
}

/* 提交按钮 */
.oc-submit-btn {
  width: 100%;
  box-sizing: border-box;
  padding: 28rpx;
  border-radius: 48rpx;
  background: var(--h-pri, #2D5016);
  color: #fff;
  font-size: 30rpx;
  font-weight: 700;
  text-align: center;
  box-shadow: 0 8rpx 24rpx rgba(45, 80, 22, 0.3);
  margin-top: 8rpx;
}

.oc-submit-btn:active {
  opacity: 0.85;
}
</style>
