<template>
	<a-modal v-model:open="visible" title="批量分配部门" :confirm-loading="loading" @ok="handleOk" @cancel="handleCancel">
		<a-form :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
			<a-form-item label="部门">
				<a-tree-select
					v-model:value="formState.department_id"
					:tree-data="departmentTree"
					placeholder="请选择部门"
					allow-clear
					:field-names="{
						label: 'name',
						value: 'id',
						children: 'children',
					}"
					tree-default-expand-all
					show-search
					:filter-tree-node="filterTreeNode"
				/>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

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

const visible = ref(false)
const loading = ref(false)
const departmentTree = ref([])
const userIds = ref([])

const formState = reactive({
	department_id: undefined,
})

// 打开弹窗
const open = (ids) => {
	visible.value = true
	userIds.value = ids
	formState.department_id = undefined
	loadDepartmentTree()
}

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

// 树节点过滤
const filterTreeNode = (inputValue, treeNode) => {
	const name = treeNode.dataRef.name
	return name ? name.toLowerCase().includes(inputValue.toLowerCase()) : false
}

// 确认
const handleOk = async () => {
	if (!formState.department_id) {
		message.warning('请选择部门')
		return
	}

	try {
		loading.value = true
		const res = await authApi.user.batchDepartment.post({
			ids: userIds.value,
			department_id: formState.department_id,
		})

		if (res.code === 200) {
			message.success('分配成功')
			emit('success')
			handleCancel()
		} else {
			message.error(res.message || '分配失败')
		}
	} catch (error) {
		console.error('批量分配部门失败:', error)
		message.error(error.message || '分配失败')
	} finally {
		loading.value = false
	}
}

// 取消
const handleCancel = () => {
	visible.value = false
	loading.value = false
	formState.department_id = undefined
}

const emit = defineEmits(['success'])

defineExpose({
	open,
})
</script>
