<template>
	<el-dialog v-model="visibleDialog" title="分配角色/部门" :width="550" destroy-on-close @closed="handleCancel">
		<el-select v-model="roleIds" style="width: 500px" multiple filterable placeholder="请选择分配角色">
			<el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
				<span style="float: left">{{ item.name }}</span>
				<span style="float: right; color: var(--el-text-color-secondary); font-size: 13px">{{ item.alias }}</span>
			</el-option>
		</el-select>
		<template #footer>
			<el-button @click="handleCancel">取 消</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import { ref, nextTick, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import user from '@/api/system/user'
import role from '@/api/system/role'

const myProps = defineProps({
	modelValue: {
		type: Boolean,
		default: false
	},
	userIds: {
		type: Array,
		default: () => []
	}
})

const isSaveing = ref(false)
const options = ref([])
const roleIds = ref([])

// 同步值
const $myEmit = defineEmits(['update:modelValue', 'successFn'])

// 关闭按钮
const closeDrawer = () => {
	$myEmit('successFn')
	$myEmit('update:modelValue', false)
}

const handleCancel = () => {
	closeDrawer()
}

// 保存
const submit = async () => {
	isSaveing.value = true
	const _param = {
		userIds: myProps.userIds,
		roleIds: roleIds.value
	}
	try {
		await user.userAssignRolesApi(_param)
		ElMessage.success('分配成功')
		isSaveing.value = false
		visibleDialog.value = false
	} catch (e) {
		ElMessage.error('分配失败')
		isSaveing.value = false
		visibleDialog.value = false
	}
}

const open = async userIds => {
	if (userIds.length === 1) {
		let data = await user.userRoleIdsApi({ id: userIds[0] })
		roleIds.value = data
	}
}

// 加载全部角色
const loadRoles = async () => {
	try {
		let data = await role.roleListAllApi()
		options.value = data
	} catch (e) {
		ElMessage.success('加载全量角色失败')
	}
}

nextTick(() => {
	loadRoles()
})

watch(
	() => myProps.modelValue,
	val => {
		if (val) {
			open(myProps.userIds)
		}
	},
	{ immediate: true }
)

const visibleDialog = computed({
	get() {
		return myProps.modelValue
	},
	set(val) {
		$myEmit('update:modelValue', val)
	}
})
</script>
