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

const toast = useToast();

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

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

const keyword = ref('');
const status = 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';
    }
}

function getExpiryDaysInfo(expiredAt) {
    if (!expiredAt) return { daysLeft: null, tooltipText: '未设置过期时间', textClass: '' };
    const expiredDate = new Date(expiredAt);
    if (Number.isNaN(expiredDate.getTime())) return { daysLeft: null, tooltipText: String(expiredAt), textClass: '' };

    const msPerDay = 24 * 60 * 60 * 1000;
    const deltaDays = Math.ceil((expiredDate.getTime() - Date.now()) / msPerDay);
    const isExpired = deltaDays < 0;
    const daysAbs = Math.abs(deltaDays);
    const tooltipText = isExpired ? `已过期 ${daysAbs} 天` : `剩余 ${deltaDays} 天`;

    let textClass = '';
    if (isExpired) textClass = 'text-red-500';
    else if (deltaDays < 10) textClass = 'text-red-500';
    else if (deltaDays < 30) textClass = 'text-orange-500';

    return { daysLeft: deltaDays, tooltipText, textClass };
}

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

const renewDialogVisible = ref(false);
const renewing = ref(false);
const renewTenant = ref(null);
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 }
];

function openRenewDialog(item) {
    renewTenant.value = item;
    renewDuration.value = 30;
    renewDialogVisible.value = true;
}

const tenantStatusDialogVisible = ref(false);
const tenantStatusOptionsLoading = ref(false);
const tenantStatusUpdating = ref(false);
const tenantStatusOptions = ref([]);
const tenantStatusTenant = ref(null);
const tenantStatusValue = ref(null);

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

async function openTenantStatusDialog(tenant) {
    tenantStatusTenant.value = tenant;
    tenantStatusValue.value = tenant?.status ?? null;
    tenantStatusDialogVisible.value = true;

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

async function confirmUpdateTenantStatus() {
    const tenantID = tenantStatusTenant.value?.id;
    if (!tenantID || !tenantStatusValue.value) return;

    tenantStatusUpdating.value = true;
    try {
        await TenantService.updateTenantStatus({ tenantID, status: tenantStatusValue.value });
        toast.add({ severity: 'success', summary: '更新成功', detail: `TenantID: ${tenantID}`, life: 3000 });
        tenantStatusDialogVisible.value = false;
        await loadTenants();
    } catch (error) {
        toast.add({ severity: 'error', summary: '更新失败', detail: error?.message || '无法更新租户状态', life: 4000 });
    } finally {
        tenantStatusUpdating.value = false;
    }
}

async function confirmRenew() {
    const tenantID = renewTenant.value?.id;
    if (!tenantID) return;

    renewing.value = true;
    try {
        await TenantService.renewTenantExpire({ tenantID, duration: renewDuration.value });
        toast.add({ severity: 'success', summary: '续期成功', detail: `TenantID: ${tenantID}`, life: 3000 });
        renewDialogVisible.value = false;
        await loadTenants();
    } catch (error) {
        toast.add({ severity: 'error', summary: '续期失败', detail: error?.message || '无法续期', life: 4000 });
    } finally {
        renewing.value = false;
    }
}

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

<template>
    <div>
        <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="名称 / Code">
                    <IconField>
                        <InputIcon>
                            <i class="pi pi-search" />
                        </InputIcon>
                        <InputText v-model="keyword" placeholder="请输入" class="w-full" @keyup.enter="onSearch" />
                    </IconField>
                </SearchField>
                <SearchField label="状态">
                    <Select v-model="status" :options="tenantStatusOptions" optionLabel="label" optionValue="value" placeholder="请选择" :loading="tenantStatusOptionsLoading" class="w-full" />
                </SearchField>
            </SearchPanel>

            <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="code" header="Code" style="min-width: 10rem" />
                <Column field="name" header="名称" sortable style="min-width: 14rem" />
                <Column field="status_description" header="状态" style="min-width: 10rem">
                    <template #body="{ data }">
                        <Tag :value="data.status_description || data.status || '-'" :severity="getStatusSeverity(data.status)" class="cursor-pointer" @click="openTenantStatusDialog(data)" />
                    </template>
                </Column>
                <Column field="user_count" header="用户数" sortable style="min-width: 8rem" />
                <Column field="user_balance" header="余额" sortable style="min-width: 8rem" />
                <Column field="expired_at" header="过期时间" sortable style="min-width: 14rem">
                    <template #body="{ data }">
                        <span v-if="data.expired_at" v-tooltip="getExpiryDaysInfo(data.expired_at).tooltipText" :class="getExpiryDaysInfo(data.expired_at).textClass">
                            {{ formatDate(data.expired_at) }}
                        </span>
                        <span v-else>-</span>
                    </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>
                <Column header="操作" :exportable="false" style="min-width: 10rem">
                    <template #body="{ data }">
                        <Button label="续期" icon="pi pi-refresh" size="small" severity="secondary" @click="openRenewDialog(data)" />
                    </template>
                </Column>
            </DataTable>
        </div>

        <Dialog v-model:visible="renewDialogVisible" :modal="true" :style="{ width: '420px' }">
            <template #header>
                <div class="flex items-center gap-2">
                    <span class="font-medium">为【 {{ renewTenant?.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="选择续期时长" 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="tenantStatusDialogVisible" :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]">{{ tenantStatusTenant?.name ?? '-' }}</span>
                </div>
            </template>
            <div class="flex flex-col gap-4">
                <div>
                    <label class="block font-medium mb-2">租户状态</label>
                    <Select v-model="tenantStatusValue" :options="tenantStatusOptions" optionLabel="label" optionValue="value" placeholder="选择状态" :disabled="tenantStatusUpdating" fluid />
                </div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" text @click="tenantStatusDialogVisible = false" :disabled="tenantStatusUpdating" />
                <Button label="确认" icon="pi pi-check" @click="confirmUpdateTenantStatus" :loading="tenantStatusUpdating" :disabled="!tenantStatusValue" />
            </template>
        </Dialog>
    </div>
</template>
