<script setup>
import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue';
import StatisticsStrip from '@/components/StatisticsStrip.vue';
import { TenantService } from '@/service/TenantService';
import { UserService } from '@/service/UserService';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, ref } from 'vue';

const toast = useToast();

const users = ref([]);
const loading = ref(false);

const totalRecords = ref(0);
const page = ref(1);
const rows = ref(10);

const userID = ref(null);
const tenantID = ref(null);
const username = ref('');
const status = ref('');
const role = ref('');
const createdAtFrom = ref(null);
const createdAtTo = ref(null);
const verifiedAtFrom = ref(null);
const verifiedAtTo = ref(null);
const sortField = ref('id');
const sortOrder = ref(-1);

function formatDate(value) {
    if (!value) return '-';
    if (String(value).startsWith('0001-01-01')) return '-';
    const date = new Date(value);
    if (Number.isNaN(date.getTime())) return String(value);
    return date.toLocaleString();
}

function formatCny(amountInCents) {
    const amount = Number(amountInCents) / 100;
    if (!Number.isFinite(amount)) return '-';
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(amount);
}

function getStatusSeverity(status) {
    switch (status) {
        case 'active':
        case 'verified':
            return 'success';
        case 'pending_verify':
        case 'pending':
            return 'warn';
        case 'banned':
        case 'disabled':
            return 'danger';
        default:
            return 'secondary';
    }
}

const statusDialogVisible = ref(false);
const statusLoading = ref(false);
const statusOptionsLoading = ref(false);
const statusOptions = ref([]);
const statusUser = ref(null);
const statusValue = ref(null);

const statusFilterOptions = computed(() => [{ label: '全部', value: '' }, ...(statusOptions.value || [])]);

const rolesDialogVisible = ref(false);
const rolesLoading = ref(false);
const rolesUser = ref(null);
const rolesSuperAdmin = ref(false);

const ownedTenantsDialogVisible = ref(false);
const ownedTenantsLoading = ref(false);
const ownedTenantsUser = ref(null);
const ownedTenants = ref([]);
const ownedTenantsTotal = ref(0);
const ownedTenantsPage = ref(1);
const ownedTenantsRows = ref(10);

const joinedTenantsDialogVisible = ref(false);
const joinedTenantsLoading = ref(false);
const joinedTenantsUser = ref(null);
const joinedTenants = ref([]);
const joinedTenantsTotal = ref(0);
const joinedTenantsPage = ref(1);
const joinedTenantsRows = ref(10);
const joinedTenantsTenantID = ref(null);
const joinedTenantsCode = ref('');
const joinedTenantsName = ref('');
const joinedTenantsRole = ref('');
const joinedTenantsStatus = ref('');
const joinedTenantsJoinedAtFrom = ref(null);
const joinedTenantsJoinedAtTo = ref(null);

const statistics = ref([]);
const statisticsLoading = ref(false);

const statisticsItems = computed(() => {
    const total = (statistics.value || []).reduce((sum, row) => sum + (Number(row?.count) || 0), 0);
    const statusIcon = (status) => {
        switch (status) {
            case 'verified':
                return 'pi-check-circle';
            case 'pending_verify':
                return 'pi-clock';
            case 'banned':
                return 'pi-ban';
            default:
                return 'pi-tag';
        }
    };
    const valueClass = (status) => {
        switch (status) {
            case 'banned':
                return 'text-red-500';
            case 'pending_verify':
                return 'text-orange-500';
            default:
                return '';
        }
    };

    return [
        { key: 'total', label: '用户总数：', value: statisticsLoading.value ? '-' : total, icon: 'pi-users' },
        ...(statistics.value || []).map((row) => ({
            key: row?.status ?? row?.status_description,
            label: `${row?.status_description || row?.status || '-'}：`,
            value: statisticsLoading.value ? '-' : (row?.count ?? 0),
            icon: statusIcon(row?.status),
            valueClass: valueClass(row?.status)
        }))
    ];
});

async function loadStatistics() {
    statisticsLoading.value = true;
    try {
        statistics.value = await UserService.getUserStatistics();
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载用户统计信息', life: 4000 });
    } finally {
        statisticsLoading.value = false;
    }
}

async function ensureStatusOptionsLoaded() {
    if (statusOptions.value.length > 0) return;
    statusOptionsLoading.value = true;
    try {
        const list = await UserService.getUserStatuses();
        statusOptions.value = (list || [])
            .map((kv) => ({
                label: kv?.value ?? kv?.key ?? '-',
                value: kv?.key ?? ''
            }))
            .filter((item) => item.value);
    } finally {
        statusOptionsLoading.value = false;
    }
}

async function openStatusDialog(user) {
    statusUser.value = user;
    statusValue.value = user?.status ?? null;
    statusDialogVisible.value = true;

    try {
        await ensureStatusOptionsLoaded();
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载用户状态列表', life: 4000 });
    }
}

async function confirmUpdateStatus() {
    const userID = statusUser.value?.id;
    if (!userID || !statusValue.value) return;

    statusLoading.value = true;
    try {
        await UserService.updateUserStatus({ userID, status: statusValue.value });
        toast.add({ severity: 'success', summary: '更新成功', detail: `用户ID: ${userID}`, life: 3000 });
        statusDialogVisible.value = false;
        await loadUsers();
        await loadStatistics();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新用户状态', life: 4000 });
    } finally {
        statusLoading.value = false;
    }
}

function hasRole(user, role) {
    const roles = user?.roles || [];
    return Array.isArray(roles) && roles.includes(role);
}

function openRolesDialog(user) {
    rolesUser.value = user;
    rolesSuperAdmin.value = hasRole(user, 'super_admin');
    rolesDialogVisible.value = true;
}

async function confirmUpdateRoles() {
    const userID = rolesUser.value?.id;
    if (!userID) return;

    const roles = ['user'];
    if (rolesSuperAdmin.value) roles.push('super_admin');

    rolesLoading.value = true;
    try {
        await UserService.updateUserRoles({ userID, roles });
        toast.add({ severity: 'success', summary: '更新成功', detail: `用户ID: ${userID}`, life: 3000 });
        rolesDialogVisible.value = false;
        await loadUsers();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新用户角色', life: 4000 });
    } finally {
        rolesLoading.value = false;
    }
}

async function loadUsers() {
    loading.value = true;
    try {
        const result = await UserService.listUsers({
            page: page.value,
            limit: rows.value,
            id: userID.value || undefined,
            tenant_id: tenantID.value || undefined,
            username: username.value,
            status: status.value,
            role: role.value || undefined,
            created_at_from: createdAtFrom.value || undefined,
            created_at_to: createdAtTo.value || undefined,
            verified_at_from: verifiedAtFrom.value || undefined,
            verified_at_to: verifiedAtTo.value || undefined,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        users.value = result.items;
        totalRecords.value = result.total;
    } catch (error) {
        toast.add({
            severity: 'error',
            summary: '加载失败',
            detail: error?.message || '无法加载用户列表',
            life: 4000
        });
    } finally {
        loading.value = false;
    }
}

function onSearch() {
    page.value = 1;
    loadUsers();
}

function onReset() {
    userID.value = null;
    tenantID.value = null;
    username.value = '';
    status.value = '';
    role.value = '';
    createdAtFrom.value = null;
    createdAtTo.value = null;
    verifiedAtFrom.value = null;
    verifiedAtTo.value = null;
    sortField.value = 'id';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadUsers();
}

function onPage(event) {
    page.value = (event.page ?? 0) + 1;
    rows.value = event.rows ?? rows.value;
    loadUsers();
}

function onSort(event) {
    sortField.value = event.sortField ?? sortField.value;
    sortOrder.value = event.sortOrder ?? sortOrder.value;
    loadUsers();
}

function openOwnedTenantsDialog(user) {
    ownedTenantsUser.value = user;
    ownedTenantsDialogVisible.value = true;
    ownedTenantsPage.value = 1;
    ownedTenantsRows.value = 10;
    loadOwnedTenants();
}

function openJoinedTenantsDialog(user) {
    joinedTenantsUser.value = user;
    joinedTenantsDialogVisible.value = true;
    joinedTenantsPage.value = 1;
    joinedTenantsRows.value = 10;
    joinedTenantsTenantID.value = null;
    joinedTenantsCode.value = '';
    joinedTenantsName.value = '';
    joinedTenantsRole.value = '';
    joinedTenantsStatus.value = '';
    joinedTenantsJoinedAtFrom.value = null;
    joinedTenantsJoinedAtTo.value = null;
    loadJoinedTenants();
}

async function loadOwnedTenants() {
    const uid = ownedTenantsUser.value?.id;
    if (!uid) return;

    ownedTenantsLoading.value = true;
    try {
        const result = await TenantService.listTenants({
            page: ownedTenantsPage.value,
            limit: ownedTenantsRows.value,
            user_id: uid,
            sortField: 'id',
            sortOrder: -1
        });
        ownedTenants.value = result.items;
        ownedTenantsTotal.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载该用户拥有的租户', life: 4000 });
    } finally {
        ownedTenantsLoading.value = false;
    }
}

function onOwnedTenantsPage(event) {
    ownedTenantsPage.value = (event.page ?? 0) + 1;
    ownedTenantsRows.value = event.rows ?? ownedTenantsRows.value;
    loadOwnedTenants();
}

async function loadJoinedTenants() {
    const uid = joinedTenantsUser.value?.id;
    if (!uid) return;

    joinedTenantsLoading.value = true;
    try {
        const result = await UserService.listUserTenants(uid, {
            page: joinedTenantsPage.value,
            limit: joinedTenantsRows.value,
            tenant_id: joinedTenantsTenantID.value || undefined,
            code: joinedTenantsCode.value,
            name: joinedTenantsName.value,
            role: joinedTenantsRole.value || undefined,
            status: joinedTenantsStatus.value || undefined,
            created_at_from: joinedTenantsJoinedAtFrom.value || undefined,
            created_at_to: joinedTenantsJoinedAtTo.value || undefined
        });
        joinedTenants.value = result.items;
        joinedTenantsTotal.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载该用户加入的租户', life: 4000 });
    } finally {
        joinedTenantsLoading.value = false;
    }
}

function onJoinedTenantsSearch() {
    joinedTenantsPage.value = 1;
    loadJoinedTenants();
}

function onJoinedTenantsReset() {
    joinedTenantsTenantID.value = null;
    joinedTenantsCode.value = '';
    joinedTenantsName.value = '';
    joinedTenantsRole.value = '';
    joinedTenantsStatus.value = '';
    joinedTenantsJoinedAtFrom.value = null;
    joinedTenantsJoinedAtTo.value = null;
    joinedTenantsPage.value = 1;
    joinedTenantsRows.value = 10;
    loadJoinedTenants();
}

function onJoinedTenantsPage(event) {
    joinedTenantsPage.value = (event.page ?? 0) + 1;
    joinedTenantsRows.value = event.rows ?? joinedTenantsRows.value;
    loadJoinedTenants();
}

onMounted(() => {
    loadUsers();
    loadStatistics();
    ensureStatusOptionsLoaded().catch(() => {});
});
</script>

<template>
    <div>
        <StatisticsStrip :items="statisticsItems" containerClass="card mb-4" />
        <div class="card">
            <div class="flex items-center justify-between mb-4">
                <h4 class="m-0">用户列表</h4>
            </div>

            <SearchPanel :loading="loading" @search="onSearch" @reset="onReset">
                <SearchField label="UserID">
                    <InputNumber v-model="userID" :min="1" placeholder="精确匹配" class="w-full" />
                </SearchField>
                <SearchField label="TenantID">
                    <InputNumber v-model="tenantID" :min="1" placeholder="加入该租户的用户" class="w-full" />
                </SearchField>
                <SearchField label="用户名">
                    <IconField>
                        <InputIcon>
                            <i class="pi pi-search" />
                        </InputIcon>
                        <InputText v-model="username" placeholder="请输入" class="w-full" @keyup.enter="onSearch" />
                    </IconField>
                </SearchField>
                <SearchField label="状态">
                    <Select v-model="status" :options="statusFilterOptions" optionLabel="label" optionValue="value" placeholder="请选择" :loading="statusOptionsLoading" class="w-full" />
                </SearchField>
                <SearchField label="角色">
                    <Select
                        v-model="role"
                        :options="[
                            { label: '全部', value: '' },
                            { label: 'user', value: 'user' },
                            { label: 'super_admin', value: 'super_admin' }
                        ]"
                        optionLabel="label"
                        optionValue="value"
                        placeholder="请选择"
                        class="w-full"
                    />
                </SearchField>
                <SearchField label="创建时间 From">
                    <DatePicker v-model="createdAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                </SearchField>
                <SearchField label="创建时间 To">
                    <DatePicker v-model="createdAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                </SearchField>
                <SearchField label="认证时间 From">
                    <DatePicker v-model="verifiedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                </SearchField>
                <SearchField label="认证时间 To">
                    <DatePicker v-model="verifiedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                </SearchField>
            </SearchPanel>

            <DataTable
                :value="users"
                dataKey="id"
                :loading="loading"
                lazy
                :paginator="true"
                :rows="rows"
                :totalRecords="totalRecords"
                :first="(page - 1) * rows"
                :rowsPerPageOptions="[10, 20, 50, 100]"
                sortMode="single"
                :sortField="sortField"
                :sortOrder="sortOrder"
                @page="onPage"
                @sort="onSort"
                currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                scrollable
                scrollHeight="flex"
                responsiveLayout="scroll"
            >
                <Column field="id" header="ID" sortable style="min-width: 6rem" />
                <Column field="username" header="用户名" sortable style="min-width: 16rem">
                    <template #body="{ data }">
                        <Button :label="data.username || '-'" icon="pi pi-external-link" text size="small" class="p-0" as="router-link" :to="`/superadmin/users/${data.id}`" />
                    </template>
                </Column>
                <Column field="status" header="状态" sortable style="min-width: 10rem">
                    <template #body="{ data }">
                        <Tag :value="data.status_description || data.status || '-'" :severity="getStatusSeverity(data.status)" class="cursor-pointer" @click="openStatusDialog(data)" />
                    </template>
                </Column>
                <Column field="roles" header="角色" style="min-width: 16rem">
                    <template #body="{ data }">
                        <div class="flex flex-wrap gap-1">
                            <Tag v-for="role in data.roles || []" :key="role" :value="role" severity="secondary" />
                            <span v-if="!data.roles || data.roles.length === 0" class="text-muted-color">-</span>
                        </div>
                    </template>
                </Column>
                <Column header="超管" style="min-width: 9rem">
                    <template #body="{ data }">
                        <Button :label="hasRole(data, 'super_admin') ? '是' : '否'" icon="pi pi-user-edit" text size="small" class="p-0" @click="openRolesDialog(data)" />
                    </template>
                </Column>
                <Column field="balance" header="余额" sortable style="min-width: 10rem">
                    <template #body="{ data }">
                        {{ formatCny(data.balance) }}
                    </template>
                </Column>
                <Column field="balance_frozen" header="冻结" sortable style="min-width: 10rem">
                    <template #body="{ data }">
                        {{ formatCny(data.balance_frozen) }}
                    </template>
                </Column>
                <Column header="拥有租户" style="min-width: 10rem">
                    <template #body="{ data }">
                        <Button :label="String(data.owned_tenant_count ?? 0)" icon="pi pi-building" text size="small" class="p-0" :disabled="(data.owned_tenant_count ?? 0) === 0" @click="openOwnedTenantsDialog(data)" />
                    </template>
                </Column>
                <Column header="加入租户" style="min-width: 10rem">
                    <template #body="{ data }">
                        <Button :label="String(data.joined_tenant_count ?? 0)" icon="pi pi-users" text size="small" class="p-0" :disabled="(data.joined_tenant_count ?? 0) === 0" @click="openJoinedTenantsDialog(data)" />
                    </template>
                </Column>
                <Column field="verified_at" header="认证时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data.verified_at) }}
                    </template>
                </Column>
                <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data.created_at) }}
                    </template>
                </Column>
                <Column field="updated_at" header="更新时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data.updated_at) }}
                    </template>
                </Column>
            </DataTable>
        </div>

        <Dialog v-model:visible="statusDialogVisible" :modal="true" :style="{ width: '420px' }">
            <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-medium">更新用户状态</span>
                    <span class="text-muted-color truncate max-w-[240px]">{{ statusUser?.username ?? '-' }}</span>
                </div>
            </template>
            <div class="flex flex-col gap-4">
                <div>
                    <label class="block font-medium mb-2">用户状态</label>
                    <Select v-model="statusValue" :options="statusOptions" optionLabel="label" optionValue="value" placeholder="选择状态" :disabled="statusLoading" fluid />
                </div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="statusDialogVisible = false" :disabled="statusLoading" />
                <Button label="确认" icon="pi pi-check" @click="confirmUpdateStatus" :loading="statusLoading" :disabled="!statusValue" />
            </template>
        </Dialog>

        <Dialog v-model:visible="rolesDialogVisible" :modal="true" :style="{ width: '420px' }">
            <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-medium">更新用户角色</span>
                    <span class="text-muted-color truncate max-w-[240px]">{{ rolesUser?.username ?? '-' }}</span>
                </div>
            </template>
            <div class="flex flex-col gap-4">
                <div class="flex items-center gap-2">
                    <Checkbox inputId="rolesSuperAdmin" v-model="rolesSuperAdmin" binary :disabled="rolesLoading" />
                    <label for="rolesSuperAdmin" class="cursor-pointer">super_admin</label>
                </div>
                <div class="text-sm text-muted-color">默认包含 user 角色。</div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="rolesDialogVisible = false" :disabled="rolesLoading" />
                <Button label="确认" icon="pi pi-check" @click="confirmUpdateRoles" :loading="rolesLoading" />
            </template>
        </Dialog>

        <Dialog v-model:visible="ownedTenantsDialogVisible" :modal="true" :style="{ width: '980px' }">
            <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-medium">该用户拥有的租户</span>
                    <span class="text-muted-color truncate max-w-[360px]">{{ ownedTenantsUser?.username ?? '-' }}</span>
                </div>
            </template>
            <div class="flex flex-col gap-4">
                <DataTable
                    :value="ownedTenants"
                    dataKey="id"
                    :loading="ownedTenantsLoading"
                    lazy
                    :paginator="true"
                    :rows="ownedTenantsRows"
                    :totalRecords="ownedTenantsTotal"
                    :first="(ownedTenantsPage - 1) * ownedTenantsRows"
                    :rowsPerPageOptions="[10, 20, 50, 100]"
                    @page="onOwnedTenantsPage"
                    currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                    paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                    scrollable
                    scrollHeight="420px"
                    responsiveLayout="scroll"
                >
                    <Column field="id" header="ID" style="min-width: 6rem" />
                    <Column field="code" header="Code" style="min-width: 10rem" />
                    <Column field="name" header="名称" style="min-width: 14rem" />
                    <Column field="status_description" header="状态" style="min-width: 10rem" />
                    <Column field="user_count" header="用户数" style="min-width: 8rem" />
                    <Column field="income_amount_paid_sum" header="累计收入" style="min-width: 10rem">
                        <template #body="{ data }">
                            {{ formatCny(data.income_amount_paid_sum) }}
                        </template>
                    </Column>
                    <Column field="expired_at" header="过期时间" style="min-width: 14rem">
                        <template #body="{ data }">
                            {{ formatDate(data.expired_at) }}
                        </template>
                    </Column>
                </DataTable>
            </div>
            <template #footer>
                <Button label="关闭" icon="pi pi-times" text @click="ownedTenantsDialogVisible = false" />
            </template>
        </Dialog>

        <Dialog v-model:visible="joinedTenantsDialogVisible" :modal="true" :style="{ width: '1180px' }">
            <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-medium">该用户加入的租户</span>
                    <span class="text-muted-color truncate max-w-[360px]">{{ joinedTenantsUser?.username ?? '-' }}</span>
                </div>
            </template>
            <div class="flex flex-col gap-4">
                <SearchPanel :loading="joinedTenantsLoading" @search="onJoinedTenantsSearch" @reset="onJoinedTenantsReset">
                    <SearchField label="TenantID">
                        <InputNumber v-model="joinedTenantsTenantID" :min="1" placeholder="精确匹配" class="w-full" />
                    </SearchField>
                    <SearchField label="Code">
                        <InputText v-model="joinedTenantsCode" placeholder="请输入" class="w-full" @keyup.enter="onJoinedTenantsSearch" />
                    </SearchField>
                    <SearchField label="名称">
                        <InputText v-model="joinedTenantsName" placeholder="请输入" class="w-full" @keyup.enter="onJoinedTenantsSearch" />
                    </SearchField>
                    <SearchField label="成员角色">
                        <Select
                            v-model="joinedTenantsRole"
                            :options="[
                                { label: '全部', value: '' },
                                { label: 'tenant_admin', value: 'tenant_admin' },
                                { label: 'member', value: 'member' }
                            ]"
                            optionLabel="label"
                            optionValue="value"
                            placeholder="请选择"
                            class="w-full"
                        />
                    </SearchField>
                    <SearchField label="成员状态">
                        <Select v-model="joinedTenantsStatus" :options="statusFilterOptions" optionLabel="label" optionValue="value" placeholder="请选择" :loading="statusOptionsLoading" class="w-full" />
                    </SearchField>
                    <SearchField label="加入时间 From">
                        <DatePicker v-model="joinedTenantsJoinedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                    </SearchField>
                    <SearchField label="加入时间 To">
                        <DatePicker v-model="joinedTenantsJoinedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                    </SearchField>
                </SearchPanel>

                <DataTable
                    :value="joinedTenants"
                    dataKey="tenant_id"
                    :loading="joinedTenantsLoading"
                    lazy
                    :paginator="true"
                    :rows="joinedTenantsRows"
                    :totalRecords="joinedTenantsTotal"
                    :first="(joinedTenantsPage - 1) * joinedTenantsRows"
                    :rowsPerPageOptions="[10, 20, 50, 100]"
                    @page="onJoinedTenantsPage"
                    currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                    paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                    scrollable
                    scrollHeight="420px"
                    responsiveLayout="scroll"
                >
                    <Column field="tenant_id" header="TenantID" style="min-width: 7rem" />
                    <Column field="code" header="Code" style="min-width: 10rem" />
                    <Column field="name" header="名称" style="min-width: 14rem" />
                    <Column header="Owner" style="min-width: 12rem">
                        <template #body="{ data }">
                            <span>{{ data?.owner?.username ?? '-' }}</span>
                        </template>
                    </Column>
                    <Column header="租户状态" style="min-width: 12rem">
                        <template #body="{ data }">
                            <Tag :value="data.tenant_status_description || data.tenant_status || '-'" severity="secondary" />
                        </template>
                    </Column>
                    <Column header="成员角色" style="min-width: 14rem">
                        <template #body="{ data }">
                            <div class="flex flex-wrap gap-1">
                                <Tag v-for="r in data.role || []" :key="r" :value="r" severity="secondary" />
                                <span v-if="!data.role || data.role.length === 0" class="text-muted-color">-</span>
                            </div>
                        </template>
                    </Column>
                    <Column header="成员状态" style="min-width: 10rem">
                        <template #body="{ data }">
                            <Tag :value="data.member_status_description || data.member_status || '-'" :severity="getStatusSeverity(data.member_status)" />
                        </template>
                    </Column>
                    <Column field="joined_at" header="加入时间" style="min-width: 14rem">
                        <template #body="{ data }">
                            {{ formatDate(data.joined_at) }}
                        </template>
                    </Column>
                    <Column field="expired_at" header="过期时间" style="min-width: 14rem">
                        <template #body="{ data }">
                            {{ formatDate(data.expired_at) }}
                        </template>
                    </Column>
                </DataTable>
            </div>
            <template #footer>
                <Button label="关闭" icon="pi pi-times" text @click="joinedTenantsDialogVisible = false" />
            </template>
        </Dialog>
    </div>
</template>
