<template>
	<a-drawer v-model:open="visible" :title="$t('pages.acl.component.modal.role.title')" placement="right" :width="600">
		<template #extra>
			<a-button style="margin-right: 8px" :loading="confirmLoading" @click="visible = false">
				{{ $t('pages.acl.component.modal.role.cancle') }}
			</a-button>
			<a-button type="primary" @click="handleOk">{{ $t('pages.acl.component.modal.role.submit') }}</a-button>
		</template>
		<a-transfer
			v-model:target-keys="targetKeys"
			v-model:selected-keys="selectedKeys"
			:data-source="roles"
			show-search
			:titles="titles"
			:render="itemRender"
			:list-style="{
				width: '300px',
				height: '500px',
			}"
		/>
	</a-drawer>
</template>
<script lang="ts" setup>
	import { TransferItem } from 'ant-design-vue/es/transfer'
	import { useI18n } from 'vue-i18n'
	const { t } = useI18n()
	const emit = defineEmits(['ok'])

	const props = withDefaults(defineProps<{ roles: Array<acl.RoleInfo> }>(), {
		roles: () => [],
	})

	const { roles } = toRefs(props)
	const visible = ref(false)
	const confirmLoading = ref(false)
	const targetKeys = ref<string[]>([])
	const selectedKeys = ref<string[]>([])
	const titles = [t('pages.acl.component.modal.role.source'), t('pages.acl.component.modal.role.target')]

	watch(
		roles,
		(newVal: acl.RoleInfo[]) => {
			targetKeys.value = newVal.filter((item) => item.selected).map((item) => item.key as string)
		},
		{ immediate: true, deep: true },
	)
	const open = () => {
		visible.value = true
		confirmLoading.value = false
	}

	const close = () => {
		visible.value = false
		confirmLoading.value = false
	}

	const itemRender = (item: TransferItem) => {
		return String(item.name)
	}

	const handleOk = () => {
		confirmLoading.value = true
		emit('ok', targetKeys.value)
	}

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