<template>
	<div class="p-5">
		<ObjectList :options="teamMembersListOptions"> </ObjectList>
	</div>
</template>

<script setup>
import { defineAsyncComponent, h, ref } from 'vue';
import { toast } from 'vue-sonner';
import { getTeam } from '../../data/team';
import { confirmDialog, renderDialog } from '../../utils/components';
import ObjectList from '../ObjectList.vue';
import UserWithAvatarCell from '../UserWithAvatarCell.vue';
import { getToastErrorMessage } from '../../utils/toast';

const team = getTeam();
team.getTeamMembers.submit();
const teamMembersListOptions = ref({
	onRowClick: () => {},
	rowHeight: 50,
	list: team.getTeamMembers,
	columns: [
		{
			label: '用户',
			type: 'Component',
			component: ({ row }) => {
				return h(UserWithAvatarCell, {
					avatarImage: row.user_image,
					fullName: row.full_name,
					email: row.email
				});
			},
			width: 1
		}
	],
	rowActions({ row }) {
		let team = getTeam();
		if (row.name === team.pg.user || row.name === team.pg.user_info?.name)
			return [];
		return [
			{
				label: '移除成员',
				condition: () => row.name !== team.pg.user,
				onClick() {
					if (team.removeTeamMember.loading) return;
					confirmDialog({
						title: '移除成员',
						message: `确定要将 <b>${row.full_name}</b> 从团队中移除吗？`,
						onSuccess({ hide }) {
							if (team.removeTeamMember.loading) return;
							toast.promise(
								team.removeTeamMember.submit({ member: row.name }),
								{
									loading: '正在移除成员...',
									success: () => {
										team.getTeamMembers.submit();
										hide();
										return '成员已移除';
									},
									error: e => getToastErrorMessage(e)
								}
							);
						}
					});
				}
			}
		];
	},
	actions() {
		return [
			{
				label: '设置',
				iconLeft: 'settings',
				onClick() {
					const TeamSettingsDialog = defineAsyncComponent(() =>
						import('./TeamSettingsDialog.vue')
					);
					renderDialog(h(TeamSettingsDialog));
				}
			},
			{
				label: '添加成员',
				variant: 'solid',
				iconLeft: 'plus',
				onClick() {
					const InviteTeamMemberDialog = defineAsyncComponent(() =>
						import('./InviteTeamMemberDialog.vue')
					);
					renderDialog(h(InviteTeamMemberDialog));
				}
			}
		];
	}
});
</script>