
<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="用户名" prop="username">
        <ElInput v-model="formData.username" />
      </ElFormItem>
      <ElFormItem label="密码" prop="password" v-if="!isEdit">
        <ElInput v-model="formData.password" />
      </ElFormItem>
      <ElFormItem label="手机号" prop="phone">
        <ElInput v-model="formData.phone" />
      </ElFormItem>
      <ElFormItem label="性别" prop="sex">
        <ElSelect v-model="formData.sex">
          <ElOption label="男" value="0" />
          <ElOption label="女" value="1" />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="角色" prop="role">
        <ElSelect v-model="formData.role_name">
          <ElOption v-for="role in roleList" :key="role.id" :value="role.name" :label="role.name" />
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { UserService } from '@/api/usersApi'

  interface Props {
    visible: boolean
    type: string
    userData?: any
    roleList: Api.Common.SelectInfo[]
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

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

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    id: 0,
    username: '',
    password: '',
    phone: '',
    sex: '男',
    role_name: ''
  })

  // 表单验证规则
  const rules: FormRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
    role_name: [{ required: true, message: '请选择角色', trigger: 'blur' }]
  }

  const isEdit = ref(false)
  // 初始化表单数据
  const initFormData = () => {
    isEdit.value = props.type === 'edit' && props.userData
    const row = props.userData
    Object.assign(formData, {
      username: isEdit.value ? row.username || '' : '',
      phone: isEdit.value ? row.phone || '' : '',
      sex: isEdit.value ? (row.sex ? '女' : '男') : '男',
      role_name: isEdit.value ? row.role_name || '' : ''
    })
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate((valid) => {
      if (valid) {
        let userData: Api.User.UserInfo = {
          id: props.userData.id,
          username: formData.username,
          password: formData.password,
          phone: formData.phone,
          sex: parseInt(formData.sex),
          role_id: props.roleList.find((item) => item.name === formData.role_name)?.id || 0
        }
        UserService.editUser(userData)
        dialogVisible.value = false
        emit('submit')
      }
    })
  }
</script>
