<template>
  <ElDialog v-model="visible" title="设置限速" width="500px">
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
      <ElFormItem label="下行速率" prop="download_speed">
        <ElInputNumber
          v-model="form.download_speed"
          :min="1"
          :step="128"
          controls-position="right"
          style="width: 100%"
        />
        <div style="margin-top: 4px; font-size: 12px; color: #909399">单位: KB/s</div>
      </ElFormItem>
      <ElFormItem label="上行速率" prop="upload_speed">
        <ElInputNumber
          v-model="form.upload_speed"
          :min="1"
          :step="128"
          controls-position="right"
          style="width: 100%"
        />
        <div style="margin-top: 4px; font-size: 12px; color: #909399">单位: KB/s</div>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="handleCancel">取消</ElButton>
      <ElButton type="primary" @click="handleConfirm" :loading="loading"> 确认设置 </ElButton>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import { ElDialog, ElForm, ElFormItem, ElInputNumber, ElButton } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    modelValue: boolean
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'confirm', data: { download_speed: number; upload_speed: number }): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  const formRef = ref<FormInstance>()
  const loading = ref(false)

  const form = reactive({
    download_speed: 1024,
    upload_speed: 512
  })

  const rules: FormRules = {
    download_speed: [{ required: true, message: '请输入下行速率', trigger: 'blur' }],
    upload_speed: [{ required: true, message: '请输入上行速率', trigger: 'blur' }]
  }

  const visible = computed({
    get: () => props.modelValue,
    set: (value) => emit('update:modelValue', value)
  })

  // 监听对话框打开，重置表单
  watch(visible, (newVal) => {
    if (newVal) {
      form.download_speed = 1024
      form.upload_speed = 512
    }
  })

  const handleCancel = () => {
    visible.value = false
  }

  const handleConfirm = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      emit('confirm', {
        download_speed: form.download_speed,
        upload_speed: form.upload_speed
      })
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }
</script>

<style lang="scss" scoped></style>
