<template>
	<a-modal v-model:open="visible" title="设置角色" :confirm-loading="loading" @ok="handleOk" @cancel="handleCancel">
		<a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
			<a-form-item label="用户">
				<a-input :value="userForm.username" disabled />
			</a-form-item>
			<a-form-item label="角色">
				<a-select v-model:value="selectedRoleIds" mode="multiple" placeholder="请选择角色" allow-clear :options="roleOptions" :field-names="{ label: 'name', value: 'id' }" :loading="roleLoading" show-search :filter-option="filterOption" />
			</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 roleLoading = ref(false)
const roleOptions = ref([])
const selectedRoleIds = ref([])
const userId = ref(null)

const userForm = reactive({
	username: '',
})

// 打开弹窗
const open = () => {
	visible.value = true
	loadRoles()
}

// 设置用户数据
const setData = (user) => {
	userId.value = user.id
	userForm.username = user.username
	// 设置已选择的角色
	selectedRoleIds.value = (user.roles || []).map((role) => role.id)
}

// 加载角色列表
const loadRoles = async () => {
	try {
		roleLoading.value = true
		const res = await authApi.role.list.get({ page_size: 1000 })
		if (res.code === 200) {
			roleOptions.value = (res.data.list || []).map((role) => ({
				id: role.id,
				name: role.name,
				code: role.code,
			}))
		}
	} catch (error) {
		console.error('加载角色列表失败:', error)
	} finally {
		roleLoading.value = false
	}
}

// 角色过滤
const filterOption = (input, option) => {
	const name = option?.name?.toLowerCase() || ''
	const code = option?.code?.toLowerCase() || ''
	const keyword = input?.toLowerCase() || ''
	return name.includes(keyword) || code.includes(keyword)
}

// 确认
const handleOk = async () => {
	if (!userId.value) {
		message.warning('用户ID不能为空')
		return
	}

	try {
		loading.value = true
		const res = await authApi.user.batchRoles.post({
			ids: [userId.value],
			role_ids: selectedRoleIds.value,
		})

		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
	userId.value = null
	userForm.username = ''
	selectedRoleIds.value = []
}

const emit = defineEmits(['success'])

defineExpose({
	open,
	setData,
})
</script>
