<template>
	<a-modal :title="titleMap[mode]" :open="visible" :width="500" :destroy-on-close="true" :footer="null" @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="parent_id">
				<a-tree-select v-model:value="form.parent_id" :tree-data="filteredDepartments" :field-names="departmentFieldNames" :tree-default-expand-all="false" placeholder="请选择上级部门" allow-clear tree-node-filter-prop="name" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" />
			</a-form-item>
			<a-form-item label="部门名称" name="name">
				<a-input v-model:value="form.name" placeholder="请输入部门名称" allow-clear></a-input>
			</a-form-item>
			<a-form-item label="负责人" name="leader">
				<a-input v-model:value="form.leader" placeholder="请输入负责人" allow-clear></a-input>
			</a-form-item>
			<a-form-item label="联系电话" name="phone">
				<a-input v-model:value="form.phone" placeholder="请输入联系电话" allow-clear></a-input>
			</a-form-item>
			<a-form-item label="排序" name="sort">
				<a-input-number v-model:value="form.sort" :min="0" :max="10000" style="width: 100%" placeholder="请输入排序" />
			</a-form-item>
			<a-form-item label="状态" name="status">
				<a-radio-group v-model:value="form.status">
					<a-radio :value="1">正常</a-radio>
					<a-radio :value="0">禁用</a-radio>
				</a-radio-group>
			</a-form-item>
			<a-form-item :wrapper-col="{ offset: 5 }">
				<div style="display: flex; gap: 10px">
					<a-button v-if="mode !== 'show'" type="primary" :loading="isSaveing" @click="submit">保 存</a-button>
					<a-button @click="handleCancel">取 消</a-button>
				</div>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

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

defineOptions({
	name: 'DepartmentSaveDialog',
})

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: '',
	name: '',
	leader: '',
	phone: '',
	sort: 0,
	parent_id: null,
	status: 1,
})

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

// 验证规则
const rules = {
	name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
	sort: [
		{ required: true, message: '请输入排序', trigger: 'change' },
		{ type: 'number', message: '排序必须为数字', trigger: 'change' },
	],
}

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

// 当前编辑的部门ID（用于过滤树）
const currentEditId = ref(null)

// 过滤后的部门树（编辑时排除自己和子部门）
const filteredDepartments = computed(() => {
	if (mode.value === 'add') {
		return departments.value
	}
	return filterDepartments(departments.value, currentEditId.value)
})

// 递归过滤部门树
const filterDepartments = (tree, excludeId) => {
	return tree
		.filter((item) => item.id !== excludeId)
		.map((item) => ({
			...item,
			children: item.children ? filterDepartments(item.children, excludeId) : undefined,
		}))
}

// 显示对话框
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 submit = async () => {
	try {
		await dialogForm.value.validate()
		isSaveing.value = true
		let res = {}
		form.parent_id = form.parent_id || 0

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

		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 loadDepartments = async () => {
	try {
		const res = await authApi.department.tree.get()
		if (res.code === 200) {
			departments.value = res.data || []
		}
	} catch (error) {
		console.error('加载部门树失败:', error)
		message.error('加载部门树失败')
	}
}

// 表单注入数据
const setData = (data) => {
	form.id = data.id
	currentEditId.value = data.id
	form.name = data.name
	form.leader = data.leader || ''
	form.phone = data.phone || ''
	form.sort = data.sort || 0
	form.parent_id = data.parent_id || null
	form.status = data.status !== undefined ? data.status : 1
}

// 组件挂载时加载数据
loadDepartments()

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

<style></style>
