<template>
    <div class="statistics-container">
        <!-- 头部 -->
        <el-card class="header-card" shadow="never">
            <div class="header-content">
                <h1>系统数据统计</h1>
                <div class="header-actions">
                    <!-- <el-button type="primary" @click="exportData">导出数据</el-button> -->
                    <el-button @click="refreshData" :loading="loading.all">刷新</el-button>
                </div>
            </div>
        </el-card>

        <!-- 时间筛选 -->
        <el-card class="filter-card" shadow="never">
            <el-form :inline="true" :model="filterForm" class="filter-form">
                <el-form-item label="统计时间">
                    <el-date-picker
                        v-model="filterForm.dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                        :shortcuts="shortcuts"
                        @change="handleDateChange"
                    />
                </el-form-item>

                <el-form-item label="时间范围">
                    <el-select
                        v-model="filterForm.timeType"
                        placeholder="请选择"
                        @change="handleTimeTypeChange"
                    >
                        <el-option label="今天" value="today" />
                        <el-option label="昨天" value="yesterday" />
                        <el-option label="本周" value="week" />
                        <el-option label="本月" value="month" />
                        <!-- <el-option label="本年" value="year" /> -->
                        <!-- <el-option label="自定义" value="custom" /> -->
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="loadData" :loading="loading.all">
                        查询
                    </el-button>
                    <el-button @click="resetFilter">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 统计数据卡片 -->
        <div class="stats-grid">
            <el-card
                v-for="(stat, index) in statsData"
                :key="index"
                class="stat-card"
                shadow="hover"
                :body-style="{ padding: '20px' }"
            >
                <div class="stat-item">
                    <div class="stat-label">{{ stat.label }}</div>
                    <div class="stat-value">
                        <span :style="{ color: stat.color || '#1890ff' }">
                            {{ stat.prefix || '' }}{{ stat.value }}{{ stat.suffix || '' }}
                        </span>
                    </div>
                    <div v-if="stat.trend" class="stat-trend">
                        <el-tag
                            :type="stat.trendType || 'success'"
                            size="small"
                            :icon="stat.trendIcon"
                        >
                            {{ stat.trend }}
                        </el-tag>
                    </div>
                    <div class="stat-icon">
                        <el-icon :size="24" :color="stat.iconColor || '#409EFF'">
                            <component :is="stat.icon" />
                        </el-icon>
                    </div>
                </div>
            </el-card>
        </div>

        <!-- 图表区域 -->
        <el-row :gutter="20" class="chart-row">
            <el-col :span="12">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span>用户增长趋势</span>
                            <el-select
                                v-model="userChartType"
                                size="small"
                                style="width: 100px"
                                @change="renderUserChart"
                            >
                                <el-option label="折线图" value="line" />
                                <el-option label="柱状图" value="bar" />
                            </el-select>
                        </div>
                    </template>
                    <div
                        v-if="!chartData.userGrowth || chartData.userGrowth.length === 0"
                        class="empty-chart"
                    >
                        <el-empty description="暂无数据" :image-size="100" />
                    </div>
                    <div v-else ref="userChart" class="chart-container"></div>
                </el-card>
            </el-col>

            <el-col :span="12">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span>订单统计</span>
                            <el-select
                                v-model="orderChartType"
                                size="small"
                                style="width: 100px"
                                @change="renderOrderChart"
                            >
                                <el-option label="组合图" value="combo" />
                                <el-option label="柱状图" value="bar" />
                                <el-option label="折线图" value="line" />
                            </el-select>
                        </div>
                    </template>
                    <div
                        v-if="!chartData.orderStats || chartData.orderStats.length === 0"
                        class="empty-chart"
                    >
                        <el-empty description="暂无数据" :image-size="100" />
                    </div>
                    <div v-else ref="orderChart" class="chart-container"></div>
                </el-card>
            </el-col>
        </el-row>

        <el-row :gutter="20" class="chart-row">
            <el-col :span="12">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span>订单状态分布</span>
                        </div>
                    </template>
                    <div v-if="!chartData.orderStatus || !hasOrderStatusData" class="empty-chart">
                        <el-empty description="暂无数据" :image-size="100" />
                    </div>
                    <div v-else ref="orderStatusChart" class="chart-container"></div>
                </el-card>
            </el-col>

            <el-col :span="12">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span>积分变更类型</span>
                        </div>
                    </template>
                    <div
                        v-if="!chartData.pointsChange || chartData.pointsChange.length === 0"
                        class="empty-chart"
                    >
                        <el-empty description="暂无数据" :image-size="100" />
                    </div>
                    <div v-else ref="pointsChart" class="chart-container"></div>
                </el-card>
            </el-col>
        </el-row>

        <el-row>
            <el-col :span="24">
                <el-card class="chart-card" shadow="hover">
                    <template #header>
                        <div class="chart-header">
                            <span>销售额趋势</span>
                            <el-select
                                v-model="salesChartType"
                                size="small"
                                style="width: 100px"
                                @change="renderSalesChart"
                            >
                                <el-option label="面积图" value="area" />
                                <el-option label="折线图" value="line" />
                            </el-select>
                        </div>
                    </template>
                    <div
                        v-if="!chartData.orderStats || chartData.orderStats.length === 0"
                        class="empty-chart"
                    >
                        <el-empty description="暂无数据" :image-size="100" />
                    </div>
                    <div v-else ref="salesChart" class="chart-container"></div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 实时订单表格 -->
        <el-card class="table-card" shadow="hover">
            <template #header>
                <div class="table-header">
                    <span>实时订单</span>
                    <el-button type="text" @click="loadRecentOrders" :loading="loading.orders">
                        刷新
                    </el-button>
                </div>
            </template>
            <el-table
                :data="recentOrders"
                v-loading="loading.orders"
                style="width: 100%"
                empty-text="暂无订单数据"
            >
                <el-table-column prop="orderNo" label="订单号" align="center">
                    <template #default="{ row }">
                        <el-tag type="info">{{ row.orderNo }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="用户名" align="center" />
                <el-table-column prop="payAmount" label="金额" align="center">
                    <template #default="{ row }">¥{{ formatNumber(row.payAmount, 2) }}</template>
                </el-table-column>
                <el-table-column prop="statusText" label="状态" align="center">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTagType(row.status)" size="small">
                            {{ row.statusText }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" align="center" />
                <!-- <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <el-button type="text" size="small" @click="viewOrderDetail(row)">
                            查看
                        </el-button>
                    </template>
                </el-table-column> -->
            </el-table>
            <div>
                <pagination
                    v-show="page.total > 0"
                    :total="page.total"
                    v-model:page="page.current"
                    v-model:limit="page.size"
                    @pagination="loadRecentOrders"
                />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed, watch } from 'vue';
import * as echarts from 'echarts';
import { ElMessage, ElLoading, ElEmpty } from 'element-plus';
import {
    User,
    ShoppingCart,
    Money,
    TrendCharts,
    Goods,
    Present,
    VideoCamera,
    ChatLineSquare,
} from '@element-plus/icons-vue';
import { statisticsStats, statisticsCharts, statisticsOrders } from '@/api/service/statistics';

// 响应式数据
const filterForm = ref({
    dateRange: [],
    timeType: 'week',
});

const shortcuts = [
    {
        text: '最近一周',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
    {
        text: '最近一个月',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
        },
    },
    {
        text: '最近三个月',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
        },
    },
];

// 统计数据卡片
const statsData = ref([
    { label: '总用户数', value: 0, icon: User, color: '#1890ff' },
    {
        label: '今日新增',
        value: 0,
        icon: TrendCharts,
        color: '#52c41a',
        trend: '0.0%',
        trendType: 'info',
    },
    { label: '总订单数', value: 0, icon: ShoppingCart, color: '#722ed1' },
    {
        label: '今日订单',
        value: 0,
        icon: Goods,
        color: '#fa8c16',
        trend: '0.0%',
        trendType: 'info',
    },
    { label: '总销售额', value: 0, prefix: '¥', icon: Money, color: '#13c2c2' },
    { label: '今日销售额', value: 0, prefix: '¥', icon: Present, color: '#f5222d' },
    { label: '直播中', value: 0, icon: VideoCamera, color: '#eb2f96' },
    { label: '活跃群组', value: 0, icon: ChatLineSquare, color: '#faad14' },
]);

// 图表相关
const userChart = ref(null);
const orderChart = ref(null);
const orderStatusChart = ref(null);
const pointsChart = ref(null);
const salesChart = ref(null);

let userChartInstance = null;
let orderChartInstance = null;
let orderStatusChartInstance = null;
let pointsChartInstance = null;
let salesChartInstance = null;

// 图表类型
const userChartType = ref('line');
const orderChartType = ref('combo');
const salesChartType = ref('area');

// 图表数据
const chartData = ref({
    userGrowth: [],
    orderStats: [],
    orderStatus: {},
    pointsChange: [],
});

// 计算属性：检查订单状态是否有数据
const hasOrderStatusData = computed(() => {
    const status = chartData.value.orderStatus;
    if (!status) return false;
    return (
        (status.pendingPayment || 0) > 0 ||
        (status.paid || 0) > 0 ||
        (status.shipped || 0) > 0 ||
        (status.completed || 0) > 0 ||
        (status.cancelled || 0) > 0 ||
        (status.refunded || 0) > 0
    );
});

// 表格数据
const recentOrders = ref([]);
const loading = ref({
    all: false,
    stats: false,
    charts: false,
    orders: false,
});

const page = ref({
    current: 1,
    size: 10,
    total: 0,
});

// 调试函数，检查数据结构
function debugData(label, data) {
    console.log(`=== ${label} ===`);
    console.log('数据类型:', typeof data);
    if (Array.isArray(data)) {
        console.log('数组长度:', data.length);
        console.log('数组内容:', data);
    } else if (data && typeof data === 'object') {
        console.log('对象keys:', Object.keys(data));
        console.log('对象内容:', data);
    } else {
        console.log('数据:', data);
    }
}

// 初始化日期
function initDateRange() {
    const end = new Date();
    const start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    filterForm.value.dateRange = [
        start.toISOString().split('T')[0],
        end.toISOString().split('T')[0],
    ];
}

// 处理日期变化
function handleDateChange() {
    filterForm.value.timeType = 'custom';
}

// 处理时间类型变化
function handleTimeTypeChange(value) {
    const today = new Date();
    const end = new Date(today);
    let start = new Date(today);

    switch (value) {
        case 'today':
            start = new Date(today);
            break;
        case 'yesterday':
            start.setDate(today.getDate() - 1);
            end.setDate(today.getDate() - 1);
            break;
        case 'week':
            start.setDate(today.getDate() - 6);
            break;
        case 'month':
            start.setDate(1);
            break;
        case 'year':
            start.setMonth(0, 1);
            break;
        case 'custom':
            return;
    }

    filterForm.value.dateRange = [
        start.toISOString().split('T')[0],
        end.toISOString().split('T')[0],
    ];

    loadData();
}

// 重置筛选
function resetFilter() {
    filterForm.value.timeType = 'week';
    initDateRange();
    loadData();
}

// 加载统计数据
async function loadStatsData() {
    loading.value.stats = true;
    try {
        const params = {
            startDate: filterForm.value.dateRange[0],
            endDate: filterForm.value.dateRange[1],
        };

        const response = await statisticsStats(params);
        const data = response.data || {};

        // 更新统计数据
        statsData.value[0].value = data.totalUsers || 0;
        statsData.value[1].value = data.todayNewUsers || 0;
        statsData.value[2].value = data.totalOrders || 0;
        statsData.value[3].value = data.todayOrders || 0;
        statsData.value[4].value = formatNumber(data.totalSales || 0, 2);
        statsData.value[5].value = formatNumber(data.todaySales || 0, 2);
        statsData.value[6].value = data.liveCount || 0;
        statsData.value[7].value = data.groupCount || 0;

        // 更新趋势
        if (data.userTrend) {
            statsData.value[1].trend = data.userTrend;
            const isPositive = data.userTrend.toString().startsWith('+');
            statsData.value[1].trendType = isPositive ? 'success' : 'danger';
        } else {
            statsData.value[1].trend = '0.0%';
            statsData.value[1].trendType = 'info';
        }

        if (data.orderTrend) {
            statsData.value[3].trend = data.orderTrend;
            const isPositive = data.orderTrend.toString().startsWith('+');
            statsData.value[3].trendType = isPositive ? 'success' : 'danger';
        } else {
            statsData.value[3].trend = '0.0%';
            statsData.value[3].trendType = 'info';
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
        ElMessage.error('加载统计数据失败');
        // 清空统计数据
        resetStatsData();
    } finally {
        loading.value.stats = false;
    }
}

// 清空统计数据
function resetStatsData() {
    statsData.value.forEach(stat => {
        stat.value = 0;
        if (stat.trend) {
            stat.trend = '0.0%';
            stat.trendType = 'info';
        }
    });
}

// 加载图表数据
async function loadChartsData() {
    loading.value.charts = true;
    try {
        const params = {
            startDate: filterForm.value.dateRange[0] + ' 00:00:00',
            endDate: filterForm.value.dateRange[1] + ' 23:59:59',
        };

        const response = await statisticsCharts(params);
        const data = response.data || {};

        // 调试：检查返回的数据结构
        debugData('图表接口返回数据', data);

        // 更新图表数据
        chartData.value = {
            userGrowth: data.userGrowth || [],
            orderStats: data.orderStats || [],
            orderStatus: data.orderStatus || {},
            pointsChange: data.pointsChange || [],
        };

        // 调试：检查处理后的图表数据
        debugData('处理后的图表数据', chartData.value);

        // 等待DOM更新后渲染图表
        await nextTick();

        // 如果有数据则渲染图表
        if (data.userGrowth && data.userGrowth.length > 0) {
            renderUserChartData(data.userGrowth);
        } else {
            clearChart(userChartInstance);
        }

        if (data.orderStats && data.orderStats.length > 0) {
            renderOrderChartData(data.orderStats);
        } else {
            clearChart(orderChartInstance);
        }

        if (data.orderStatus && hasOrderStatusData.value) {
            renderOrderStatusChartData(data.orderStatus);
        } else {
            clearChart(orderStatusChartInstance);
        }

        if (data.pointsChange && data.pointsChange.length > 0) {
            renderPointsChartData(data.pointsChange);
        } else {
            clearChart(pointsChartInstance);
        }

        if (data.orderStats && data.orderStats.length > 0) {
            renderSalesChartData(data.orderStats);
        } else {
            clearChart(salesChartInstance);
        }
    } catch (error) {
        console.error('加载图表数据失败:', error);
        // 清空图表数据
        clearAllCharts();
    } finally {
        loading.value.charts = false;
    }
}

// 清空图表
function clearChart(chartInstance) {
    if (chartInstance) {
        chartInstance.clear();
    }
}

// 清空所有图表
function clearAllCharts() {
    clearChart(userChartInstance);
    clearChart(orderChartInstance);
    clearChart(orderStatusChartInstance);
    clearChart(pointsChartInstance);
    clearChart(salesChartInstance);
    chartData.value = {
        userGrowth: [],
        orderStats: [],
        orderStatus: {},
        pointsChange: [],
    };
}

// 加载最近订单
async function loadRecentOrders() {
    loading.value.orders = true;
    try {
        const params = {
            pageNum: page.value.current,
            pageSize: page.value.size,
        };

        const response = await statisticsOrders(params);
        const data = response.rows || {};

        // 调试：检查订单数据
        // debugData('订单接口返回数据', data);

        recentOrders.value = data || data || [];
        page.value.total = response.total || 0;

        // 调试：检查处理后的订单数据
        console.log('处理后的订单数据:', recentOrders.value);
    } catch (error) {
        console.error('加载订单数据失败:', error);
        ElMessage.error('加载订单数据失败');
        recentOrders.value = [];
        page.value.total = 0;
    } finally {
        loading.value.orders = false;
    }
}

// 初始化图表实例
function initChartInstance(chartRef, instance) {
    if (!instance && chartRef.value) {
        try {
            return echarts.init(chartRef.value);
        } catch (error) {
            console.error('初始化图表失败:', error);
            console.error('图表DOM元素:', chartRef.value);
            return null;
        }
    }
    return instance;
}

// 渲染用户增长图表
function renderUserChartData(data) {
    console.log('开始渲染用户增长图表，数据:', data);

    if (!data || data.length === 0 || !userChart.value) {
        console.log('用户增长图表数据为空或DOM未就绪');
        if (userChartInstance) {
            userChartInstance.clear();
        }
        return;
    }

    const dates = data.map(item => item.date || '');
    const values = data.map(item => item.count || 0);

    console.log('用户增长图表数据:', { dates, values });

    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>新增用户: {c}人',
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            boundaryGap: userChartType.value === 'line',
            data: dates,
        },
        yAxis: {
            type: 'value',
            name: '人数',
        },
        series: [
            {
                name: '新增用户',
                type: userChartType.value,
                data: values,
                smooth: true,
                lineStyle: {
                    width: 3,
                },
                areaStyle:
                    userChartType.value === 'line'
                        ? {
                              opacity: 0.1,
                          }
                        : null,
                symbolSize: 8,
                itemStyle: {
                    color: '#1890ff',
                },
            },
        ],
    };

    userChartInstance = initChartInstance(userChart, userChartInstance);
    if (userChartInstance) {
        userChartInstance.setOption(option);
        console.log('用户增长图表渲染成功');
    } else {
        console.error('用户增长图表实例初始化失败');
    }
}

// 渲染订单统计图表
function renderOrderChartData(data) {
    console.log('开始渲染订单统计图表，数据:', data);

    if (!data || data.length === 0 || !orderChart.value) {
        console.log('订单统计图表数据为空或DOM未就绪');
        if (orderChartInstance) {
            orderChartInstance.clear();
        }
        return;
    }

    const dates = data.map(item => item.date || '');
    const orderCounts = data.map(item => item.orderCount || 0);
    const salesAmounts = data.map(item => item.salesAmount || 0);

    console.log('订单统计图表数据:', { dates, orderCounts, salesAmounts });

    let option;

    if (orderChartType.value === 'combo') {
        option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                },
            },
            legend: {
                data: ['订单数', '销售额'],
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true,
            },
            xAxis: {
                type: 'category',
                data: dates,
            },
            yAxis: [
                {
                    type: 'value',
                    name: '订单数',
                    position: 'left',
                },
                {
                    type: 'value',
                    name: '销售额',
                    position: 'right',
                    axisLabel: {
                        formatter: '¥{value}',
                    },
                },
            ],
            series: [
                {
                    name: '订单数',
                    type: 'bar',
                    data: orderCounts,
                    yAxisIndex: 0,
                    barWidth: '60%',
                    itemStyle: {
                        color: '#1890ff',
                    },
                },
                {
                    name: '销售额',
                    type: 'line',
                    data: salesAmounts,
                    yAxisIndex: 1,
                    smooth: true,
                    lineStyle: {
                        width: 3,
                    },
                    symbolSize: 8,
                    itemStyle: {
                        color: '#52c41a',
                    },
                },
            ],
        };
    } else {
        const isLineChart = orderChartType.value === 'line';
        option = {
            tooltip: {
                trigger: 'axis',
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true,
            },
            xAxis: {
                type: 'category',
                data: dates,
            },
            yAxis: {
                type: 'value',
                name: isLineChart ? '销售额(元)' : '订单数',
            },
            series: [
                {
                    name: isLineChart ? '销售额' : '订单数',
                    type: orderChartType.value,
                    data: isLineChart ? salesAmounts : orderCounts,
                    smooth: true,
                    lineStyle: {
                        width: 3,
                    },
                    areaStyle: isLineChart
                        ? {
                              opacity: 0.1,
                          }
                        : null,
                    symbolSize: 8,
                    itemStyle: {
                        color: isLineChart ? '#52c41a' : '#1890ff',
                    },
                },
            ],
        };
    }

    orderChartInstance = initChartInstance(orderChart, orderChartInstance);
    if (orderChartInstance) {
        orderChartInstance.setOption(option);
        console.log('订单统计图表渲染成功');
    } else {
        console.error('订单统计图表实例初始化失败');
    }
}

// 渲染订单状态分布图表
function renderOrderStatusChartData(data) {
    console.log('开始渲染订单状态图表，数据:', data);

    if (!data || !orderStatusChart.value) {
        console.log('订单状态图表数据为空或DOM未就绪');
        if (orderStatusChartInstance) {
            orderStatusChartInstance.clear();
        }
        return;
    }

    const statusData = [
        { name: '待支付', value: data.pendingPayment || 0 },
        { name: '已支付', value: data.paid || 0 },
        { name: '已发货', value: data.shipped || 0 },
        { name: '已完成', value: data.completed || 0 },
        { name: '已取消', value: data.cancelled || 0 },
        { name: '已退款', value: data.refunded || 0 },
    ];

    console.log('订单状态数据:', statusData);

    // 过滤掉值为0的数据
    const filteredData = statusData.filter(item => item.value > 0);

    if (filteredData.length === 0) {
        console.log('订单状态数据全部为0');
        if (orderStatusChartInstance) {
            orderStatusChartInstance.clear();
        }
        return;
    }

    console.log('过滤后的订单状态数据:', filteredData);

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: filteredData.map(item => item.name),
        },
        series: [
            {
                name: '订单状态',
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2,
                },
                label: {
                    show: false,
                    position: 'center',
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: 20,
                        fontWeight: 'bold',
                    },
                },
                labelLine: {
                    show: false,
                },
                data: filteredData,
                color: ['#ff4d4f', '#52c41a', '#1890ff', '#722ed1', '#fa8c16', '#13c2c2'],
            },
        ],
    };

    orderStatusChartInstance = initChartInstance(orderStatusChart, orderStatusChartInstance);
    if (orderStatusChartInstance) {
        orderStatusChartInstance.setOption(option);
        console.log('订单状态图表渲染成功');
    } else {
        console.error('订单状态图表实例初始化失败');
    }
}

// 渲染积分变更图表
function renderPointsChartData(data) {
    console.log('开始渲染积分变更图表，数据:', data);

    if (!data || data.length === 0 || !pointsChart.value) {
        console.log('积分变更图表数据为空或DOM未就绪');
        if (pointsChartInstance) {
            pointsChartInstance.clear();
        }
        return;
    }

    const typeNames = data.map(item => item.changeTypeName || '');
    const values = data.map(item => {
        const total = parseFloat(item.total) || 0;
        return {
            value: Math.abs(total), // 柱状图高度用绝对值
            originalValue: total, // 保留原始值用于tooltip
            itemStyle: {
                color: total >= 0 ? '#52c41a' : '#f5222d', // 正数为绿色，负数为红色
            },
        };
    });

    console.log('积分变更图表数据:', { typeNames, values });

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
            formatter: function (params) {
                const param = params[0];
                const originalValue = param.data.originalValue;
                const sign = originalValue >= 0 ? '+' : '';
                return param.name + '<br/>积分: ' + sign + formatNumber(originalValue, 2);
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            data: typeNames,
            axisLabel: {
                interval: 0,
                rotate: 45,
                fontSize: 12,
            },
        },
        yAxis: {
            type: 'value',
            name: '积分',
            axisLabel: {
                formatter: function (value) {
                    return Math.abs(value); // 显示绝对值
                },
            },
        },
        series: [
            {
                name: '积分变更',
                type: 'bar',
                data: values,
                barWidth: '60%',
            },
        ],
    };

    pointsChartInstance = initChartInstance(pointsChart, pointsChartInstance);
    if (pointsChartInstance) {
        pointsChartInstance.setOption(option);
        console.log('积分变更图表渲染成功');
    } else {
        console.error('积分变更图表实例初始化失败');
    }
}

// 渲染销售额图表
function renderSalesChartData(data) {
    console.log('开始渲染销售额图表，数据:', data);

    if (!data || data.length === 0 || !salesChart.value) {
        console.log('销售额图表数据为空或DOM未就绪');
        if (salesChartInstance) {
            salesChartInstance.clear();
        }
        return;
    }

    const dates = data.map(item => item.date || '');
    const sales = data.map(item => item.salesAmount || 0);

    console.log('销售额图表数据:', { dates, sales });

    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function (params) {
                const param = params[0];
                return param.name + '<br/>¥' + formatNumber(param.value, 2);
            },
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dates,
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '¥{value}',
            },
        },
        series: [
            {
                name: '销售额',
                type: 'line',
                smooth: true,
                data: sales,
                lineStyle: {
                    width: 4,
                },
                areaStyle:
                    salesChartType.value === 'area'
                        ? {
                              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                  { offset: 0, color: 'rgba(24, 144, 255, 0.6)' },
                                  { offset: 1, color: 'rgba(24, 144, 255, 0.1)' },
                              ]),
                          }
                        : null,
                symbolSize: 10,
                symbol: 'circle',
                itemStyle: {
                    color: '#1890ff',
                },
            },
        ],
    };

    salesChartInstance = initChartInstance(salesChart, salesChartInstance);
    if (salesChartInstance) {
        salesChartInstance.setOption(option);
        console.log('销售额图表渲染成功');
    } else {
        console.error('销售额图表实例初始化失败');
    }
}

// 图表类型切换
function renderUserChart() {
    if (userChartInstance && chartData.value.userGrowth && chartData.value.userGrowth.length > 0) {
        renderUserChartData(chartData.value.userGrowth);
    }
}

function renderOrderChart() {
    if (orderChartInstance && chartData.value.orderStats && chartData.value.orderStats.length > 0) {
        renderOrderChartData(chartData.value.orderStats);
    }
}

function renderSalesChart() {
    if (salesChartInstance && chartData.value.orderStats && chartData.value.orderStats.length > 0) {
        renderSalesChartData(chartData.value.orderStats);
    }
}

// 获取状态标签类型
function getStatusTagType(status) {
    const typeMap = {
        0: 'warning', // 待支付
        1: 'success', // 已支付
        2: 'info', // 已取消
        3: '', // 已完成
        4: 'warning', // 待发货
        5: 'primary', // 已发货
        6: 'warning', // 待收货
        7: 'success', // 已收货
        8: 'danger', // 已退款
    };
    return typeMap[status] || 'info';
}

// 查看订单详情
function viewOrderDetail(order) {
    console.log('查看订单:', order);
    ElMessage.info(`查看订单: ${order.orderNo}`);
    // 这里可以打开订单详情弹窗
}

// 刷新数据
function refreshData() {
    loadData();
}

// 加载所有数据
async function loadData() {
    loading.value.all = true;
    try {
        await Promise.all([loadStatsData(), loadChartsData(), loadRecentOrders()]);
    } finally {
        loading.value.all = false;
    }
}

// 格式化数字
function formatNumber(num, decimals = 0) {
    if (typeof num !== 'number') {
        num = parseFloat(num) || 0;
    }
    return num.toLocaleString('zh-CN', {
        minimumFractionDigits: decimals,
        maximumFractionDigits: decimals,
    });
}

// 监听窗口大小变化
function handleResize() {
    if (userChartInstance) userChartInstance.resize();
    if (orderChartInstance) orderChartInstance.resize();
    if (orderStatusChartInstance) orderStatusChartInstance.resize();
    if (pointsChartInstance) pointsChartInstance.resize();
    if (salesChartInstance) salesChartInstance.resize();
}

// 生命周期
onMounted(() => {
    initDateRange();
    loadData();

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);

    // 初始渲染
    nextTick(() => {
        handleResize();
    });
});

onBeforeUnmount(() => {
    if (userChartInstance) {
        userChartInstance.dispose();
        userChartInstance = null;
    }
    if (orderChartInstance) {
        orderChartInstance.dispose();
        orderChartInstance = null;
    }
    if (orderStatusChartInstance) {
        orderStatusChartInstance.dispose();
        orderStatusChartInstance = null;
    }
    if (pointsChartInstance) {
        pointsChartInstance.dispose();
        pointsChartInstance = null;
    }
    if (salesChartInstance) {
        salesChartInstance.dispose();
        salesChartInstance = null;
    }

    window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.statistics-container {
    /* padding: 20px; */
    min-height: 100vh;
    /* background-color: #f0f2f5; */
}

.header-card {
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-content h1 {
    margin: 0;
    color: #1890ff;
    font-size: 24px;
    font-weight: 600;
}

.filter-card {
    margin-bottom: 20px;
}

.filter-form {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
}

.stat-card {
    transition: all 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

.stat-item {
    position: relative;
    min-height: 80px;
}

.stat-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 4px;
}

.stat-trend {
    position: absolute;
    bottom: 0;
    left: 0;
}

.stat-icon {
    position: absolute;
    top: 0;
    right: 0;
    opacity: 0.3;
}

.chart-row {
    margin-bottom: 20px;
}

.chart-card {
    height: 100%;
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.chart-container {
    width: 100%;
    height: 300px;
    min-height: 300px;
}

.empty-chart {
    width: 100%;
    height: 300px;
    min-height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fafafa;
    border-radius: 4px;
}

.table-card {
    margin-top: 20px;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
/* 
.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    height: 45px;
    position: relative;
} */

/* 响应式调整 */
@media (max-width: 768px) {
    .stats-grid {
        grid-template-columns: repeat(auto-fill, minmax(100%, 1fr));
    }

    .chart-row {
        flex-direction: column;
    }

    .chart-row .el-col {
        width: 100%;
        margin-bottom: 20px;
    }

    .filter-form {
        flex-direction: column;
    }
}
</style>
