<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">刷新</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">查询</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 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 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 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 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 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">刷新</el-button>
                </div>
            </template>
            <el-table :data="recentOrders" v-loading="loading.orders" style="width: 100%">
                <el-table-column prop="orderNo" label="订单号">
                    <template #default="{ row }">
                        <el-tag type="info">{{ row.orderNo }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="userName" label="用户名" />
                <el-table-column prop="payAmount" label="金额">
                    <template #default="{ row }">¥{{ row.payAmount }}</template>
                </el-table-column>
                <el-table-column prop="statusText" label="状态">
                    <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="创建时间" />
                <el-table-column label="操作" width="120">
                    <template #default="{ row }">
                        <el-button type="text" size="small" @click="viewOrderDetail(row)">
                            查看
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-container">
                <el-pagination
                    v-model:current-page="page.current"
                    v-model:page-size="page.size"
                    :total="page.total"
                    :page-sizes="[5, 10, 20, 50]"
                    layout="total, sizes, prev, pager, next, jumper"
                    @size-change="loadRecentOrders"
                    @current-change="loadRecentOrders"
                />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ElMessage, ElLoading } 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: 15234, icon: User, color: '#1890ff' },
    {
        label: '今日新增',
        value: 45,
        icon: TrendCharts,
        color: '#52c41a',
        trend: '+3.2%',
        trendType: 'success',
    },
    { label: '总订单数', value: 2345, icon: ShoppingCart, color: '#722ed1' },
    {
        label: '今日订单',
        value: 67,
        icon: Goods,
        color: '#fa8c16',
        trend: '+5.1%',
        trendType: 'success',
    },
    { label: '总销售额', value: '156,780.50', prefix: '¥', icon: Money, color: '#13c2c2' },
    { label: '今日销售额', value: '4,523.80', prefix: '¥', icon: Present, color: '#f5222d' },
    { label: '直播中', value: 12, icon: VideoCamera, color: '#eb2f96' },
    { label: '活跃群组', value: 89, 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 recentOrders = ref([
    {
        id: 1,
        orderNo: 'SO202401140001',
        userName: '张三',
        payAmount: 199.0,
        status: 1,
        statusText: '已支付',
        createTime: '2024-01-14 10:30:00',
    },
    {
        id: 2,
        orderNo: 'SO202401140002',
        userName: '李四',
        payAmount: 299.0,
        status: 5,
        statusText: '已发货',
        createTime: '2024-01-14 11:15:00',
    },
    {
        id: 3,
        orderNo: 'SO202401140003',
        userName: '王五',
        payAmount: 399.0,
        status: 3,
        statusText: '已完成',
        createTime: '2024-01-14 12:20:00',
    },
    {
        id: 4,
        orderNo: 'SO202401140004',
        userName: '赵六',
        payAmount: 499.0,
        status: 0,
        statusText: '待支付',
        createTime: '2024-01-14 13:45:00',
    },
    {
        id: 5,
        orderNo: 'SO202401140005',
        userName: '钱七',
        payAmount: 599.0,
        status: 6,
        statusText: '待收货',
        createTime: '2024-01-14 14:30:00',
    },
    {
        id: 6,
        orderNo: 'SO202401140006',
        userName: '孙八',
        payAmount: 699.0,
        status: 8,
        statusText: '已退款',
        createTime: '2024-01-14 15:10:00',
    },
    {
        id: 7,
        orderNo: 'SO202401140007',
        userName: '周九',
        payAmount: 799.0,
        status: 2,
        statusText: '已取消',
        createTime: '2024-01-14 16:20:00',
    },
    {
        id: 8,
        orderNo: 'SO202401140008',
        userName: '吴十',
        payAmount: 899.0,
        status: 7,
        statusText: '已收货',
        createTime: '2024-01-14 17:30:00',
    },
]);

const loading = ref({
    stats: false,
    charts: false,
    orders: false,
});

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

// 默认图表数据
const defaultChartData = {
    // 用户增长数据
    userGrowth: [
        { date: '01-08', count: 12 },
        { date: '01-09', count: 15 },
        { date: '01-10', count: 8 },
        { date: '01-11', count: 23 },
        { date: '01-12', count: 17 },
        { date: '01-13', count: 25 },
        { date: '01-14', count: 18 },
    ],
    // 订单统计数据
    orderStats: [
        { date: '01-08', order_count: 45, sales_amount: 3200.0 },
        { date: '01-09', order_count: 52, sales_amount: 3800.0 },
        { date: '01-10', order_count: 38, sales_amount: 2500.0 },
        { date: '01-11', order_count: 67, sales_amount: 5200.0 },
        { date: '01-12', order_count: 54, sales_amount: 4100.0 },
        { date: '01-13', order_count: 72, sales_amount: 6200.0 },
        { date: '01-14', order_count: 60, sales_amount: 4800.0 },
    ],
    // 订单状态数据
    orderStatus: {
        pending_payment: 335,
        paid: 310,
        shipped: 234,
        completed: 135,
        cancelled: 154,
        refunded: 98,
    },
    // 积分变更数据
    pointsChange: [
        { change_type: 1, change_type_name: '拼单获得', total: 150.0 },
        { change_type: 2, change_type_name: '消费', total: 230.0 },
        { change_type: 3, change_type_name: '退款', total: 80.0 },
        { change_type: 4, change_type_name: '系统赠送', total: 50.0 },
        { change_type: 5, change_type_name: '系统扣除', total: 20.0 },
        { change_type: 6, change_type_name: '签到', total: 300.0 },
        { change_type: 7, change_type_name: '提现', total: 100.0 },
    ],
};

// 初始化日期
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 {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500));

        // 使用默认数据
        const mockStats = {
            totalUsers: 15234,
            todayNewUsers: 45,
            totalOrders: 2345,
            todayOrders: 67,
            totalSales: 156780.5,
            todaySales: 4523.8,
            liveCount: 12,
            groupCount: 89,
            userTrend: '+3.2%',
            orderTrend: '+5.1%',
        };

        // 更新统计数据
        statsData.value[0].value = mockStats.totalUsers.toLocaleString();
        statsData.value[1].value = mockStats.todayNewUsers;
        statsData.value[1].trend = mockStats.userTrend;
        statsData.value[2].value = mockStats.totalOrders.toLocaleString();
        statsData.value[3].value = mockStats.todayOrders;
        statsData.value[3].trend = mockStats.orderTrend;
        statsData.value[4].value = formatNumber(mockStats.totalSales, 2);
        statsData.value[5].value = formatNumber(mockStats.todaySales, 2);
        statsData.value[6].value = mockStats.liveCount;
        statsData.value[7].value = mockStats.groupCount;
    } catch (error) {
        console.error('加载统计数据失败:', error);
        ElMessage.error('加载统计数据失败');
    } finally {
        loading.value.stats = false;
    }
}

// 加载图表数据 - 使用默认数据
async function loadChartsData() {
    loading.value.charts = true;
    try {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500));

        // 使用默认数据渲染图表
        renderUserChartData(defaultChartData.userGrowth);
        renderOrderChartData(defaultChartData.orderStats);
        renderOrderStatusChartData(defaultChartData.orderStatus);
        renderPointsChartData(defaultChartData.pointsChange);
        renderSalesChartData(defaultChartData.orderStats);
    } catch (error) {
        console.error('加载图表数据失败:', error);
        ElMessage.error('加载图表数据失败');
    } finally {
        loading.value.charts = false;
    }
}

// 加载最近订单 - 使用默认数据
async function loadRecentOrders() {
    loading.value.orders = true;
    try {
        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 500));

        // 使用默认数据
        const mockOrders = recentOrders.value;

        // 如果有分页，可以这样处理
        const startIndex = (page.value.current - 1) * page.value.size;
        const endIndex = startIndex + page.value.size;
        const pagedOrders = mockOrders.slice(startIndex, endIndex);

        recentOrders.value = pagedOrders;
        page.value.total = mockOrders.length;
    } catch (error) {
        console.error('加载订单数据失败:', error);
        ElMessage.error('加载订单数据失败');
    } finally {
        loading.value.orders = false;
    }
}

// 渲染用户增长图表
function renderUserChartData(data) {
    if (!data || data.length === 0) {
        data = defaultChartData.userGrowth;
    }

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

    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',
                },
            },
        ],
    };

    if (!userChartInstance) {
        userChartInstance = echarts.init(userChart.value);
    }
    userChartInstance.setOption(option);
}

// 渲染订单统计图表
function renderOrderChartData(data) {
    if (!data || data.length === 0) {
        data = defaultChartData.orderStats;
    }

    const dates = data.map(item => item.date);
    const orderCounts = data.map(item => item.order_count);
    const salesAmounts = data.map(item => item.sales_amount);

    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 {
        option = {
            tooltip: {
                trigger: 'axis',
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true,
            },
            xAxis: {
                type: 'category',
                data: dates,
            },
            yAxis: {
                type: 'value',
                name: orderChartType.value === 'line' ? '销售额(元)' : '订单数',
            },
            series: [
                {
                    name: orderChartType.value === 'line' ? '销售额' : '订单数',
                    type: orderChartType.value,
                    data: orderChartType.value === 'line' ? salesAmounts : orderCounts,
                    smooth: true,
                    lineStyle: {
                        width: 3,
                    },
                    areaStyle:
                        orderChartType.value === 'line'
                            ? {
                                  opacity: 0.1,
                              }
                            : null,
                    symbolSize: 8,
                    itemStyle: {
                        color: orderChartType.value === 'line' ? '#52c41a' : '#1890ff',
                    },
                },
            ],
        };
    }

    if (!orderChartInstance) {
        orderChartInstance = echarts.init(orderChart.value);
    }
    orderChartInstance.setOption(option);
}

// 渲染订单状态分布图表
function renderOrderStatusChartData(data) {
    if (!data) {
        data = defaultChartData.orderStatus;
    }

    const statusMap = {
        pending_payment: { name: '待支付', value: 335 },
        paid: { name: '已支付', value: 310 },
        shipped: { name: '已发货', value: 234 },
        completed: { name: '已完成', value: 135 },
        cancelled: { name: '已取消', value: 154 },
        refunded: { name: '已退款', value: 98 },
    };

    const pieData = Object.entries(data).map(([key, value]) => ({
        name: statusMap[key]?.name || key,
        value: value || 0,
    }));

    const option = {
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: pieData.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: pieData,
                color: ['#ff4d4f', '#52c41a', '#1890ff', '#722ed1', '#fa8c16', '#13c2c2'],
            },
        ],
    };

    if (!orderStatusChartInstance) {
        orderStatusChartInstance = echarts.init(orderStatusChart.value);
    }
    orderStatusChartInstance.setOption(option);
}

// 渲染积分变更图表
function renderPointsChartData(data) {
    if (!data || data.length === 0) {
        data = defaultChartData.pointsChange;
    }

    const typeNames = data.map(item => item.change_type_name);
    const values = data.map(item => item.total);

    const option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow',
            },
            formatter: '{b}<br/>积分: {c}',
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            data: typeNames,
            axisLabel: {
                interval: 0,
                rotate: 45,
            },
        },
        yAxis: {
            type: 'value',
            name: '积分',
        },
        series: [
            {
                name: '积分变更',
                type: 'bar',
                data: values,
                barWidth: '60%',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: '#83bff6' },
                        { offset: 0.5, color: '#188df0' },
                        { offset: 1, color: '#188df0' },
                    ]),
                },
            },
        ],
    };

    if (!pointsChartInstance) {
        pointsChartInstance = echarts.init(pointsChart.value);
    }
    pointsChartInstance.setOption(option);
}

// 渲染销售额图表
function renderSalesChartData(data) {
    if (!data || data.length === 0) {
        data = defaultChartData.orderStats;
    }

    const dates = data.map(item => item.date);
    const sales = data.map(item => item.sales_amount);

    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: '{b}<br/>¥{c}',
        },
        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',
                },
            },
        ],
    };

    if (!salesChartInstance) {
        salesChartInstance = echarts.init(salesChart.value);
    }
    salesChartInstance.setOption(option);
}

// 图表类型切换
function renderUserChart() {
    if (userChartInstance) {
        renderUserChartData(defaultChartData.userGrowth);
    }
}

function renderOrderChart() {
    if (orderChartInstance) {
        renderOrderChartData(defaultChartData.orderStats);
    }
}

function renderSalesChart() {
    if (salesChartInstance) {
        renderSalesChartData(defaultChartData.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.success(`查看订单: ${order.orderNo}`);
    // 这里可以打开订单详情弹窗
}

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

// 加载所有数据
async function loadData() {
    await Promise.all([loadStatsData(), loadChartsData(), loadRecentOrders()]);
    ElMessage.success('数据刷新成功');
}

// 格式化数字
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();
}

// 模拟API调用
function simulateApiCall() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve({
                success: true,
                data: '模拟数据',
            });
        }, 500);
    });
}

// 生命周期
onMounted(() => {
    initDateRange();
    // 使用默认数据初始化
    loadData();

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

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

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

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

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

/* 响应式调整 */
@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>
