<template>
	<el-dialog v-model="visibleDialog" :title="`分配${currentTypeFlag ? '角色' : '部门'}`" :width="550" destroy-on-close @closed="handleCancel">
		<el-select v-model="roleIds" style="width: 500px" multiple filterable :placeholder="`请选择分配${currentTypeFlag ? '角色' : '部门'}`">
			<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'
import department from '@/api/system/department'

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

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,
		[currentTypeFlag.value ? 'roleIds' : 'departmentIds']: roleIds.value
	}
	try {
		if (currentTypeFlag.value) {
			await user.userAssignRolesApi(_param)
		} else {
			await user.userAssignDepartmentApi(_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 = currentTypeFlag.value ? data.roleIds : data.departmentIds
	}
}

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

// 加载全部部门
const loadDepartments = async () => {
	try {
		let data = await department.departmentListAllApi()
		options.value = data
	} catch (e) {
		ElMessage.success('加载全量部门失败')
	}
}
nextTick(() => {
	if (currentTypeFlag.value) {
		loadRoles()
	} else {
		loadDepartments()
	}
})

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

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

const currentTypeFlag = computed(() => {
	return myProps.typeModel === 'role' // true: 角色 false: 部门
})
</script>
