<template>
	<div class="mb-5 flex items-center gap-2">
		<Tooltip text="所有角色">
			<Button :route="{ name: 'SettingsPermissionRoles' }">
				<template #icon>
					<i-lucide-arrow-left class="h-4 w-4 text-gray-700" />
				</template>
			</Button>
		</Tooltip>
		<h3 class="text-lg font-medium text-gray-900">
			{{ role.pg?.title }}
		</h3>
		<Tooltip text="管理员角色" v-if="role.pg.admin_access">
			<FeatherIcon name="shield" class="h-5 w-5 text-gray-700" />
		</Tooltip>
	</div>
	<ObjectList
		:options="rolePermissions"
		@update:selections="(e) => (selectedItems = e)"
	>
		<template #header-left="{ listResource }">
			<Dropdown :options="getDropdownOptions(listResource)">
				<Button>
					<template #prefix>
						<LucideAppWindow class="h-4 w-4 text-gray-500" />
					</template>
					{{ currentDropdownOption.label }}
					<template #suffix>
						<FeatherIcon name="chevron-down" class="h-4 w-4 text-gray-500" />
					</template>
				</Button>
			</Dropdown>
		</template>
	</ObjectList>
</template>

<script setup>
import {
	Button,
	Dropdown,
	createDocumentResource,
	createResource,
} from 'jingrow-ui';
import { computed, h, ref } from 'vue';
import LucideAppWindow from '~icons/lucide/app-window';
import ObjectList from '../ObjectList.vue';
import { toast } from 'vue-sonner';
import { getToastErrorMessage } from '../../utils/toast';
import { confirmDialog, icon, renderDialog } from '../../utils/components';
import RoleConfigureDialog from './RoleConfigureDialog.vue';

let selectedItems = ref(new Set());

const props = defineProps({
	roleId: { type: String, required: true },
});

const role = createDocumentResource({
	pagetype: 'Jcloud Role',
	name: props.roleId,
	auto: true,
	whitelistedMethods: {
		addUser: 'add_user',
		removeUser: 'remove_user',
		bulkDelete: 'delete_permissions',
	},
});

const docInsert = createResource({
	url: 'jcloud.api.client.insert',
});

const dropdownOptions = [
	{ label: '允许的站点', pagetype: 'Site', fieldname: 'site' },
	{
		label: '允许的发布组',
		pagetype: 'Release Group',
		fieldname: 'release_group',
	},
	{ label: '允许的服务器', pagetype: 'Server', fieldname: 'server' },
];
const currentDropdownOption = ref(dropdownOptions[0]);
function getDropdownOptions(listResource) {
	return dropdownOptions.map((option) => {
		return {
			...option,
			onClick: () => {
				currentDropdownOption.value = option;
				let filters = {
					role: props.roleId,
				};
				if (option.pagetype === 'Site') {
					filters.site = ['is', 'set'];
				}
				if (option.pagetype === 'Release Group') {
					filters.release_group = ['is', 'set'];
				}
				if (option.pagetype === 'Server') {
					filters.server = ['is', 'set'];
				}
				listResource.update({ filters });
				listResource.reload();
			},
		};
	});
}

const rolePermissions = ref({
	pagetype: 'Jcloud Role Permission',
	fields: [
		'site',
		'site.host_name as site_host_name',
		'release_group',
		'release_group.title as release_group_title',
		'server',
		'server.title as server_title',
	],
	filters: {
		role: props.roleId,
		site: ['is', 'set'],
	},
	selectable: true,
	columns: [
		{
			label: computed(() =>
				currentDropdownOption.value.pagetype.replace(
					'Release Group',
					'发布组',
				),
			),
			format(_value, row) {
				return (
					row.site_host_name ||
					row.site ||
					row.release_group_title ||
					row.server_title
				);
			},
		},
	],
	actions({ listResource: permissions }) {
		return [
			{
				label: '配置',
				slots: {
					prefix: icon('settings'),
				},
				onClick() {
					renderDialog(h(RoleConfigureDialog, { roleId: props.roleId }));
				},
			},
			{
				label: '删除',
slots: {
					prefix: icon('trash-2'),
				},
				condition: () => selectedItems.value.size > 0,
				onClick() {
					role.bulkDelete.submit(
						{
							permissions: Array.from(selectedItems.value),
						},
						{
							onSuccess: () => {
								toast.success('项目删除成功');
								selectedItems.value.clear();
							},
						},
					);
				},
			},
			{
				label: '添加',
				slots: {
					prefix: icon('plus'),
				},
				onClick() {
					confirmDialog({
						title: '添加权限',
						message: '',
						fields: [
							{
								label: `选择 ${currentDropdownOption.value.pagetype.replace(
									'Release Group',
									'Bench Group',
								)}`,
								type: 'link',
								fieldname: 'document_name',
								options: {
									pagetype: currentDropdownOption.value.pagetype,
									filters: {
										name: [
											'not in',
											permissions.data.map(
												(p) => p[currentDropdownOption.value.fieldname],
											) || '',
										],
										status: ['!=', 'Archived'],
									},
								},
							},
						],
						primaryAction: {
							label: '添加',
							onClick({ values }) {
								let key = currentDropdownOption.value.fieldname;

								toast.promise(
									docInsert.submit({
										pg: {
											pagetype: 'Jcloud Role Permission',
											role: props.roleId,
											[key]: values.document_name,
										},
									}),
									{
										loading: '正在添加权限...',
										success() {
											permissions.reload();
											return '权限添加成功';
										},
										error: (e) => getToastErrorMessage(e),
									},
								);
							},
						},
					});
				},
			},
		].filter((action) => (action.condition ? action.condition() : true));
	},
});
</script>