<script setup>
import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue';
import { ContentService } from '@/service/ContentService';
import { OrderService } from '@/service/OrderService';
import { TenantService } from '@/service/TenantService';
import { useToast } from 'primevue/usetoast';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

const toast = useToast();
const route = useRoute();

const tenantID = computed(() => Number(route.params.tenantID));

const loading = ref(false);
const tenant = ref(null);

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 'verified':
            return 'success';
        case 'pending_verify':
            return 'warn';
        case 'banned':
            return 'danger';
        default:
            return 'secondary';
    }
}

function getOrderStatusSeverity(value) {
    switch (value) {
        case 'paid':
            return 'success';
        case 'created':
        case 'refunding':
            return 'warn';
        case 'failed':
        case 'canceled':
            return 'danger';
        default:
            return 'secondary';
    }
}

function getContentStatusSeverity(value) {
    switch (value) {
        case 'published':
            return 'success';
        case 'reviewing':
            return 'warn';
        case 'blocked':
            return 'danger';
        case 'draft':
        case 'unpublished':
        default:
            return 'secondary';
    }
}

function getContentVisibilitySeverity(value) {
    switch (value) {
        case 'public':
            return 'info';
        case 'tenant_only':
            return 'warn';
        case 'private':
            return 'secondary';
        default:
            return 'secondary';
    }
}

async function loadTenant() {
    const id = tenantID.value;
    if (!id || Number.isNaN(id)) return;

    loading.value = true;
    try {
        tenant.value = await TenantService.getTenantDetail(id);
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载租户详情', life: 4000 });
    } finally {
        loading.value = false;
    }
}

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

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

async function openStatusDialog() {
    statusValue.value = tenant.value?.status ?? '';
    statusDialogVisible.value = true;
    await ensureStatusOptionsLoaded();
}

async function confirmUpdateStatus() {
    const id = tenantID.value;
    if (!id || !statusValue.value) return;
    statusLoading.value = true;
    try {
        await TenantService.updateTenantStatus({ tenantID: id, status: statusValue.value });
        toast.add({ severity: 'success', summary: '更新成功', detail: `租户ID: ${id}`, life: 3000 });
        statusDialogVisible.value = false;
        await loadTenant();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新租户状态', life: 4000 });
    } finally {
        statusLoading.value = false;
    }
}

const renewDialogVisible = ref(false);
const renewing = ref(false);
const renewDuration = ref(30);
const durationOptions = [
    { label: '7 天', value: 7 },
    { label: '30 天', value: 30 },
    { label: '90 天', value: 90 },
    { label: '180 天', value: 180 },
    { label: '365 天', value: 365 }
];

const unpublishDialogVisible = ref(false);
const unpublishLoading = ref(false);
const unpublishItem = ref(null);

function openUnpublishDialog(row) {
    unpublishItem.value = row;
    unpublishDialogVisible.value = true;
}

async function confirmUnpublish() {
    const id = tenantID.value;
    const contentID = unpublishItem.value?.content?.id;
    if (!id || !contentID) return;

    unpublishLoading.value = true;
    try {
        await ContentService.updateTenantContentStatus(id, contentID, { status: 'unpublished' });
        toast.add({ severity: 'success', summary: '下架成功', detail: `ContentID: ${contentID}`, life: 3000 });
        unpublishDialogVisible.value = false;
        await loadContents();
    } catch (error) {
        toast.add({ severity: 'error', summary: '下架失败', detail: error?.message || '无法下架内容', life: 4000 });
    } finally {
        unpublishLoading.value = false;
    }
}

async function confirmRenew() {
    const id = tenantID.value;
    if (!id) return;
    renewing.value = true;
    try {
        await TenantService.renewTenantExpire({ tenantID: id, duration: renewDuration.value });
        toast.add({ severity: 'success', summary: '续期成功', detail: `+${renewDuration.value} 天`, life: 3000 });
        renewDialogVisible.value = false;
        await loadTenant();
    } catch (error) {
        toast.add({ severity: 'error', summary: '续期失败', detail: error?.message || '无法续期', life: 4000 });
    } finally {
        renewing.value = false;
    }
}

const tabValue = ref('users');

const tenantUsersLoading = ref(false);
const tenantUsers = ref([]);
const tenantUsersTotal = ref(0);
const tenantUsersPage = ref(1);
const tenantUsersRows = ref(10);
const tenantUsersUsername = ref('');
const tenantUsersUserID = ref(null);
const tenantUsersRole = ref('');
const tenantUsersStatus = ref('');

async function loadTenantUsers() {
    const id = tenantID.value;
    if (!id) return;

    tenantUsersLoading.value = true;
    try {
        const data = await TenantService.listTenantUsers(id, {
            page: tenantUsersPage.value,
            limit: tenantUsersRows.value,
            username: tenantUsersUsername.value,
            user_id: tenantUsersUserID.value || undefined,
            role: tenantUsersRole.value || undefined,
            status: tenantUsersStatus.value || undefined
        });

        const normalizeItems = (items) => {
            if (Array.isArray(items)) return items;
            if (items && typeof items === 'object') return [items];
            return [];
        };
        tenantUsers.value = normalizeItems(data?.items);
        tenantUsersTotal.value = data?.total ?? 0;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载租户成员列表', life: 4000 });
    } finally {
        tenantUsersLoading.value = false;
    }
}

function onTenantUsersSearch() {
    tenantUsersPage.value = 1;
    loadTenantUsers();
}

function onTenantUsersReset() {
    tenantUsersUsername.value = '';
    tenantUsersUserID.value = null;
    tenantUsersRole.value = '';
    tenantUsersStatus.value = '';
    tenantUsersPage.value = 1;
    tenantUsersRows.value = 10;
    loadTenantUsers();
}

function onTenantUsersPageChange(event) {
    tenantUsersPage.value = (event.page ?? 0) + 1;
    tenantUsersRows.value = event.rows ?? tenantUsersRows.value;
    loadTenantUsers();
}

const contentsLoading = ref(false);
const contents = ref([]);
const contentsTotal = ref(0);
const contentsPage = ref(1);
const contentsRows = ref(10);
const contentsKeyword = ref('');
const contentsStatus = ref('published');
const contentsVisibility = ref('');
const contentsOwnerUserID = ref(null);
const contentsPublishedAtFrom = ref(null);
const contentsPublishedAtTo = ref(null);
const contentsCreatedAtFrom = ref(null);
const contentsCreatedAtTo = ref(null);
const contentsSortField = ref('id');
const contentsSortOrder = ref(-1);

const contentStatusOptions = [
    { label: '全部', value: '' },
    { label: 'draft', value: 'draft' },
    { label: 'reviewing', value: 'reviewing' },
    { label: 'published', value: 'published' },
    { label: 'unpublished', value: 'unpublished' },
    { label: 'blocked', value: 'blocked' }
];

const contentVisibilityOptions = [
    { label: '全部', value: '' },
    { label: 'public', value: 'public' },
    { label: 'tenant_only', value: 'tenant_only' },
    { label: 'private', value: 'private' }
];

async function loadContents() {
    const id = tenantID.value;
    if (!id) return;

    contentsLoading.value = true;
    try {
        const result = await ContentService.listTenantContents(id, {
            page: contentsPage.value,
            limit: contentsRows.value,
            keyword: contentsKeyword.value,
            status: contentsStatus.value || undefined,
            visibility: contentsVisibility.value || undefined,
            user_id: contentsOwnerUserID.value || undefined,
            published_at_from: contentsPublishedAtFrom.value || undefined,
            published_at_to: contentsPublishedAtTo.value || undefined,
            created_at_from: contentsCreatedAtFrom.value || undefined,
            created_at_to: contentsCreatedAtTo.value || undefined,
            sortField: contentsSortField.value,
            sortOrder: contentsSortOrder.value
        });
        contents.value = (result.items || []).map((item) => ({ ...item, __key: item?.content?.id ?? undefined }));
        contentsTotal.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载租户内容列表', life: 4000 });
    } finally {
        contentsLoading.value = false;
    }
}

function onContentsSearch() {
    contentsPage.value = 1;
    loadContents();
}

function onContentsReset() {
    contentsKeyword.value = '';
    contentsStatus.value = 'published';
    contentsVisibility.value = '';
    contentsOwnerUserID.value = null;
    contentsPublishedAtFrom.value = null;
    contentsPublishedAtTo.value = null;
    contentsCreatedAtFrom.value = null;
    contentsCreatedAtTo.value = null;
    contentsSortField.value = 'id';
    contentsSortOrder.value = -1;
    contentsPage.value = 1;
    contentsRows.value = 10;
    loadContents();
}

function onContentsPage(event) {
    contentsPage.value = (event.page ?? 0) + 1;
    contentsRows.value = event.rows ?? contentsRows.value;
    loadContents();
}

function onContentsSort(event) {
    contentsSortField.value = event.sortField ?? contentsSortField.value;
    contentsSortOrder.value = event.sortOrder ?? contentsSortOrder.value;
    loadContents();
}

const ordersLoading = ref(false);
const orders = ref([]);
const ordersTotal = ref(0);
const ordersPage = ref(1);
const ordersRows = ref(10);
const orderIDFilter = ref(null);
const buyerUserIDFilter = ref(null);
const buyerUsernameFilter = ref('');
const orderStatusFilter = ref('');
const createdAtFromFilter = ref(null);
const createdAtToFilter = ref(null);
const paidAtFromFilter = ref(null);
const paidAtToFilter = ref(null);
const orderSortField = ref('id');
const orderSortOrder = ref(-1);

const orderStatusOptions = [
    { label: '全部', value: '' },
    { label: 'created', value: 'created' },
    { label: 'paid', value: 'paid' },
    { label: 'refunding', value: 'refunding' },
    { label: 'refunded', value: 'refunded' },
    { label: 'canceled', value: 'canceled' },
    { label: 'failed', value: 'failed' }
];

async function loadOrders() {
    const id = tenantID.value;
    if (!id) return;

    ordersLoading.value = true;
    try {
        const result = await OrderService.listOrders({
            page: ordersPage.value,
            limit: ordersRows.value,
            tenant_id: id,
            id: orderIDFilter.value || undefined,
            user_id: buyerUserIDFilter.value || undefined,
            username: buyerUsernameFilter.value,
            status: orderStatusFilter.value,
            created_at_from: createdAtFromFilter.value || undefined,
            created_at_to: createdAtToFilter.value || undefined,
            paid_at_from: paidAtFromFilter.value || undefined,
            paid_at_to: paidAtToFilter.value || undefined,
            sortField: orderSortField.value,
            sortOrder: orderSortOrder.value
        });
        orders.value = result.items;
        ordersTotal.value = result.total;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载租户订单列表', life: 4000 });
    } finally {
        ordersLoading.value = false;
    }
}

function onOrdersSearch() {
    ordersPage.value = 1;
    loadOrders();
}

function onOrdersReset() {
    orderIDFilter.value = null;
    buyerUserIDFilter.value = null;
    buyerUsernameFilter.value = '';
    orderStatusFilter.value = '';
    createdAtFromFilter.value = null;
    createdAtToFilter.value = null;
    paidAtFromFilter.value = null;
    paidAtToFilter.value = null;
    orderSortField.value = 'id';
    orderSortOrder.value = -1;
    ordersPage.value = 1;
    ordersRows.value = 10;
    loadOrders();
}

function onOrdersPage(event) {
    ordersPage.value = (event.page ?? 0) + 1;
    ordersRows.value = event.rows ?? ordersRows.value;
    loadOrders();
}

function onOrdersSort(event) {
    orderSortField.value = event.sortField ?? orderSortField.value;
    orderSortOrder.value = event.sortOrder ?? orderSortOrder.value;
    loadOrders();
}

watch(
    () => tenantID.value,
    () => {
        tenantUsersPage.value = 1;
        tenantUsersRows.value = 10;
        contentsPage.value = 1;
        contentsRows.value = 10;
        ordersPage.value = 1;
        ordersRows.value = 10;
        loadTenant();
        loadTenantUsers();
        loadContents();
        loadOrders();
    },
    { immediate: true }
);

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

<template>
    <div class="card">
        <div class="flex items-center justify-between mb-4">
            <div class="flex flex-col">
                <h4 class="m-0">租户详情</h4>
                <span class="text-muted-color">TenantID: {{ tenantID || '-' }}</span>
            </div>
            <div class="flex items-center gap-2">
                <Button label="刷新" icon="pi pi-refresh" severity="secondary" @click="loadTenant" :disabled="loading" />
                <Button label="续期" icon="pi pi-calendar-plus" @click="renewDialogVisible = true" :disabled="loading" />
            </div>
        </div>

        <div v-if="loading" class="flex items-center justify-center py-10">
            <ProgressSpinner style="width: 36px; height: 36px" strokeWidth="6" />
        </div>
        <div v-else class="grid grid-cols-12 gap-3">
            <div class="col-span-12 md:col-span-6">
                <div class="text-sm text-muted-color">名称</div>
                <div class="font-medium">{{ tenant?.name ?? '-' }}</div>
                <div class="text-sm text-muted-color">Code: {{ tenant?.code ?? '-' }}</div>
            </div>
            <div class="col-span-12 md:col-span-6">
                <div class="text-sm text-muted-color">状态</div>
                <Tag :value="tenant?.status_description || tenant?.status || '-'" :severity="getStatusSeverity(tenant?.status)" class="cursor-pointer" @click="openStatusDialog" />
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">Owner</div>
                <div class="font-medium">{{ tenant?.owner?.username ?? tenant?.user_id ?? '-' }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">管理员</div>
                <div class="flex flex-wrap gap-1">
                    <Tag v-for="u in tenant?.admin_users || []" :key="u.id" :value="u.username" severity="secondary" />
                    <span v-if="!tenant?.admin_users || tenant.admin_users.length === 0" class="text-muted-color">-</span>
                </div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">累计收入</div>
                <div class="font-medium">{{ formatCny(tenant?.income_amount_paid_sum) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">成员数</div>
                <div class="font-medium">{{ tenant?.user_count ?? 0 }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">过期时间</div>
                <div class="font-medium">{{ formatDate(tenant?.expired_at) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">创建时间</div>
                <div class="font-medium">{{ formatDate(tenant?.created_at) }}</div>
            </div>
            <div class="col-span-12 md:col-span-4">
                <div class="text-sm text-muted-color">更新时间</div>
                <div class="font-medium">{{ formatDate(tenant?.updated_at) }}</div>
            </div>
        </div>
    </div>

    <div class="card">
        <Tabs v-model:value="tabValue" value="users">
            <TabList>
                <Tab value="users">成员</Tab>
                <Tab value="contents">内容</Tab>
                <Tab value="orders">订单</Tab>
            </TabList>
            <TabPanels>
                <TabPanel value="users">
                    <div class="flex flex-col gap-4">
                        <SearchPanel :loading="tenantUsersLoading" @search="onTenantUsersSearch" @reset="onTenantUsersReset">
                            <SearchField label="UserID">
                                <InputNumber v-model="tenantUsersUserID" :min="1" placeholder="精确匹配" class="w-full" />
                            </SearchField>
                            <SearchField label="用户名">
                                <InputText v-model="tenantUsersUsername" placeholder="请输入" class="w-full" @keyup.enter="onTenantUsersSearch" />
                            </SearchField>
                            <SearchField label="角色">
                                <Select
                                    v-model="tenantUsersRole"
                                    :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="tenantUsersStatus"
                                    :options="[
                                        { label: '全部', value: '' },
                                        { label: 'verified', value: 'verified' },
                                        { label: 'pending_verify', value: 'pending_verify' },
                                        { label: 'banned', value: 'banned' }
                                    ]"
                                    optionLabel="label"
                                    optionValue="value"
                                    placeholder="请选择"
                                    class="w-full"
                                />
                            </SearchField>
                        </SearchPanel>

                        <DataTable
                            :value="tenantUsers"
                            dataKey="id"
                            :loading="tenantUsersLoading"
                            lazy
                            :paginator="true"
                            :rows="tenantUsersRows"
                            :totalRecords="tenantUsersTotal"
                            :first="(tenantUsersPage - 1) * tenantUsersRows"
                            :rowsPerPageOptions="[10, 20, 50, 100]"
                            @page="onTenantUsersPageChange"
                            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                            scrollable
                            scrollHeight="520px"
                            responsiveLayout="scroll"
                        >
                            <Column field="user.id" header="UserID" style="min-width: 8rem">
                                <template #body="{ data }">
                                    {{ data?.user?.id ?? data?.user_id ?? '-' }}
                                </template>
                            </Column>
                            <Column field="user.username" header="用户名" style="min-width: 14rem">
                                <template #body="{ data }">
                                    <Button
                                        :label="data?.user?.username ?? '-'"
                                        icon="pi pi-external-link"
                                        text
                                        size="small"
                                        class="p-0"
                                        as="router-link"
                                        :to="data?.user?.id ? `/superadmin/users/${data.user.id}` : undefined"
                                        :disabled="!data?.user?.id"
                                    />
                                </template>
                            </Column>
                            <Column header="角色" style="min-width: 16rem">
                                <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 field="status" header="状态" style="min-width: 10rem">
                                <template #body="{ data }">
                                    <Tag :value="data.status_description || data.status || '-'" :severity="getStatusSeverity(data.status)" />
                                </template>
                            </Column>
                            <Column field="created_at" header="加入时间" style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data.created_at) }}
                                </template>
                            </Column>
                        </DataTable>
                    </div>
                </TabPanel>
                <TabPanel value="contents">
                    <div class="flex flex-col gap-4">
                        <SearchPanel :loading="contentsLoading" @search="onContentsSearch" @reset="onContentsReset">
                            <SearchField label="Keyword">
                                <IconField>
                                    <InputIcon>
                                        <i class="pi pi-search" />
                                    </InputIcon>
                                    <InputText v-model="contentsKeyword" placeholder="标题关键词" class="w-full" @keyup.enter="onContentsSearch" />
                                </IconField>
                            </SearchField>
                            <SearchField label="状态">
                                <Select v-model="contentsStatus" :options="contentStatusOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
                            </SearchField>
                            <SearchField label="可见性">
                                <Select v-model="contentsVisibility" :options="contentVisibilityOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
                            </SearchField>
                            <SearchField label="OwnerUserID">
                                <InputNumber v-model="contentsOwnerUserID" :min="1" placeholder="精确匹配" class="w-full" />
                            </SearchField>
                            <SearchField label="发布时间 From">
                                <DatePicker v-model="contentsPublishedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                            </SearchField>
                            <SearchField label="发布时间 To">
                                <DatePicker v-model="contentsPublishedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                            </SearchField>
                            <SearchField label="创建时间 From">
                                <DatePicker v-model="contentsCreatedAtFrom" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                            </SearchField>
                            <SearchField label="创建时间 To">
                                <DatePicker v-model="contentsCreatedAtTo" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                            </SearchField>
                        </SearchPanel>

                        <DataTable
                            :value="contents"
                            dataKey="__key"
                            :loading="contentsLoading"
                            lazy
                            :paginator="true"
                            :rows="contentsRows"
                            :totalRecords="contentsTotal"
                            :first="(contentsPage - 1) * contentsRows"
                            :rowsPerPageOptions="[10, 20, 50, 100]"
                            sortMode="single"
                            :sortField="contentsSortField"
                            :sortOrder="contentsSortOrder"
                            @page="onContentsPage"
                            @sort="onContentsSort"
                            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                            scrollable
                            scrollHeight="520px"
                            responsiveLayout="scroll"
                        >
                            <Column header="ID" sortable sortField="id" style="min-width: 8rem">
                                <template #body="{ data }">
                                    <span class="text-muted-color">{{ data?.content?.id ?? '-' }}</span>
                                </template>
                            </Column>
                            <Column header="标题" sortable sortField="title" style="min-width: 22rem">
                                <template #body="{ data }">
                                    <div class="flex flex-col">
                                        <span class="font-medium truncate max-w-[520px]">{{ data?.content?.title ?? '-' }}</span>
                                        <span class="text-muted-color">ContentID: {{ data?.content?.id ?? '-' }}</span>
                                    </div>
                                </template>
                            </Column>
                            <Column header="Owner" sortable sortField="user_id" style="min-width: 14rem">
                                <template #body="{ data }">
                                    <div class="flex flex-col">
                                        <span class="font-medium">{{ data?.owner?.username ?? '-' }}</span>
                                        <span class="text-muted-color">ID: {{ data?.content?.user_id ?? '-' }}</span>
                                    </div>
                                </template>
                            </Column>
                            <Column header="状态" sortable sortField="status" style="min-width: 12rem">
                                <template #body="{ data }">
                                    <Tag :value="data?.status_description || data?.content?.status || '-'" :severity="getContentStatusSeverity(data?.content?.status)" />
                                </template>
                            </Column>
                            <Column header="可见性" sortable sortField="visibility" style="min-width: 12rem">
                                <template #body="{ data }">
                                    <Tag :value="data?.visibility_description || data?.content?.visibility || '-'" :severity="getContentVisibilitySeverity(data?.content?.visibility)" />
                                </template>
                            </Column>
                            <Column header="价格" style="min-width: 10rem">
                                <template #body="{ data }">
                                    <span v-if="data?.price && (data.price.price_amount ?? null) !== null">
                                        {{ Number(data.price.price_amount) === 0 ? '免费' : formatCny(data.price.price_amount) }}
                                    </span>
                                    <span v-else class="text-muted-color">-</span>
                                </template>
                            </Column>
                            <Column header="发布时间" sortable sortField="published_at" style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data?.content?.published_at) }}
                                </template>
                            </Column>
                            <Column header="创建时间" sortable sortField="created_at" style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data?.content?.created_at) }}
                                </template>
                            </Column>
                            <Column header="操作" style="min-width: 10rem">
                                <template #body="{ data }">
                                    <Button v-if="data?.content?.status === 'published'" label="下架" icon="pi pi-ban" severity="danger" text size="small" class="p-0" @click="openUnpublishDialog(data)" />
                                    <span v-else class="text-muted-color">-</span>
                                </template>
                            </Column>
                        </DataTable>
                    </div>
                </TabPanel>
                <TabPanel value="orders">
                    <div class="flex flex-col gap-4">
                        <SearchPanel :loading="ordersLoading" @search="onOrdersSearch" @reset="onOrdersReset">
                            <SearchField label="OrderID">
                                <InputNumber v-model="orderIDFilter" :min="1" placeholder="精确匹配" class="w-full" />
                            </SearchField>
                            <SearchField label="BuyerUserID">
                                <InputNumber v-model="buyerUserIDFilter" :min="1" placeholder="精确匹配" class="w-full" />
                            </SearchField>
                            <SearchField label="BuyerUsername">
                                <IconField>
                                    <InputIcon>
                                        <i class="pi pi-search" />
                                    </InputIcon>
                                    <InputText v-model="buyerUsernameFilter" placeholder="请输入" class="w-full" @keyup.enter="onOrdersSearch" />
                                </IconField>
                            </SearchField>
                            <SearchField label="状态">
                                <Select v-model="orderStatusFilter" :options="orderStatusOptions" optionLabel="label" optionValue="value" placeholder="请选择" class="w-full" />
                            </SearchField>
                            <SearchField label="创建时间 From">
                                <DatePicker v-model="createdAtFromFilter" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                            </SearchField>
                            <SearchField label="创建时间 To">
                                <DatePicker v-model="createdAtToFilter" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                            </SearchField>
                            <SearchField label="支付时间 From">
                                <DatePicker v-model="paidAtFromFilter" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                            </SearchField>
                            <SearchField label="支付时间 To">
                                <DatePicker v-model="paidAtToFilter" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                            </SearchField>
                        </SearchPanel>

                        <DataTable
                            :value="orders"
                            dataKey="id"
                            :loading="ordersLoading"
                            lazy
                            :paginator="true"
                            :rows="ordersRows"
                            :totalRecords="ordersTotal"
                            :first="(ordersPage - 1) * ordersRows"
                            :rowsPerPageOptions="[10, 20, 50, 100]"
                            sortMode="single"
                            :sortField="orderSortField"
                            :sortOrder="orderSortOrder"
                            @page="onOrdersPage"
                            @sort="onOrdersSort"
                            currentPageReportTemplate="显示第 {first} - {last} 条，共 {totalRecords} 条"
                            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                            scrollable
                            scrollHeight="520px"
                            responsiveLayout="scroll"
                        >
                            <Column field="id" header="ID" sortable style="min-width: 8rem">
                                <template #body="{ data }">
                                    <Button label="详情" icon="pi pi-search" text size="small" class="p-0 mr-2" as="router-link" :to="`/superadmin/orders/${data.id}`" />
                                    <span class="text-muted-color">{{ data.id }}</span>
                                </template>
                            </Column>
                            <Column header="买家" style="min-width: 14rem">
                                <template #body="{ data }">
                                    <div class="flex flex-col">
                                        <span class="font-medium">{{ data?.buyer?.username ?? '-' }}</span>
                                        <span class="text-muted-color">ID: {{ data?.buyer?.id ?? '-' }}</span>
                                    </div>
                                </template>
                            </Column>
                            <Column field="status" header="状态" sortable style="min-width: 12rem">
                                <template #body="{ data }">
                                    <Tag :value="data?.status_description || data?.status || '-'" :severity="getOrderStatusSeverity(data?.status)" />
                                </template>
                            </Column>
                            <Column field="amount_paid" header="实付" sortable style="min-width: 10rem">
                                <template #body="{ data }">
                                    {{ formatCny(data.amount_paid) }}
                                </template>
                            </Column>
                            <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data.created_at) }}
                                </template>
                            </Column>
                            <Column field="paid_at" header="支付时间" sortable style="min-width: 14rem">
                                <template #body="{ data }">
                                    {{ formatDate(data.paid_at) }}
                                </template>
                            </Column>
                        </DataTable>
                    </div>
                </TabPanel>
            </TabPanels>
        </Tabs>
    </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]">{{ tenant?.name ?? '-' }}</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" :loading="statusOptionsLoading" 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="renewDialogVisible" :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]">{{ tenant?.name ?? '-' }}</span>
            </div>
        </template>
        <div class="flex flex-col gap-4">
            <div>
                <label class="block font-medium mb-2">续期时长</label>
                <Select v-model="renewDuration" :options="durationOptions" optionLabel="label" optionValue="value" placeholder="选择时长" :disabled="renewing" fluid />
            </div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="renewDialogVisible = false" :disabled="renewing" />
            <Button label="确认" icon="pi pi-check" @click="confirmRenew" :loading="renewing" />
        </template>
    </Dialog>

    <Dialog v-model:visible="unpublishDialogVisible" :modal="true" :style="{ width: '460px' }">
        <template #header>
            <div class="flex items-center gap-2">
                <span class="font-medium">下架内容</span>
                <span class="text-muted-color truncate max-w-[280px]">{{ unpublishItem?.content?.title ?? '-' }}</span>
            </div>
        </template>
        <div class="flex flex-col gap-2">
            <div class="text-muted-color">确认将该内容下架？下架后租户端将不可见/不可购买。</div>
            <div class="text-sm text-muted-color">ContentID: {{ unpublishItem?.content?.id ?? '-' }}</div>
        </div>
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="unpublishDialogVisible = false" :disabled="unpublishLoading" />
            <Button label="确认下架" icon="pi pi-ban" severity="danger" @click="confirmUnpublish" :loading="unpublishLoading" />
        </template>
    </Dialog>
</template>
