<template>
  <el-dialog v-model="visible" title="电费充值" width="400px">
    <el-form label-width="80px">
      <el-form-item label="房间">
        <strong>{{ currentMeter?.roomName }}</strong>
      </el-form-item>
      <el-form-item label="当前余额">
        <span class="text-primary font-bold">{{ currentMeter?.balance }} kWh</span>
      </el-form-item>
      <el-form-item label="充值金额">
        <el-input-number v-model="rechargeAmount" :min="1" :step="10" />
        <span class="ml-10">元</span>
      </el-form-item>
      <el-form-item label="折合电量">
        <span>{{ (rechargeAmount / 0.6).toFixed(2) }} kWh</span>
        <span class="text-gray text-xs ml-10">(单价: 0.6元/kWh)</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="confirmRecharge" :loading="loading">确认充值</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const loading = ref(false)
const currentMeter = ref(null)
const rechargeAmount = ref(50)

const open = (meter) => {
  currentMeter.value = meter
  rechargeAmount.value = 50
  visible.value = true
}

const confirmRecharge = () => {
  loading.value = true
  setTimeout(() => {
    const kwh = parseFloat((rechargeAmount.value / 0.6).toFixed(2))
    if (currentMeter.value) {
      currentMeter.value.balance += kwh
    }
    loading.value = false
    visible.value = false
    ElMessage.success(`充值成功！增加电量 ${kwh} kWh`)
  }, 1000)
}

defineExpose({
  open
})
</script>

<style scoped>
.ml-10 { margin-left: 10px; }
.text-primary { color: var(--el-color-primary); }
.font-bold { font-weight: bold; }
.text-gray { color: #909399; }
.text-xs { font-size: 12px; }
</style>
