<script setup>
import { TenantService } from '@/service/TenantService';
import { onMounted, ref } from 'vue';
import { useToast } from 'primevue/usetoast';

const toast = useToast();

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

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

const name = ref('');
const sortField = ref('id');
const sortOrder = ref(-1);

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

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

async function loadTenants() {
    loading.value = true;
    try {
        const result = await TenantService.listTenants({
            page: page.value,
            limit: rows.value,
            name: name.value,
            sortField: sortField.value,
            sortOrder: sortOrder.value
        });
        tenants.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;
    loadTenants();
}

function onReset() {
    name.value = '';
    sortField.value = 'id';
    sortOrder.value = -1;
    page.value = 1;
    rows.value = 10;
    loadTenants();
}

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

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

onMounted(() => {
    loadTenants();
});
</script>

<template>
    <div>
        <div class="card">
            <div class="flex flex-wrap items-center justify-between gap-3 mb-4">
                <div class="flex items-center gap-2">
                    <h4 class="m-0">租户列表</h4>
                    <Tag :value="`总数：${totalRecords}`" severity="secondary" />
                </div>
                <div class="flex flex-wrap items-center gap-2">
                    <IconField>
                        <InputIcon>
                            <i class="pi pi-search" />
                        </InputIcon>
                        <InputText v-model="name" placeholder="按名称搜索" @keyup.enter="onSearch" />
                    </IconField>
                    <Button label="查询" icon="pi pi-search" severity="secondary" @click="onSearch" />
                    <Button label="重置" icon="pi pi-refresh" severity="secondary" @click="onReset" />
                </div>
            </div>

            <DataTable
                :value="tenants"
                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="uuid" header="UUID" style="min-width: 14rem" />
                <Column field="code" header="Code" style="min-width: 10rem" />
                <Column field="name" header="名称" sortable style="min-width: 14rem" />
                <Column field="status" header="状态" sortable style="min-width: 10rem">
                    <template #body="{ data }">
                        <Tag :value="data.status || '-'" :severity="getStatusSeverity(data.status)" />
                    </template>
                </Column>
                <Column field="userCount" header="用户数" sortable style="min-width: 8rem" />
                <Column field="userBalance" header="余额" sortable style="min-width: 8rem" />
                <Column field="created_at" header="创建时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data.created_at) }}
                    </template>
                </Column>
                <Column field="expired_at" header="过期时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data.expired_at) }}
                    </template>
                </Column>
                <Column field="updated_at" header="更新时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        {{ formatDate(data.updated_at) }}
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>
</template>
