<template>
	<a-modal :title="titleMap[mode]" :open="visible" :width="500" :destroy-on-close="true" :mask-closable="false" @cancel="handleCancel">
		<a-form :model="form" :rules="rules" :disabled="mode === 'show'" ref="dialogForm" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
			<a-form-item label="头像" name="avatar">
				<sc-upload v-model="form.avatar" :cropper="true" :aspectRatio="1" title="上传头像"></sc-upload>
			</a-form-item>
			<a-form-item label="用户名" name="username">
				<a-input v-model:value="form.username" placeholder="请输入用户名" allow-clear :disabled="mode === 'edit'" />
			</a-form-item>
			<a-form-item label="真实姓名" name="real_name">
				<a-input v-model:value="form.real_name" placeholder="请输入真实姓名" allow-clear />
			</a-form-item>
			<a-form-item label="邮箱" name="email">
				<a-input v-model:value="form.email" placeholder="请输入邮箱" allow-clear />
			</a-form-item>
			<a-form-item label="手机号" name="phone">
				<a-input v-model:value="form.phone" placeholder="请输入手机号" allow-clear />
			</a-form-item>
			<template v-if="mode === 'add'">
				<a-form-item label="登录密码" name="password">
					<a-input-password v-model:value="form.password" placeholder="请输入登录密码" allow-clear />
				</a-form-item>
				<a-form-item label="确认密码" name="password2">
					<a-input-password v-model:value="form.password2" placeholder="请再次输入密码" allow-clear />
				</a-form-item>
			</template>
			<a-form-item label="所属部门" name="department_id">
				<a-tree-select v-model:value="form.department_id" :tree-data="department" :field-names="departmentFieldNames" :tree-default-expand-all="false" show-icon placeholder="请选择部门" allow-clear tree-node-filter-prop="name" />
			</a-form-item>
			<a-form-item label="所属角色" name="role_ids">
				<a-select v-model:value="form.role_ids" mode="multiple" placeholder="请选择角色" allow-clear style="width: 100%">
					<a-select-option v-for="role in rolesList" :key="role.id" :value="role.id">
						{{ role.name }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="性别" name="gender">
				<sc-select v-model:value="form.gender" source-type="dictionary" dictionary-code="gender" placeholder="请选择性别" allow-clear />
			</a-form-item>
			<a-form-item label="状态" name="status">
				<sc-select v-model:value="form.status" source-type="dictionary" dictionary-code="user_status" placeholder="请选择状态" allow-clear />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button @click="handleCancel">取 消</a-button>
			<a-button v-if="mode !== 'show'" type="primary" :loading="isSaveing" @click="submit">保 存</a-button>
		</template>
	</a-modal>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { message } from 'ant-design-vue'
import scUpload from '@/components/scUpload/index.vue'
import scSelect from '@/components/scSelect/index.vue'
import authApi from '@/api/auth'

const emit = defineEmits(['success', 'closed'])

const mode = ref('add')
const titleMap = {
	add: '新增用户',
	edit: '编辑用户',
	show: '查看用户',
}
const visible = ref(false)
const isSaveing = ref(false)

// 表单数据
const form = reactive({
	id: '',
	username: '',
	avatar: '',
	real_name: '',
	email: '',
	phone: '',
	department_id: null,
	role_ids: [],
	gender: null,
	status: null,
})

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

// 验证规则
const rules = {
	username: [
		{ required: true, message: '请输入用户名', trigger: 'blur' },
		{
			min: 3,
			max: 50,
			message: '用户名长度在 3 到 50 个字符',
			trigger: 'blur',
		},
	],
	real_name: [
		{ required: true, message: '请输入真实姓名', trigger: 'blur' },
		{
			min: 2,
			max: 50,
			message: '真实姓名长度在 2 到 50 个字符',
			trigger: 'blur',
		},
	],
	email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
	phone: [
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入正确的手机号',
			trigger: 'blur',
		},
	],
	password: [
		{ required: true, message: '请输入登录密码', trigger: 'blur' },
		{
			min: 6,
			max: 20,
			message: '密码长度在 6 到 20 个字符',
			trigger: 'blur',
		},
		{
			validator: (rule, value) => {
				if (form.password2 !== '') {
					dialogForm.value?.validateFields('password2')
				}
				return Promise.resolve()
			},
			trigger: 'change',
		},
	],
	password2: [
		{ required: true, message: '请再次输入密码', trigger: 'blur' },
		{
			validator: (rule, value) => {
				if (value !== form.password) {
					return Promise.reject(new Error('两次输入密码不一致!'))
				}
				return Promise.resolve()
			},
			trigger: 'blur',
		},
	],
}

// 部门数据
const department = ref([])
const departmentFieldNames = {
	value: 'id',
	label: 'name',
	children: 'children',
}

// 角色列表
const rolesList = ref([])

// 显示对话框
const open = (openMode = 'add') => {
	mode.value = openMode
	visible.value = true
	return {
		setData,
		open,
		close,
	}
}

// 关闭对话框
const close = () => {
	visible.value = false
}

// 处理取消
const handleCancel = () => {
	emit('closed')
	visible.value = false
}

// 加载部门树数据
const loadDepartment = async () => {
	try {
		const res = await authApi.department.tree.get()
		if (res.code === 200) {
			department.value = res.data || []
		}
	} catch (error) {
		console.error('加载部门树失败:', error)
	}
}

// 加载角色列表
const loadRoles = async () => {
	try {
		const res = await authApi.role.all.get()
		if (res.code === 200) {
			rolesList.value = res.data || []
		}
	} catch (error) {
		console.error('加载角色列表失败:', error)
	}
}

// 表单提交方法
const submit = async () => {
	try {
		await dialogForm.value.validate()
		isSaveing.value = true

		const submitData = {
			username: form.username,
			avatar: form.avatar,
			real_name: form.real_name,
			email: form.email,
			phone: form.phone,
			department_id: form.department_id,
			role_ids: form.role_ids,
			gender: form.gender,
			status: form.status,
		}

		if (mode.value === 'add') {
			submitData.password = form.password
		}

		let res = {}
		if (mode.value === 'add') {
			res = await authApi.user.add.post(submitData)
		} else {
			res = await authApi.user.edit.put(form.id, submitData)
		}

		isSaveing.value = false
		if (res.code === 200) {
			emit('success', form, mode.value)
			visible.value = false
			message.success('操作成功')
		} else {
			message.error(res.message || '操作失败')
		}
	} catch (error) {
		console.error('表单验证失败', error)
		isSaveing.value = false
	}
}

// 表单注入数据
const setData = (data) => {
	form.id = data.id
	form.username = data.username
	form.avatar = data.avatar
	form.real_name = data.real_name
	form.email = data.email
	form.phone = data.phone
	form.department_id = data.department_id
	form.role_ids = data.roles ? data.roles.map((item) => item.id) : []
	form.gender = data.gender !== undefined ? data.gender : null
	form.status = data.status !== undefined ? data.status : null
}

// 组件挂载时加载数据
loadDepartment()
loadRoles()

// 暴露方法给父组件
defineExpose({
	open,
	setData,
	close,
})
</script>

<style></style>
