<script setup>
import StatisticsStrip from '@/components/StatisticsStrip.vue';
import { OrderService } from '@/service/OrderService';
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 tenantTotal = ref(null);
const tenantLoading = ref(false);

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

const orderStats = ref(null);
const orderStatsLoading = ref(false);

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);
}

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: 'users-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)
        }))
    ];
});

const tenantItems = computed(() => [
    {
        key: 'tenants-total',
        label: '租户总数：',
        value: tenantLoading.value ? '-' : (tenantTotal.value ?? '-'),
        icon: 'pi-building'
    }
]);

const orderItems = computed(() => {
    const byStatus = new Map((orderStats.value?.by_status || []).map((row) => [row?.status, row]));
    const getCount = (status) => byStatus.get(status)?.count ?? 0;

    const totalCount = orderStats.value?.total_count ?? 0;
    const totalAmountPaidSum = orderStats.value?.total_amount_paid_sum ?? 0;
    const refundingCount = getCount('refunding');
    const refundedCount = getCount('refunded');
    const refundRequestedCount = refundingCount + refundedCount;

    return [
        { key: 'orders-total', label: '订单总数：', value: orderStatsLoading.value ? '-' : totalCount, icon: 'pi-shopping-cart' },
        { key: 'orders-paid', label: '已支付：', value: orderStatsLoading.value ? '-' : getCount('paid'), icon: 'pi-check-circle' },
        { key: 'orders-refunding', label: '退款中：', value: orderStatsLoading.value ? '-' : refundingCount, icon: 'pi-spin pi-spinner' },
        { key: 'orders-refund-requested', label: '退款申请：', value: orderStatsLoading.value ? '-' : refundRequestedCount, icon: 'pi-undo' },
        { key: 'orders-refunded', label: '已退款：', value: orderStatsLoading.value ? '-' : getCount('refunded'), icon: 'pi-undo' },
        { key: 'orders-amount', label: '实付总额：', value: orderStatsLoading.value ? '-' : formatCny(totalAmountPaidSum), icon: 'pi-wallet' }
    ];
});

async function loadTenantTotal() {
    tenantLoading.value = true;
    try {
        const result = await TenantService.listTenants({ page: 1, limit: 10 });
        tenantTotal.value = result?.total ?? 0;
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载租户信息', life: 4000 });
    } finally {
        tenantLoading.value = false;
    }
}

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 loadOrderStatistics() {
    orderStatsLoading.value = true;
    try {
        orderStats.value = await OrderService.getOrderStatistics();
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载订单统计信息', life: 4000 });
    } finally {
        orderStatsLoading.value = false;
    }
}

onMounted(() => {
    loadTenantTotal();
    loadStatistics();
    loadOrderStatistics();
});
</script>

<template>
    <div>
        <StatisticsStrip :items="tenantItems" containerClass="card mb-4" />
        <StatisticsStrip :items="orderItems" containerClass="card mb-4" />
        <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>
            <div class="flex flex-wrap gap-2">
                <Button label="租户管理" icon="pi pi-building" as="router-link" to="/superadmin/tenants" />
                <Button label="用户管理" icon="pi pi-users" as="router-link" to="/superadmin/users" severity="secondary" />
            </div>
        </div>
    </div>
</template>
