<template>
  <ElDialog v-model="visible" title="设置限速" width="500px" @close="handleClose">
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <ElFormItem label="设备信息">
        <span style="font-weight: bold; color: #409eff">{{ deviceInfo }}</span>
      </ElFormItem>
      <ElFormItem label="下行速率" prop="download_speed">
        <ElInputNumber
          v-model="formData.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="formData.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="visible = false">取消</ElButton>
      <ElButton type="primary" @click="handleConfirm" :loading="confirmLoading">
        确认设置
      </ElButton>
    </template>
  </ElDialog>
</template>

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

  interface Props {
    modelValue: boolean
    deviceInfo: string
    loading?: boolean
  }

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

  const props = withDefaults(defineProps<Props>(), {
    loading: false
  })

  const emit = defineEmits<Emits>()

  const visible = ref(props.modelValue)
  const confirmLoading = ref(props.loading)
  const formRef = ref<FormInstance>()

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

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

  watch(
    () => props.modelValue,
    (val) => {
      visible.value = val
      if (val) {
        // 重置表单
        formData.download_speed = 1024
        formData.upload_speed = 512
      }
    }
  )

  watch(visible, (val) => {
    emit('update:modelValue', val)
  })

  watch(
    () => props.loading,
    (val) => {
      confirmLoading.value = val
    }
  )

  const handleClose = () => {
    formRef.value?.resetFields()
  }

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

    await formRef.value.validate((valid) => {
      if (valid) {
        emit('confirm', {
          download_speed: formData.download_speed,
          upload_speed: formData.upload_speed
        })
      }
    })
  }
</script>
