<template>
    <div class="fission-analysis-container">
        <el-card class="analysis-card mt-4" shadow="never">
            <div class="date-selector-container">
                <!-- Top Navigation Section -->
                <div class="date-period-selector">
                    <el-button
                        :class="{ active: activePeriod === 'yesterday' }"
                        @click="changePeriod('yesterday')"
                        >昨日</el-button
                    >
                    <el-button
                        :class="{ active: activePeriod === '7d' }"
                        @click="changePeriod('7d')"
                        >7日</el-button
                    >
                    <el-button
                        :class="{ active: activePeriod === '15d' }"
                        @click="changePeriod('15d')"
                        >15日</el-button
                    >
                    <el-button
                        :class="{ active: activePeriod === '30d' }"
                        @click="changePeriod('30d')"
                        >30日</el-button
                    >

                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                        :clearable="false"
                        :disabled-date="(date) => false"
                        @change="handleDateRangeChange"
                    />
                    <div class="date-action-buttons">
                        <el-button type="primary" @click="fetchData"
                            >搜索</el-button
                        >
                        <el-button @click="resetFilters">重置</el-button>
                    </div>
                </div>
            </div>

            <!-- Metrics Cards -->
            <div class="metrics-cards">
                <el-row :gutter="20" class="metrics-row">
                    <el-col
                        v-for="(item, index) in metricsCardsData"
                        :key="index"
                        class="metric-col"
                    >
                        <el-card shadow="never" class="metric-card">
                            <div class="metric-title">{{ item.title }}</div>
                            <div class="metric-date">{{
                                displayDateRange
                            }}</div>
                            <div class="metric-value-container">
                                <div class="metric-label">合计</div>
                                <div class="metric-value">{{ item.value }}</div>
                            </div>
                            <div class="metric-comparison">
                                环比 {{ item.change }}%
                                <template v-if="parseFloat(item.change) > 0"
                                    ><span class="arrow-up">↑</span></template
                                >
                                <template
                                    v-else-if="parseFloat(item.change) < 0"
                                    ><span class="arrow-down">↓</span></template
                                >
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- Numbers Cards -->
            <div class="number-metrics">
                <el-row :gutter="20">
                    <el-col
                        :span="4"
                        v-for="(item, index) in numberMetricsData"
                        :key="index"
                    >
                        <el-card shadow="hover" class="number-card">
                            <div class="number-value">{{ item.value }}</div>
                            <div class="number-label">{{ item.label }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- Chart Section -->
            <div class="trend-chart-section">
                <div class="chart-title">30日分享人数趋势</div>
                <div class="chart-container" ref="chartRef"></div>
            </div>
        </el-card>
    </div>
</template>

<script setup>
    import { ref, onMounted, computed, watch } from 'vue';
    import * as echarts from 'echarts';
    import dayjs from 'dayjs';
    import request from '@/utils/request';
    import { ElMessage } from 'element-plus';

    // 状态变量
    const activePeriod = ref('');
    const chartRef = ref(null);
    let chart = null;
    // 跟踪是否使用自定义日期范围
    const isCustomDateRange = ref(false);
    // 使用今日初始化日期范围
    const dateRange = ref([
        dayjs().format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
    ]);

    // API数据
    const statisticData = ref(null);

    // 从API响应计算的指标
    const metrics = computed(() => {
        if (!statisticData.value) {
            return {
                totalUsers: '',
                totalUsersChange: '0',
                orders: '',
                ordersChange: '0',
                scanNum: '',
                scanNumChange: '0',
                scanRate: '',
                scanRateChange: '0',
                newUserRate: '',
                newUserRateChange: '0'
            };
        }

        const data = statisticData.value.data;

        // 辅助函数，用于一致地格式化比较值
        const formatComparison = (value) => {
            if (value === null || value === undefined) return '0';
            // 如果存在%则移除，仅返回数字字符串
            return String(value).replace('%', '');
        };

        return {
            totalUsers: data.upsellHelpNum || '0',
            totalUsersChange: formatComparison(data.upsellHelpNumComparison),
            orders: data.upsellOrderNum || '0',
            ordersChange: formatComparison(data.upsellOrderNumComparison),
            scanNum: data.upsellScanNum || '0',
            scanNumChange: formatComparison(data.upsellScanNumComparison),
            scanRate: data.scanJoinRate ? `${data.scanJoinRate}%` : '0%',
            scanRateChange: formatComparison(data.scanJoinRateComparison),
            newUserRate: data.newUserRate ? `${data.newUserRate}%` : '0%',
            newUserRateChange: formatComparison(data.newUserRateComparison)
        };
    });

    const stats = computed(() => {
        if (!statisticData.value) {
            return {
                participants: '0',
                helps: '0',
                ordersCount: '0',
                totalOrderAmount: '0',
                totalAddedPoints: '0',
                totalSaleAmount: '0'
            };
        }

        const data = statisticData.value.data;

        return {
            participants: data.upsellShareNum || '0',
            helps: data.upsellHelpTimes || '0',
            ordersCount: data.orderBookNum || '0',
            totalOrderAmount: data.orderTotalMoney || '0',
            totalAddedPoints: data.upsellTotalMoney || '0',
            totalSaleAmount: data.upsellFinalTotalMoney || '0'
        };
    });

    // 数字指标卡片数据
    const numberMetricsData = computed(() => {
        return [
            { label: '参与用户数', value: stats.value.participants },
            { label: '助力次数', value: stats.value.helps },
            { label: '订单总本数', value: stats.value.ordersCount },
            { label: '订单预估总金额', value: stats.value.totalOrderAmount },
            { label: '加价预估总金额', value: stats.value.totalAddedPoints },
            { label: '实际加价金额', value: stats.value.totalSaleAmount }
        ];
    });

    // 度量指标卡片数据
    const metricsCardsData = computed(() => {
        return [
            { 
                title: '助力人数', 
                value: `${metrics.value.totalUsers}人`, 
                change: metrics.value.totalUsersChange 
            },
            { 
                title: '参与活动订单数', 
                value: `${metrics.value.orders}单`, 
                change: metrics.value.ordersChange 
            },
            { 
                title: '活动书单扫描次数', 
                value: `${metrics.value.scanNum}次`, 
                change: metrics.value.scanNumChange 
            },
            { 
                title: '活动书单扫描/参与占比', 
                value: metrics.value.scanRate, 
                change: metrics.value.scanRateChange 
            },
            { 
                title: '助力新用户占比', 
                value: metrics.value.newUserRate, 
                change: metrics.value.newUserRateChange 
            }
        ];
    });

    // 图表数据
    const chartData = computed(() => {
        if (!statisticData.value || !statisticData.value.data.chartList) {
            return {
                dates: [],
                values: []
            };
        }

        const chartList = statisticData.value.data.chartList;
        return {
            dates: chartList.map((item) => item.date),
            values: chartList.map((item) => item.shareNum)
        };
    });

    const currentDate = computed(() => {
        return dayjs().format('YYYY-MM-DD');
    });

    const displayDateRange = computed(() => {
        if (Array.isArray(dateRange.value) && dateRange.value.length === 2) {
            // If start and end dates are the same, only show one date
            if (dateRange.value[0] === dateRange.value[1]) {
                return dateRange.value[0];
            }
            return `${dateRange.value[0]} - ${dateRange.value[1]}`;
        } else {
            return currentDate.value;
        }
    });

    // 根据时间段更新日期范围的方法
    const updateDateRangeByPeriod = (period) => {
        isCustomDateRange.value = false;

        switch (period) {
            case 'yesterday':
                dateRange.value = [
                    dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
                    dayjs().subtract(1, 'day').format('YYYY-MM-DD')
                ];
                break;
            case '7d':
                dateRange.value = [
                    dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
                    dayjs().format('YYYY-MM-DD')
                ];
                break;
            case '15d':
                dateRange.value = [
                    dayjs().subtract(15, 'day').format('YYYY-MM-DD'),
                    dayjs().format('YYYY-MM-DD')
                ];
                break;
            case '30d':
                dateRange.value = [
                    dayjs().subtract(30, 'day').format('YYYY-MM-DD'),
                    dayjs().format('YYYY-MM-DD')
                ];
                break;
            default:
                dateRange.value = [
                    dayjs().subtract(7, 'day').format('YYYY-MM-DD'),
                    dayjs().format('YYYY-MM-DD')
                ];
        }
    };

    // 处理时间段变更按钮点击的方法
    const changePeriod = (period) => {
        activePeriod.value = period;
        updateDateRangeByPeriod(period);
        fetchData();
    };

    // 处理日期选择器变更
    const handleDateRangeChange = () => {
        isCustomDateRange.value = true;
        activePeriod.value = '';
        fetchData();
    };

    const getDateRangeForAPI = () => {
        let startDate, endDate;

        if (Array.isArray(dateRange.value) && dateRange.value.length === 2) {
            startDate = dayjs(dateRange.value[0]).format('YYYY-MM-DD 00:00:00');
            endDate = dayjs(dateRange.value[1]).format('YYYY-MM-DD 23:59:59');
        } else {
            // 如果dateRange不是数组，使用当天作为默认值
            startDate = dayjs().format('YYYY-MM-DD 00:00:00');
            endDate = dayjs().format('YYYY-MM-DD 23:59:59');
        }

        return { startDate, endDate };
    };

    const fetchData = async () => {
        const { startDate, endDate } = getDateRangeForAPI();

        try {
            const { data } = await request.get(
                '/activity/activityUpsellInfo/statistic',
                {
                    params: {
                        startDate,
                        endDate
                    }
                }
            );

            statisticData.value = data;
            updateChart();
        } catch (error) {
            ElMessage.error('获取数据失败');
            console.error('Failed to fetch statistic data:', error);
        }
    };

    const resetFilters = () => {
        isCustomDateRange.value = false;
        activePeriod.value = '';
        // 重置为今日
        dateRange.value = [
            dayjs().format('YYYY-MM-DD'),
            dayjs().format('YYYY-MM-DD')
        ];
        fetchData();
    };

    const updateChart = () => {
        if (!chart || !chartData.value.dates.length) return;

        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: chartData.value.dates,
                boundaryGap: false
            },
            yAxis: {
                type: 'value',
                min: 0
            },
            series: [
                {
                    name: '分享人数',
                    type: 'line',
                    data: chartData.value.values,
                    smooth: true,
                    lineStyle: {
                        color: '#5470c6',
                        width: 2
                    },
                    symbol: 'circle',
                    symbolSize: 8,
                    itemStyle: {
                        color: '#5470c6'
                    }
                }
            ]
        };

        chart.setOption(option);
    };

    const initChart = () => {
        if (chartRef.value) {
            chart = echarts.init(chartRef.value);

            // 使用空数据初始化，API调用后更新
            const option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    boundaryGap: false
                },
                yAxis: {
                    type: 'value',
                    min: 0
                },
                series: [
                    {
                        name: '分享人数',
                        type: 'line',
                        data: [],
                        smooth: true,
                        lineStyle: {
                            color: '#5470c6',
                            width: 2
                        },
                        symbol: 'circle',
                        symbolSize: 8,
                        itemStyle: {
                            color: '#5470c6'
                        }
                    }
                ]
            };

            chart.setOption(option);

            // 处理窗口大小调整
            window.addEventListener('resize', () => {
                chart.resize();
            });

            // 使用ResizeObserver检测并响应图表容器大小变化
            const resizeObserver = new ResizeObserver(() => {
                chart.resize();
            });

            resizeObserver.observe(chartRef.value);
        }
    };

    // 手动调整图表大小的方法 - 可从父组件调用
    const resizeChart = () => {
        if (chart) {
            chart.resize();
        }
    };

    // 监听dateRange变化以更新activePeriod
    watch(dateRange, (newValue) => {
        if (isCustomDateRange.value) {
            activePeriod.value = '';
        }
    });

    onMounted(() => {
        initChart();
        activePeriod.value = '';
        // 不更新日期范围，保持为今日
        fetchData();
        
        // 在组件挂载后强制调整大小
        setTimeout(() => {
            resizeChart();
        }, 300);
    });

    // 向父组件暴露resizeChart方法
    defineExpose({
        resizeChart
    });
</script>

<style lang="scss" scoped>
    .date-selector-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        border-bottom: 1px solid #ebeef5;
        padding-bottom: 16px;
    }

    .arrow-up {
        color: #67c23a; /* Element Plus 成功颜色（绿色） */
    }

    .arrow-down {
        color: #f56c6c; /* Element Plus 危险颜色（红色） */
    }

    .date-period-selector {
        display: flex;
        gap: 10px;

        .el-button {
            border-radius: 4px;
        }

        .active {
            color: #409eff;
            border-color: #409eff;
        }
    }

    .custom-date-range {
        display: flex;
        align-items: center;
        gap: 16px;
    }

    .time-range-selector {
        display: flex;
        align-items: center;
        gap: 8px;

        .time-label {
            font-size: 14px;
            color: #606266;
        }
    }

    .time-slider {
        width: 200px;
    }

    .date-action-buttons {
        display: flex;
        gap: 8px;
    }

    .date-display {
        display: flex;
        align-items: center;
        gap: 4px;
        cursor: pointer;
        padding: 6px 12px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        margin-bottom: 20px;
    }

    .metrics-cards {
        margin-bottom: 24px;
    }

    .metrics-row {
        display: flex;
        flex-wrap: nowrap;
    }

    .metric-col {
        flex: 1;
    }

    .metric-card {
        border: 1px solid #ebeef5;
        height: 150px;
        position: relative;

        &:first-child {
            border-left: 3px solid #409eff;
        }

        .metric-title {
            font-size: 14px;
            color: #303133;
            margin-bottom: 4px;
        }

        .metric-date {
            font-size: 12px;
            color: #909399;
        }

        .metric-value-container {
            display: flex;
            margin-bottom: 4px;
            align-items: center;

            .metric-label {
                font-size: 14px;
                color: #606266;
                margin-right: 10px;
            }

            .metric-value {
                font-size: 32px;
                font-weight: bold;
                color: #303133;
            }
        }

        .metric-comparison {
            font-size: 12px;
            color: #606266;
            position: absolute;
            bottom: 12px;
        }
    }

    .number-metrics {
        margin-bottom: 24px;
    }

    .number-card {
        text-align: center;
        padding: 16px;
        height: 120px;

        .number-value {
            font-size: 22px;
            font-weight: bold;
            color: #f6a623;
            margin-bottom: 8px;
        }

        .number-label {
            font-size: 14px;
            color: #606266;
        }
    }

    .trend-chart-section {
        margin-top: 24px;
        width: 100%;

        .chart-title {
            font-size: 16px;
            color: #303133;
            margin-bottom: 16px;
        }

        .chart-container {
            height: 350px;
            width: 100%;
            position: relative;
            overflow: hidden;
        }
    }

    .date-popover-content {
        padding: 12px;
    }
</style>
