<script setup>
import SearchField from '@/components/SearchField.vue';
import SearchPanel from '@/components/SearchPanel.vue';
import StatisticsStrip from '@/components/StatisticsStrip.vue';
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 username = ref('');
const status = ref('');
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 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 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;
    }
}

async function loadUsers() {
    loading.value = true;
    try {
        const result = await UserService.listUsers({
            page: page.value,
            limit: rows.value,
            username: username.value,
            status: status.value,
            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() {
    username.value = '';
    status.value = '';
    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();
}

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="用户名">
                    <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="statusOptions" optionLabel="label" optionValue="value" placeholder="请选择" :loading="statusOptionsLoading" 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: 14rem" />
                <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 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>
    </div>
</template>
