<template>
  <view class="payment-container">
    <!-- 订单状态 -->
    <view class="status-card">
      <view class="status-icon" :class="orderStatus.class"></view>
      <view class="status-text">{{ orderStatus.text }}</view>
      <view class="status-desc">{{ orderStatus.desc }}</view>
    </view>
    
    <!-- 订单信息 -->
    <view class="order-card">
      <view class="card-title">{{ $t('payment.orderInfo') }}</view>
      <view class="info-item">
        <text class="label">{{ $t('order.orderNo') }}</text>
        <text class="value">{{ orderInfo.orderNo || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">{{ $t('order.deviceNo') }}</text>
        <text class="value">{{ orderInfo.deviceNo || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">{{ $t('payment.createTime') }}</text>
        <text class="value">{{ orderInfo.createTime || '-' }}</text>
      </view>
      <view class="info-item">
        <text class="label">{{ $t('payment.contactPhone') }}</text>
        <text class="value">{{ orderInfo.phone || '-' }}</text>
      </view>
    </view>
    
    <!-- 费用信息 -->
    <view class="price-card">
      <view class="card-title">{{ $t('payment.feeInfo') }}</view>
      <view class="price-item">
        <text class="label">{{ $t('payment.deposit') }}</text>
        <text class="value">￥{{ orderInfo.deposit || '99.00' }}</text>
      </view>
      <view class="price-item">
        <text class="label">{{ $t('payment.package') }}</text>
        <text class="value">{{ packageInfo.price }}{{ $t('unit.yuan') }}/{{ packageInfo.time }}{{ $t('time.hour') }}</text>
      </view>
      <view class="price-item total">
        <text class="label">{{ $t('payment.total') }}</text>
        <text class="value">￥{{ totalAmount }}</text>
      </view>
    </view>
    

  
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar">
      <view class="total-amount">
        <text>{{ $t('payment.total') }}：</text>
        <text class="amount">￥{{ totalAmount }}</text>
      </view>
      <view class="pay-btn" @click="handlePayment">{{ $t('payment.payNow') }}</view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { queryById, createWxPayment } from '@/config/api/order.js'
import { getDeviceInfo } from '@/config/api/device.js'
import { updateUserBalance } from '@/config/api/user.js'
import { useI18n } from '@/utils/i18n.js'

const { t } = useI18n()

const orderId = ref(null)
const deviceNo = ref(null)
const orderInfo = ref({})
const packageInfo = ref({
  time: '',
  price: '0.00'
})
const deviceInfo = ref(null)
const passedTotalAmount = ref(null)
const passedDepositAmount = ref(null)

const orderStatus = reactive({
  get text() { return t('payment.waitingForPayment') },
  get desc() { return t('payment.pleasePayIn15Min') },
  class: 'waiting'
})

const totalAmount = computed(() => {
  if (passedTotalAmount.value !== null) {
    return parseFloat(passedTotalAmount.value).toFixed(2);
  }
  const deposit = parseFloat(orderInfo.value.deposit || passedDepositAmount.value || 99)
  const packagePrice = parseFloat(packageInfo.value.price || 0)
  return (deposit + packagePrice).toFixed(2)
})

// 加载订单信息
const loadOrderInfo = async () => {
  try {
    uni.showLoading({
      title: t('common.loading')
    })
    
    const res = await queryById(orderId.value)
    if (res.code === 200 && res.data) {
      const orderData = res.data
      
      // 处理创建时间
      let formattedTime;
      try {
        if (orderData.createTime) {
          formattedTime = formatTime(new Date(orderData.createTime));
        } else {
          formattedTime = formatTime(new Date());
        }
      } catch (e) {
        console.error('时间格式化错误:', e);
        formattedTime = formatTime(new Date());
      }
      
      orderInfo.value = {
        orderNo: orderData.orderNo || orderData.orderId,
        deviceNo: orderData.deviceNo,
        createTime: formattedTime,
        phone: orderData.phone,
        deposit: passedDepositAmount.value || orderData.depositAmount || '99.00',
      }
      
      if (orderData.packageTime && orderData.packagePrice) {
        const timeInHours = (parseFloat(orderData.packageTime) / 60).toFixed(1);
        packageInfo.value = {
          time: timeInHours.toString(),
          price: orderData.packagePrice.toString()
        }
      }
      
      deviceNo.value = orderData.deviceNo;
      await loadDeviceInfo();
    } else {
      throw new Error(t('order.getOrderFailed'))
    }
  } catch (error) {
    console.error('获取订单信息失败:', error)
    uni.showToast({
      title: error.message || t('order.getOrderFailed'),
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 加载设备信息
const loadDeviceInfo = async () => {
  if (!deviceNo.value) return;
  
  try {
    const res = await getDeviceInfo(deviceNo.value);
    if (res.code === 200 && res.data) {
      deviceInfo.value = res.data.device;
      
      if (deviceInfo.value && deviceInfo.value.depositAmount) {
        orderInfo.value.deposit = deviceInfo.value.depositAmount;
      }
    }
  } catch (error) {
    console.error('获取设备信息失败:', error);
  }
}

// 处理支付
const handlePayment = async () => {
  try {
    uni.showLoading({
      title: t('common.processing')
    })
    
    const res = await createWxPayment(orderInfo.value.orderNo)

    if (res && res.code === 200) {
      const payParams = res.data
      
      await uni.requestPayment({
        ...payParams,
        success: async () => {
          uni.showToast({
            title: t('payment.paymentSuccess'),
            icon: 'success'
          });
          
          try {
            await updateUserBalance(orderId.value);
          } catch (error) {
            console.warn('更新用户余额失败:', error);
          }
          
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/order/index?orderId=${orderId.value}`
            });
          }, 1500);
        },
        fail: (err) => {
          console.error('支付失败:', err)
          uni.showToast({
            title: t('payment.paymentFailedRetry'),
            icon: 'none'
          })
        }
      })
    } else {
      throw new Error(res?.msg || t('payment.createPayOrderFailed'))
    }
  } catch (error) {
    console.error('支付失败:', error)
    uni.showToast({
      title: error.message || t('payment.paymentFailed'),
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 格式化时间
const formatTime = (date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const hour = date.getHours().toString().padStart(2, '0')
  const minute = date.getMinutes().toString().padStart(2, '0')
  
  return `${year}-${month}-${day} ${hour}:${minute}`
}

onLoad((options) => {
  uni.setNavigationBarTitle({
    title: t('payment.orderPayment')
  })
  
  if (options && options.orderId) {
    orderId.value = options.orderId
    
    if (options.totalAmount) {
      passedTotalAmount.value = options.totalAmount;
    }
    
    if (options.depositAmount) {
      passedDepositAmount.value = options.depositAmount;
    }
    
    if (options.feeConfig) {
      try {
        const feeConfigStr = decodeURIComponent(options.feeConfig)
        deviceInfo.value = { feeConfig: feeConfigStr }
      } catch (e) {
        console.error('解析URL中的feeConfig失败:', e)
      }
    }
    
    loadOrderInfo()
  } else {
    uni.showToast({
      title: t('order.orderNotExist'),
      icon: 'none'
    })
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/index/index'
      })
    }, 1500)
  }
})
</script>

<style lang="scss" scoped>
.payment-container {
  min-height: 100vh;
  background: #f8f8f8;
  padding: 30rpx;
  padding-bottom: 180rpx;
  box-sizing: border-box;
  
  .status-card {
    background: #fff;
    border-radius: 24rpx;
    padding: 40rpx 30rpx;
    margin-bottom: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    
    .status-icon {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      background: #f5f5f5;
      margin-bottom: 20rpx;
      
      &.waiting {
        background: #FFF9C4;
      }
      
      &.success {
        background: #E8F5E9;
      }
      
      &.failed {
        background: #FFEBEE;
      }
    }
    
    .status-text {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .status-desc {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .order-card, .price-card {
    background: #fff;
    border-radius: 24rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    
    .card-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 20rpx;
      position: relative;
      padding-left: 20rpx;
      
      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        width: 8rpx;
        height: 32rpx;
        background: #1976D2;
        border-radius: 4rpx;
      }
    }
    
    .info-item, .price-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1px solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .label {
        font-size: 28rpx;
        color: #666;
      }
      
      .value {
        font-size: 28rpx;
        color: #333;
      }
      
      &.total {
        margin-top: 10rpx;
        padding-top: 30rpx;
        border-top: 1px solid #f5f5f5;
        
        .label, .value {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
        
        .value {
          color: #FF5722;
        }
      }
    }
  }
  
  .wechat-tip {
    background: #fff;
    border-radius: 24rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
    display: flex;
    align-items: center;
    
    .method-icon {
      width: 48rpx;
      height: 48rpx;
      margin-right: 20rpx;
      
      &.wechat {
        background: url('../../static/images/wechat.svg') no-repeat center/contain;
      }
    }
    
    .method-text {
      font-size: 28rpx;
      color: #333;
      font-weight: 500;
    }
  }
  
  .bottom-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    padding: 20rpx 30rpx;
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.04);
    
    .total-amount {
      font-size: 28rpx;
      color: #666;
      
      .amount {
        font-size: 36rpx;
        font-weight: 600;
        color: #FF5722;
        margin-left: 10rpx;
      }
    }
    
    .pay-btn {
      background: #1976D2;
      color: #fff;
      font-size: 32rpx;
      font-weight: 600;
      padding: 20rpx 60rpx;
      border-radius: 100rpx;
      border: none;
      
      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style>