<template>
  <div class="recharge-container">
    <el-card class="recharge-card">
      <h2 class="recharge-title">账户充值</h2>
      
      <div class="balance-display">
        <el-text type="primary" size="large">
          当前余额: <span class="balance-amount">￥{{ user.balance || 0 }}</span>
        </el-text>
      </div>
      
      <el-form 
        ref="rechargeForm" 
        :model="form" 
        :rules="rules" 
        label-width="100px">
        <el-form-item label="充值金额" prop="money">
          <el-input-number 
            v-model="form.money" 
            :min="10" 
            :step="10" 
            :precision="2" 
            controls-position="right" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRecharge">立即充值</el-button>
        </el-form-item>
      </el-form>
      
      <div class="recharge-options">
        <h3>快捷充值</h3>
        <div class="options-grid">
          <el-button 
            v-for="amount in [10, 50, 100,150,200,300,400,500]" 
            :key="amount" 
            @click="quickRecharge(amount)">
            ￥{{ amount }}
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

const store = useStore()
const user = computed(() => store.state.user || {})

const form = ref({
  money: 10
})

const rules = ref({
  money: [
    { required: true, message: '请输入充值金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '充值金额必须大于0', trigger: 'blur' }
  ]
})

const rechargeForm = ref(null)

const submitRecharge = async () => {
  try {
    await rechargeForm.value.validate()
    
    await store.dispatch('recharge', { money: form.value.money })
    ElMessage.success(`成功充值￥${form.value.money}元`)
    
    // 更新用户信息
    await store.dispatch('fetchUser')
  } catch (error) {
    console.error('充值失败:', error)
    ElMessage.error(error.message || '充值失败')
  }
}

const quickRecharge = (amount) => {
  form.value.money = amount
  submitRecharge()
}
</script>

<style scoped>
.recharge-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.recharge-card {
  padding: 30px;
}

.recharge-title {
  text-align: center;
  margin-bottom: 30px;
}

.balance-display {
  text-align: center;
  margin-bottom: 30px;
  font-size: 18px;
}

.balance-amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.recharge-options {
  margin-top: 40px;
}

.recharge-options h3 {
  text-align: center;
  margin-bottom: 20px;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 15px;
}
</style>