<template>
  <view class="recharge-container">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-content">
        <view class="nav-left" @click="goBack">
          <text class="nav-icon">‹</text>
        </view>
        <view class="nav-title">会员充值</view>
        <view class="nav-right"></view>
      </view>
    </view>

    <!-- 用户余额显示 -->
    <view class="balance-section">
      <view class="balance-card">
        <view class="balance-label">当前余额</view>
        <view class="balance-amount">¥{{ userBalance }}</view>
        <view class="balance-tip">充值后余额可用于AI对话和语音服务</view>
      </view>
    </view>

    <!-- 充值金额选择 -->
    <view class="amount-section">
      <view class="section-title">选择充值金额</view>
      <view class="amount-grid">
        <view 
          v-for="(amount, index) in rechargeAmounts" 
          :key="index"
          class="amount-item"
          :class="{ active: selectedAmount === amount.value }"
          @click="selectAmount(amount.value)"
        >
          <view class="amount-value">¥{{ amount.value }}</view>
        </view>
      </view>
      
      <!-- 自定义金额输入 -->
      <view class="custom-amount">
        <view class="custom-label">自定义金额</view>
        <view class="custom-input-wrapper">
          <text class="currency-symbol">¥</text>
          <input 
            class="custom-input"
            type="digit"
            placeholder="请输入金额"
            v-model="customAmount"
            @input="onCustomAmountInput"
            @focus="onCustomAmountFocus"
          />
        </view>
        <view class="amount-tips">
          <text class="tip-item">最低充值：¥1</text>
          <text class="tip-item">最高充值：¥1000</text>
        </view>
      </view>
    </view>

    <!-- 支付方式选择 -->
    <view class="payment-section">
      <view class="section-title">支付方式</view>
      <view class="payment-methods">
        <view 
          class="payment-item"
          :class="{ active: selectedPayment === 'wechat' }"
          @click="selectPayment('wechat')"
        >
          <view class="payment-icon wechat-icon">💳</view>
          <view class="payment-info">
            <view class="payment-name">微信支付</view>
            <view class="payment-desc">安全便捷，支持免密支付</view>
          </view>
          <view class="payment-radio">
            <view class="radio-dot" v-if="selectedPayment === 'wechat'"></view>
          </view>
        </view>
      </view>
    </view>

    <!-- 充值说明 -->
    <view class="notice-section">
      <view class="notice-title">充值说明</view>
      <view class="notice-content">
        <view class="notice-item">• 充值金额实时到账，可用于AI对话服务</view>
        <view class="notice-item">• 余额永久有效，无使用期限</view>
        <view class="notice-item">• 充值成功后不支持退款，请谨慎操作</view>
        <view class="notice-item">• 如有问题请联系客服</view>
      </view>
    </view>

    <!-- 底部充值按钮 -->
    <view class="bottom-section">
      <view class="recharge-summary">
        <view class="summary-item">
          <text class="summary-label">充值金额：</text>
          <text class="summary-value">¥{{ finalAmount }}</text>
        </view>
        <view class="summary-item total">
          <text class="summary-label">到账金额：</text>
          <text class="summary-value">¥{{ finalAmount }}</text>
        </view>
      </view>
      
      <button 
        class="recharge-btn"
        :class="{ disabled: !canRecharge }"
        :disabled="!canRecharge"
        @click="handleRecharge"
      >
        <text class="btn-text">立即充值 ¥{{ finalAmount }}</text>
      </button>
    </view>

    <!-- 加载遮罩 -->
    <view class="loading-mask" v-if="isLoading">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <view class="loading-text">{{ loadingText }}</view>
      </view>
    </view>
  </view>
</template>

<script>
import { rechargeAPI } from '@/utils/api.js'

export default {
  name: 'RechargePage',
  data() {
    return {
      userBalance: 0.00, // 用户当前余额
      selectedAmount: 0, // 选中的充值金额
      customAmount: '', // 自定义金额
      selectedPayment: 'wechat', // 选中的支付方式
      isLoading: false, // 是否正在加载
      loadingText: '处理中...', // 加载文本
      
      // 充值金额选项
      rechargeAmounts: [
        { value: 10, bonus: 0 },
        { value: 20, bonus: 0 },
        { value: 50, bonus: 0 },
        { value: 100, bonus: 0 },
        { value: 200, bonus: 0 },
        { value: 500, bonus: 0 }
      ]
    }
  },
  
  computed: {
    // 最终充值金额
    finalAmount() {
      if (this.customAmount && parseFloat(this.customAmount) > 0) {
        return parseFloat(this.customAmount)
      }
      return this.selectedAmount
    },
    
    // 赠送金额（已取消赠送服务）
    bonusAmount() {
      return 0 // 所有充值金额都不赠送
    },
    
    // 是否可以充值
    canRecharge() {
      return this.finalAmount >= 1 && this.finalAmount <= 1000 && this.selectedPayment
    }
  },
  
  onLoad() {
    this.loadUserBalance()
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载用户余额
    async loadUserBalance() {
      try {
        const result = await rechargeAPI.getUserBalance()
        if (result.success) {
          this.userBalance = result.data.balance || 0
        }
      } catch (error) {
        console.error('获取用户余额失败:', error)
        uni.showToast({
          title: '获取余额失败',
          icon: 'none'
        })
      }
    },
    
    // 选择充值金额
    selectAmount(amount) {
      this.selectedAmount = amount
      this.customAmount = '' // 清空自定义金额
    },
    
    // 自定义金额输入
    onCustomAmountInput(e) {
      const value = e.detail.value
      // 只允许数字和小数点
      if (!/^\d*\.?\d*$/.test(value)) {
        this.customAmount = this.customAmount.replace(/[^\d.]/g, '')
        return
      }
      
      // 限制小数点后最多两位
      if (value.includes('.')) {
        const parts = value.split('.')
        if (parts[1] && parts[1].length > 2) {
          this.customAmount = parts[0] + '.' + parts[1].substring(0, 2)
          return
        }
      }
      
      this.customAmount = value
      this.selectedAmount = 0 // 清空预设金额选择
    },
    
    // 自定义金额获得焦点
    onCustomAmountFocus() {
      this.selectedAmount = 0
    },
    
    // 选择支付方式
    selectPayment(payment) {
      this.selectedPayment = payment
    },
    
    // 处理充值
    async handleRecharge() {
      if (!this.canRecharge) {
        uni.showToast({
          title: '请选择充值金额',
          icon: 'none'
        })
        return
      }
      
      // 检查金额范围
      if (this.finalAmount < 1) {
        uni.showToast({
          title: '充值金额不能少于1元',
          icon: 'none'
        })
        return
      }
      
      if (this.finalAmount > 1000) {
        uni.showToast({
          title: '充值金额不能超过1000元',
          icon: 'none'
        })
        return
      }
      
      this.isLoading = true
      this.loadingText = '创建订单中...'
      
      try {
        // 1. 创建充值订单
        const orderResult = await rechargeAPI.createRechargeOrder({
          amount: this.finalAmount,
          paymentMethod: this.selectedPayment
        })
        
        if (!orderResult.success) {
          throw new Error(orderResult.error?.message || '创建订单失败')
        }
        
        this.loadingText = '调起支付中...'
        
        // 2. 调起微信支付
        const paymentResult = await this.requestPayment(orderResult.data.paymentParams)
        
        if (paymentResult.success) {
          // 3. 支付成功，更新余额
          this.loadingText = '更新余额中...'
          await this.loadUserBalance()
          
          uni.showToast({
            title: '充值成功',
            icon: 'success'
          })
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(paymentResult.error?.message || '支付失败')
        }
        
      } catch (error) {
        console.error('充值失败:', error)
        uni.showToast({
          title: error.message || '充值失败，请重试',
          icon: 'none'
        })
      } finally {
        this.isLoading = false
      }
    },
    
    // 调起微信支付
    requestPayment(paymentParams) {
      return new Promise((resolve) => {
        uni.requestPayment({
          ...paymentParams,
          success: (res) => {
            console.log('支付成功:', res)
            resolve({ success: true, data: res })
          },
          fail: (err) => {
            console.error('支付失败:', err)
            if (err.errMsg && err.errMsg.includes('cancel')) {
              resolve({ success: false, error: { message: '用户取消支付' } })
            } else {
              resolve({ success: false, error: err })
            }
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.recharge-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx;
}

// 导航栏
.nav-bar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-top: var(--status-bar-height);
  
  .nav-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;
    
    .nav-left {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .nav-icon {
        font-size: 40rpx;
        color: #fff;
        font-weight: bold;
      }
    }
    
    .nav-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .nav-right {
      width: 60rpx;
    }
  }
}

// 余额卡片
.balance-section {
  padding: 30rpx;
  
  .balance-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20rpx;
    padding: 40rpx;
    text-align: center;
    color: #fff;
    
    .balance-label {
      font-size: 28rpx;
      opacity: 0.9;
      margin-bottom: 10rpx;
    }
    
    .balance-amount {
      font-size: 60rpx;
      font-weight: bold;
      margin-bottom: 15rpx;
    }
    
    .balance-tip {
      font-size: 24rpx;
      opacity: 0.8;
    }
  }
}

// 金额选择
.amount-section {
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .amount-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20rpx;
    margin-bottom: 40rpx;
    
    .amount-item {
      background: #fff;
      border: 2rpx solid #e5e5e5;
      border-radius: 16rpx;
      padding: 30rpx 20rpx;
      text-align: center;
      transition: all 0.3s ease;
      
      &.active {
        border-color: #667eea;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #fff;
        
        .amount-bonus {
          color: rgba(255, 255, 255, 0.9);
        }
      }
      
      .amount-value {
        font-size: 32rpx;
        font-weight: 600;
        margin-bottom: 8rpx;
      }
      
      .amount-bonus {
        font-size: 24rpx;
        color: #ff6b6b;
      }
    }
  }
  
  .custom-amount {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    
    .custom-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .custom-input-wrapper {
      display: flex;
      align-items: center;
      border: 2rpx solid #e5e5e5;
      border-radius: 12rpx;
      padding: 0 20rpx;
      margin-bottom: 20rpx;
      
      .currency-symbol {
        font-size: 32rpx;
        color: #666;
        margin-right: 10rpx;
      }
      
      .custom-input {
        flex: 1;
        height: 80rpx;
        font-size: 32rpx;
        color: #333;
      }
    }
    
    .amount-tips {
      display: flex;
      justify-content: space-between;
      
      .tip-item {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

// 支付方式
.payment-section {
  padding: 0 30rpx 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 30rpx;
  }
  
  .payment-methods {
    .payment-item {
      background: #fff;
      border-radius: 16rpx;
      padding: 30rpx;
      display: flex;
      align-items: center;
      border: 2rpx solid #e5e5e5;
      transition: all 0.3s ease;
      
      &.active {
        border-color: #667eea;
        background: #f8f9ff;
      }
      
      .payment-icon {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 40rpx;
        margin-right: 20rpx;
        
        &.wechat-icon {
          background: #07c160;
          color: #fff;
        }
      }
      
      .payment-info {
        flex: 1;
        
        .payment-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
          margin-bottom: 8rpx;
        }
        
        .payment-desc {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .payment-radio {
        width: 40rpx;
        height: 40rpx;
        border: 2rpx solid #e5e5e5;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        
        .radio-dot {
          width: 20rpx;
          height: 20rpx;
          background: #667eea;
          border-radius: 50%;
        }
      }
    }
  }
}

// 充值说明
.notice-section {
  padding: 0 30rpx 30rpx;
  
  .notice-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .notice-content {
    background: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    
    .notice-item {
      font-size: 26rpx;
      color: #666;
      line-height: 1.6;
      margin-bottom: 15rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

// 底部区域
.bottom-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 30rpx;
  border-top: 1rpx solid #e5e5e5;
  
  .recharge-summary {
    margin-bottom: 30rpx;
    
    .summary-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15rpx;
      
      &.total {
        border-top: 1rpx solid #e5e5e5;
        padding-top: 15rpx;
        margin-top: 15rpx;
        
        .summary-label,
        .summary-value {
          font-size: 32rpx;
          font-weight: 600;
          color: #333;
        }
      }
      
      .summary-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .summary-value {
        font-size: 28rpx;
        color: #333;
        font-weight: 600;
        
        &.bonus {
          color: #ff6b6b;
        }
      }
    }
  }
  
  .recharge-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 44rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    
    &.disabled {
      background: #ccc;
    }
    
    .btn-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #fff;
    }
  }
}

// 加载遮罩
.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loading-content {
    background: #fff;
    border-radius: 20rpx;
    padding: 60rpx 40rpx;
    text-align: center;
    
    .loading-spinner {
      width: 60rpx;
      height: 60rpx;
      border: 4rpx solid #e5e5e5;
      border-top: 4rpx solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin: 0 auto 20rpx;
    }
    
    .loading-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
