<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { userService } from '@/service/user'

/**
 * 用户类型选项
 */
const userTypeOptions = [
  { label: '普通用户', value: 1 },
  { label: '管理员', value: 2 },
  { label: '系统用户', value: 3 },
]

/**
 * 状态选项
 */
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
]

const props = defineProps<{
  visible: boolean
  /** 编辑时传入的用户数据，新增时为 null */
  row?: any
}>()

const emit = defineEmits<{
  (e: 'update:visible', val: boolean): void
  (e: 'success'): void
}>()

// 表单数据
const form = reactive({
  id: undefined as number | undefined,
  username: '',
  password: '',
  userType: 1,
  status: 1,
})

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 是否编辑模式
const isEdit = ref(false)

// 监听 visible 变化
watch(() => props.visible, (val) => {
  if (val) {
    if (props.row) {
      // 编辑模式
      isEdit.value = true
      form.id = props.row.id
      form.username = props.row.username
      form.password = '' // 编辑时不显示密码
      form.userType = props.row.userType ?? 1
      form.status = props.row.status ?? 1
    } else {
      // 新增模式
      isEdit.value = false
      form.id = undefined
      form.username = ''
      form.password = ''
      form.userType = 1
      form.status = 1
    }
  }
})

/**
 * 表单校验规则
 */
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' },
  ],
  password: [
    { required: !isEdit.value, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur' },
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'change' },
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' },
  ],
}

/**
 * 提交表单
 */
async function handleSubmit() {
  const valid = await formRef.value?.validate().catch(() => false)
  if (!valid) return

  loading.value = true
  try {
    if (isEdit.value) {
      // 编辑
      await userService.update({
        id: form.id!,
        username: form.username,
        userType: form.userType,
        status: form.status,
      })
      ElMessage.success('修改成功')
    } else {
      // 新增
      await userService.add({
        username: form.username,
        password: form.password,
        userType: form.userType,
        status: form.status,
      })
      ElMessage.success('新增成功')
    }
    emit('success')
    emit('update:visible', false)
  } catch {
    // 错误已由请求拦截器统一提示
  } finally {
    loading.value = false
  }
}

/**
 * 关闭弹窗
 */
function handleClose() {
  emit('update:visible', false)
}
</script>

<template>
  <el-dialog
    class="rui-dialog"
    :title="isEdit ? '编辑用户' : '新增用户'"
    :model-value="visible"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="form.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input v-model.trim="form.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="form.userType" placeholder="请选择用户类型" style="width: 100%">
          <el-option
            v-for="item in userTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio-button
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">
        取消
      </el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
