<template>
  <view class="payment-success-page">
    <view class="success-content">
      <view class="icon-wrapper">
        <text class="success-icon">✓</text>
      </view>
      <text class="success-title">支付成功</text>
      <text class="success-desc">您的订单已支付成功，我们将尽快为您发货</text>
      
      <view class="order-info" v-if="orderId">
        <text class="info-text">订单编号：{{ orderNo }}</text>
        <text class="info-text">支付金额：¥{{ amount.toFixed(2) }}</text>
      </view>
      
      <view class="action-buttons">
        <button class="btn primary-btn" @click="viewOrder">查看订单</button>
        <button class="btn secondary-btn" @click="goHome">返回首页</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="uts">
import { ref, onMounted } from 'vue'
import { supabaseService } from '@/utils/supabaseService.uts'

const orderId = ref('')
const orderNo = ref('')
const amount = ref(0)

const getOptionString = (options: UTSJSONObject, key: string): string => {
  try {
    const value = options.getString(key)
    if (value != null) {
      return value
    }
  } catch (e) {
  }

  try {
    const normalized = JSON.parse(JSON.stringify(options)) as UTSJSONObject
    const value = normalized.getString(key)
    if (value != null) {
      return value
    }
  } catch (e) {
  }

  return ''
}

// 定义 loadOrderInfo 函数（必须在 onMounted 之前）
const loadOrderInfo = async () => {
  try {
    const response = await supabaseService.getOrderById(orderId.value)
    console.log('[payment-success] getOrderById response:', JSON.stringify(response))
    
    if (response != null) {
        const orderData = response as UTSJSONObject
        const totalAmount = orderData.getNumber('total_amount')
        const paidAmount = orderData.getNumber('paid_amount')
        console.log('[payment-success] total_amount:', totalAmount, 'paid_amount:', paidAmount)
        
        if (paidAmount != null && paidAmount > 0) {
            amount.value = paidAmount
        } else if (totalAmount != null && totalAmount > 0) {
            amount.value = totalAmount
        }
        
        const orderNoVal = orderData.getString('order_no')
        if (orderNoVal != null && orderNoVal != '') {
            orderNo.value = orderNoVal
        }
    }
  } catch (err) {
    console.error('[payment-success] 加载订单信息失败:', err)
  }
}

onLoad((options) => {
  if (options == null) return

  const optionsObj = options as UTSJSONObject
  const orderIdValue = getOptionString(optionsObj, 'orderId')
  if (orderIdValue != '') {
    orderId.value = orderIdValue
    orderNo.value = orderIdValue

    const amountValue = getOptionString(optionsObj, 'amount')
    if (amountValue != '') {
        const amountStr = amountValue
        console.log('[payment-success] amountStr:', amountStr)
        const parsed = parseFloat(amountStr)
        console.log('[payment-success] parsed:', parsed)
        if (Number.isNaN(parsed) == false) {
            amount.value = parsed
        }
    }
    
    if (amount.value == 0) {
        console.log('[payment-success] amount为0，尝试从数据库查询')
    }
    
    loadOrderInfo()
  }
})

onMounted(() => {
  // 逻辑已移到 onLoad
})

const viewOrder = () => {
  uni.navigateTo({
    url: '/pages/mall/consumer/orders'
  })
}

const goHome = () => {
  uni.switchTab({
    url: '/pages/main/index'
  })
}
</script>

<style scoped>
.payment-success-page {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* height: 100%; */
  flex: 1;
  background-color: #ffffff;
  padding: 0 30px;
}

.success-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.icon-wrapper {
  width: 80px;
  height: 80px;
  border-radius: 40px;
  background-color: #4cd964;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  box-shadow: 0 4px 10px rgba(76, 217, 100, 0.3);
}

.success-icon {
  font-size: 40px;
  color: #ffffff;
  font-weight: bold;
}

.success-title {
  font-size: 24px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 10px;
}

.success-desc {
  font-size: 14px;
  color: #999999;
  text-align: center;
  margin-bottom: 30px;
  line-height: 1.5;
}

.order-info {
  background-color: #f9f9f9;
  padding: 15px 20px;
  border-radius: 8px;
  width: 100%;
  margin-bottom: 30px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-text {
  font-size: 14px;
  color: #666666;
  margin-bottom: 5px;
}

.action-buttons {
  width: 100%;
  display: flex;
  flex-direction: column;
  /* gap: 15px; */
}

.btn {
  width: 100%;
  height: 45px;
  line-height: 45px;
  text-align: center;
  border-radius: 22.5px;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.primary-btn {
  background-color: #007aff;
  color: #ffffff;
  border: none;
}

.secondary-btn {
  background-color: #ffffff;
  color: #666666;
  border: 1px solid #cccccc;
}
</style>

