<template>
  <ElDialog v-model="visible" title="设置WiFi" width="500px" :append-to-body="true">
    <ElForm ref="formRef" :model="form" :rules="rules" label-width="120px">
      <ElFormItem label="WiFi状态" prop="enabled">
        <ElRadioGroup v-model="form.enabled">
          <ElRadio :value="1">启用</ElRadio>
          <ElRadio :value="0">禁用</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <ElFormItem label="WiFi名称" prop="ssid">
        <ElInput
          v-model="form.ssid"
          placeholder="请输入WiFi名称（1-32个字符）"
          maxlength="32"
          show-word-limit
          clearable
        />
      </ElFormItem>
      <ElFormItem label="WiFi密码" prop="password">
        <ElInput
          v-model="form.password"
          type="password"
          placeholder="请输入WiFi密码（8-63个字符）"
          maxlength="63"
          show-word-limit
          show-password
          clearable
        />
      </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,
    ElInput,
    ElRadioGroup,
    ElRadio,
    ElButton
  } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'

  interface Props {
    modelValue: boolean
    cardNo?: string // 流量卡号（ICCID）
  }

  interface Emits {
    (e: 'update:modelValue', value: boolean): void
    (e: 'confirm', data: { card_no: string; enabled: number; ssid: string; password: string }): void
  }

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

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

  const form = reactive({
    enabled: 1,
    ssid: '',
    password: ''
  })

  const rules: FormRules = {
    ssid: [
      { required: true, message: '请输入WiFi名称', trigger: 'blur' },
      { min: 1, max: 32, message: 'WiFi名称长度为1-32个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入WiFi密码', trigger: 'blur' },
      { min: 8, max: 63, message: 'WiFi密码长度为8-63个字符', trigger: 'blur' }
    ]
  }

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

  // 监听对话框打开，重置表单
  watch(visible, (newVal) => {
    if (newVal) {
      form.enabled = 1
      form.ssid = ''
      form.password = ''
    }
  })

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

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

    try {
      await formRef.value.validate()
      emit('confirm', {
        card_no: props.cardNo || '',
        enabled: form.enabled,
        ssid: form.ssid,
        password: form.password
      })
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  }
</script>

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