<template>
  <el-dialog v-model="visible" title="设备注册" width="500px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="所属楼宇" prop="building">
        <el-select v-model="form.building" placeholder="请选择楼宇" style="width: 100%">
          <el-option label="北区1号楼" value="1" />
          <el-option label="南区A栋" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间号" prop="room">
        <el-input v-model="form.room" placeholder="例如: 101" />
      </el-form-item>
      <el-form-item label="设备类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio label="single">单相电表</el-radio>
          <el-radio label="three">三相电表</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceId">
        <el-input v-model="form.deviceId" placeholder="请输入设备出厂ID" />
      </el-form-item>
      <el-form-item label="通讯协议" prop="protocol">
        <el-select v-model="form.protocol" style="width: 100%">
          <el-option label="Modbus-RTU" value="modbus" />
          <el-option label="DL/T 645-2007" value="dl645" />
          <el-option label="MQTT" value="mqtt" />
        </el-select>
      </el-form-item>
      <el-form-item label="初始电量" prop="initBalance">
        <el-input-number v-model="form.initBalance" :min="0" :precision="2" />
        <span class="ml-10">kWh</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleConfirm" :loading="loading">确认注册</el-button>
    </template>
  </el-dialog>
</template>

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

const emit = defineEmits(['success'])

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)

const form = reactive({
  building: '',
  room: '',
  type: 'single',
  deviceId: '',
  protocol: 'modbus',
  initBalance: 0
})

const rules = {
  building: [{ required: true, message: '请选择所属楼宇', trigger: 'change' }],
  room: [{ required: true, message: '请输入房间号', trigger: 'blur' }],
  deviceId: [{ required: true, message: '请输入设备编号', trigger: 'blur' }]
}

const open = () => {
  // Reset form
  form.building = ''
  form.room = ''
  form.type = 'single'
  form.deviceId = ''
  form.protocol = 'modbus'
  form.initBalance = 0
  
  visible.value = true
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      // Simulate API call
      setTimeout(() => {
        loading.value = false
        visible.value = false
        ElMessage.success('设备注册成功')
        emit('success', { ...form })
      }, 1000)
    }
  })
}

defineExpose({
  open
})
</script>

<style scoped>
.ml-10 { margin-left: 10px; }
</style>
