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

const toast = useToast();

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

const tenantID = ref(null);
const startAt = ref(null);
const endAt = ref(null);
const granularity = ref('day');

const granularityOptions = [{ label: '按天', value: 'day' }];

function formatPercent(value) {
    const rate = Number(value);
    if (!Number.isFinite(rate)) return '-';
    return `${(rate * 100).toFixed(2)}%`;
}

function formatCnyFromYuan(amount) {
    const value = Number(amount);
    if (!Number.isFinite(value)) return '-';
    return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(value);
}

const summaryItems = computed(() => {
    const summary = overview.value?.summary;
    if (!summary) return [];

    return [
        { key: 'views', label: '累计曝光：', value: summary.total_views ?? 0, icon: 'pi-eye' },
        { key: 'paid-orders', label: '已支付订单：', value: summary.paid_orders ?? 0, icon: 'pi-shopping-cart' },
        { key: 'paid-amount', label: '已支付金额：', value: formatCnyFromYuan(summary.paid_amount), icon: 'pi-wallet' },
        { key: 'refund-orders', label: '退款订单：', value: summary.refund_orders ?? 0, icon: 'pi-undo' },
        { key: 'refund-amount', label: '退款金额：', value: formatCnyFromYuan(summary.refund_amount), icon: 'pi-replay' },
        { key: 'conversion', label: '转化率：', value: formatPercent(summary.conversion_rate), icon: 'pi-percentage' }
    ];
});

async function loadOverview() {
    loading.value = true;
    try {
        overview.value = await ReportService.getOverview({
            tenant_id: tenantID.value || undefined,
            start_at: startAt.value || undefined,
            end_at: endAt.value || undefined,
            granularity: granularity.value
        });
    } catch (error) {
        toast.add({ severity: 'error', summary: '加载失败', detail: error?.message || '无法加载报表数据', life: 4000 });
    } finally {
        loading.value = false;
    }
}

function onSearch() {
    loadOverview();
}

function onReset() {
    tenantID.value = null;
    startAt.value = null;
    endAt.value = null;
    granularity.value = 'day';
    loadOverview();
}

async function exportReport() {
    try {
        const res = await ReportService.exportReport({
            tenant_id: tenantID.value || undefined,
            start_at: startAt.value || undefined,
            end_at: endAt.value || undefined,
            granularity: granularity.value,
            format: 'csv'
        });
        const content = res?.content ?? '';
        const filename = res?.filename || 'report.csv';
        const blob = new Blob([content], { type: res?.mime_type || 'text/csv' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        link.click();
        URL.revokeObjectURL(url);
        toast.add({ severity: 'success', summary: '导出成功', detail: filename, life: 3000 });
    } catch (error) {
        toast.add({ severity: 'error', summary: '导出失败', detail: error?.message || '无法导出报表', life: 4000 });
    }
}

loadOverview();
</script>

<template>
    <div>
        <div class="card">
            <div class="flex items-center justify-between mb-4">
                <h4 class="m-0">运营报表</h4>
                <Button label="导出 CSV" icon="pi pi-download" severity="secondary" :loading="loading" @click="exportReport" />
            </div>

            <SearchPanel :loading="loading" @search="onSearch" @reset="onReset">
                <SearchField label="TenantID">
                    <InputNumber v-model="tenantID" :min="1" placeholder="不填则全平台" class="w-full" />
                </SearchField>
                <SearchField label="开始时间">
                    <DatePicker v-model="startAt" showIcon showButtonBar placeholder="开始时间" class="w-full" />
                </SearchField>
                <SearchField label="结束时间">
                    <DatePicker v-model="endAt" showIcon showButtonBar placeholder="结束时间" class="w-full" />
                </SearchField>
                <SearchField label="统计粒度">
                    <Select v-model="granularity" :options="granularityOptions" optionLabel="label" optionValue="value" class="w-full" />
                </SearchField>
            </SearchPanel>
        </div>

        <StatisticsStrip v-if="summaryItems.length" :items="summaryItems" containerClass="card mb-4" />

        <div class="card">
            <div class="flex items-center justify-between mb-4">
                <h4 class="m-0">趋势明细</h4>
            </div>
            <DataTable :value="overview?.items || []" :loading="loading" scrollable scrollHeight="420px" responsiveLayout="scroll">
                <Column field="date" header="日期" style="min-width: 10rem" />
                <Column field="paid_orders" header="已支付订单" style="min-width: 10rem" />
                <Column field="paid_amount" header="已支付金额" style="min-width: 12rem">
                    <template #body="{ data }">
                        {{ formatCnyFromYuan(data.paid_amount) }}
                    </template>
                </Column>
                <Column field="refund_orders" header="退款订单" style="min-width: 10rem" />
                <Column field="refund_amount" header="退款金额" style="min-width: 12rem">
                    <template #body="{ data }">
                        {{ formatCnyFromYuan(data.refund_amount) }}
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>
</template>
