<script setup lang="ts">
import { api } from '@/utils/request'
import type { UserRecord } from '@/stores/user-manage'
import type { Rule } from 'ant-design-vue/es/form'

const props = defineProps<{
  open: boolean
  mode: 'create' | 'edit'
  userData: UserRecord | null
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  success: []
}>()

interface RoleOption {
  id: number
  name: string
}

const formRef = ref()
const submitting = ref(false)
const roles = ref<RoleOption[]>([])
const formState = reactive({
  username: '',
  password: '',
  email: '',
  status: 1 as number,
  role_id: undefined as number | undefined,
})

const rules = computed<Record<string, Rule[]>>(() => {
  const base: Record<string, Rule[]> = {
    username: [
      { required: true, message: '请输入用户名' },
      { min: 3, max: 20, message: '用户名长度为 3-20 个字符' },
    ],
    email: [
      { required: true, message: '请输入邮箱' },
      { type: 'email', message: '请输入有效的邮箱地址' },
    ],
    status: [{ required: true, message: '请选择状态' }],
  }
  if (props.mode === 'create') {
    base.password = [
      { required: true, message: '请输入密码' },
      { min: 6, max: 32, message: '密码长度为 6-32 个字符' },
    ]
  }
  return base
})

const title = computed(() => (props.mode === 'create' ? '新建用户' : '编辑用户'))

async function fetchRoles() {
  try {
    const data = await api.get<RoleOption[]>('/api/v1/roles')
    roles.value = data
  } catch {
    roles.value = []
    message.warning('获取角色列表失败，角色选择不可用')
  }
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      fetchRoles()
      if (props.mode === 'edit' && props.userData) {
        formState.username = props.userData.username
        formState.email = props.userData.email
        formState.status = props.userData.status
        formState.role_id = props.userData.role_id
        formState.password = ''
      } else {
        formState.username = ''
        formState.password = ''
        formState.email = ''
        formState.status = 1
        formState.role_id = undefined
      }
      // 清除上一次的校验状态
      nextTick(() => formRef.value?.clearValidate())
    }
  },
)

async function handleSubmit() {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    let userId: number
    if (props.mode === 'create') {
      const created = await api.post<{ id: number }>('/api/v1/users', {
        username: formState.username,
        password: formState.password,
        email: formState.email,
        status: formState.status,
      })
      userId = created.id
    } else {
      await api.put(`/api/v1/users/${props.userData!.id}`, {
        username: formState.username,
        email: formState.email,
        status: formState.status,
      })
      userId = props.userData!.id
    }

    // 角色分配（独立 try-catch，用户信息保存不受影响）
    const needsRoleUpdate = props.mode === 'create'
      ? !!formState.role_id
      : formState.role_id && formState.role_id !== props.userData!.role_id
    if (needsRoleUpdate) {
      try {
        await api.put(`/api/v1/users/${userId}/role`, { role_id: formState.role_id })
      } catch {
        message.warning('用户已保存，但角色分配失败，请稍后在用户列表中重试')
      }
    }

    message.success('操作成功')
    emit('update:open', false)
    emit('success')
  } catch (err: unknown) {
    const msg = err instanceof Error ? err.message : '操作失败'
    message.error(msg)
  } finally {
    submitting.value = false
  }
}

function handleCancel() {
  emit('update:open', false)
}
</script>

<template>
  <a-modal
    :open="open"
    :title="title"
    :confirm-loading="submitting"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formState" :rules="rules" layout="vertical">
      <a-form-item label="用户名" name="username">
        <a-input v-model:value="formState.username" placeholder="请输入用户名" />
      </a-form-item>
      <a-form-item v-if="mode === 'create'" label="密码" name="password">
        <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item label="邮箱" name="email">
        <a-input v-model:value="formState.email" placeholder="请输入邮箱" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-select v-model:value="formState.status">
          <a-select-option :value="1">启用</a-select-option>
          <a-select-option :value="0">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="角色" name="role_id">
        <a-select v-model:value="formState.role_id" placeholder="请选择角色">
          <a-select-option v-for="role in roles" :key="role.id" :value="role.id">
            {{ role.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
