import { h, defineAsyncComponent } from 'vue';
import { confirmDialog, icon, renderDialog } from '../../utils/components';
import { toast } from 'vue-sonner';
import { getToastErrorMessage } from '../../utils/toast';

export function tagTab() {
	return {
		label: '标签',
		icon: icon('tag'),
		route: 'tags',
		type: 'list',
		list: {
			pagetype: 'Resource Tag',
			filters: documentResource => {
				return {
					parent: documentResource.name,
					parenttype: documentResource.pagetype
				};
			},
			orderBy: 'creation desc',
			columns: [
				{
					label: '标签',
					fieldname: 'tag_name'
				}
			],
			primaryAction({ listResource: tags, documentResource }) {
				return {
					label: '添加标签',
					slots: {
						prefix: icon('plus')
					},
					onClick() {
						let AddTagDialog = defineAsyncComponent(() =>
							import('../../components/AddTagDialog.vue')
						);
						renderDialog(
							h(AddTagDialog, {
								pagetype: documentResource.pagetype,
								docname: documentResource.name,
								onAdded() {
									tags.reload();
								}
							})
						);
					}
				};
			},
			rowActions({ row, listResource: tags, documentResource }) {
				return [
					{
						label: '移除',
						onClick() {
							if (documentResource.removeTag.loading) return;
							confirmDialog({
								title: '移除标签',
								message: `确定要移除标签 <b>${row.tag_name}</b> 吗？`,
								onSuccess({ hide }) {
									documentResource.removeTag.submit(
										{
											tag: row.tag_name
										},
										{
											onSuccess() {
												tags.reload();
												hide();
											}
										}
									);
									toast.promise(documentResource.removeTag.promise, {
										loading: '正在移除标签...',
										success: () => `标签 ${row.tag_name} 已移除`,
										error: e => getToastErrorMessage(e, '移除标签失败')
									});
								}
							});
						}
					}
				];
			}
		}
	};
}