<template>
    <div class="fission-analysis-container p-4">
        <el-card class="analysis-card" shadow="never" v-loading="loading">
            <div class="date-selector-container mb-6">
                <!-- Top Navigation Section -->
                <div class="date-period-selector flex items-center gap-4">
                    <el-button-group>
                        <el-button
                            :type="
                                activePeriod === 'yesterday' ? 'primary' : ''
                            "
                            @click="changePeriod('yesterday')"
                            >昨日</el-button
                        >
                        <el-button
                            :type="activePeriod === '7d' ? 'primary' : ''"
                            @click="changePeriod('7d')"
                            >7日</el-button
                        >
                        <el-button
                            :type="activePeriod === '15d' ? 'primary' : ''"
                            @click="changePeriod('15d')"
                            >15日</el-button
                        >
                        <el-button
                            :type="activePeriod === '30d' ? 'primary' : ''"
                            @click="changePeriod('30d')"
                            >30日</el-button
                        >
                    </el-button-group>

                    <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"
                        @change="handleDateRangeChange"
                        style="max-width: 400px"
                    />
                    <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 mb-6">
                <el-row :gutter="20">
                    <el-col
                        v-for="(item, index) in metricsCardsData"
                        :key="index"
                        :span="4"
                    >
                        <el-card shadow="never" class="metric-card">
                            <div class="text-gray-500 text-sm mb-2">{{
                                item.title
                            }}</div>
                            <div class="text-xs text-gray-400 mb-2">{{
                                displayDateRange
                            }}</div>
                            <div class="flex justify-between items-end mb-2">
                                <span class="text-sm text-gray-500">合计</span>
                                <span class="text-xl font-bold">{{
                                    item.value
                                }}</span>
                            </div>
                            <div
                                class="text-xs text-gray-500 flex items-center"
                            >
                                环比 {{ item.change }}%
                                <span
                                    v-if="parseFloat(item.change) > 0"
                                    class="text-red-500 ml-1"
                                    >↑</span
                                >
                                <span
                                    v-else-if="parseFloat(item.change) < 0"
                                    class="text-green-500 ml-1"
                                    >↓</span
                                >
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- Numbers Cards -->
            <div class="number-metrics mb-6">
                <el-row :gutter="20">
                    <el-col
                        :span="4"
                        v-for="(item, index) in numberMetricsData"
                        :key="index"
                    >
                        <el-card shadow="hover" class="bg-gray-50">
                            <div class="text-2xl font-bold mb-1 text-center">{{
                                item.value
                            }}</div>
                            <div class="text-sm text-gray-500 text-center">{{
                                item.label
                            }}</div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- Chart Section -->
            <div class="trend-chart-section">
                <div class="text-lg font-bold mb-4">分享人数趋势</div>
                <div class="h-80 w-full" ref="chartRef"></div>
            </div>
        </el-card>
    </div>
</template>

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

    defineOptions({ name: 'ShareDiscountFission' });

    // State
    const activePeriod = ref('30d');
    const chartRef = ref(null);
    let chart = null;
    const dateRange = ref([
        dayjs().subtract(29, 'day').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD')
    ]);
    const loading = ref(false);
    const statisticData = ref(null);

    const formatComparison = (value) => {
        if (value === null || value === undefined) return '0';
        return String(value).replace('%', '');
    };

    const formatPercent = (value) => {
        if (value === null || value === undefined || value === '') return '0%';
        const str = String(value);
        return str.includes('%') ? str : `${str}%`;
    };

    const formatMoney = (value) => {
        if (value === null || value === undefined || value === '') {
            return '¥0';
        }
        const num = Number(value);
        if (Number.isNaN(num)) return '¥0';
        return `¥${num.toLocaleString('zh-CN', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 2
        })}`;
    };

    const resultData = computed(() => statisticData.value?.data || {});

    const displayDateRange = computed(() => {
        if (!dateRange.value?.length) return '';
        if (dateRange.value[0] === dateRange.value[1]) {
            return dateRange.value[0];
        }
        return `${dateRange.value[0]} ~ ${dateRange.value[1]}`;
    });

    const metricsCardsData = computed(() => {
        const data = resultData.value;
        return [
            {
                title: '降价助力人数',
                value: data.reduceHelpNum ?? 0,
                change: formatComparison(data.reduceHelpNumComparison)
            },
            {
                title: '参与活动订单数',
                value: data.reduceOrderNum ?? 0,
                change: formatComparison(data.reduceOrderNumComparison)
            },
            {
                title: '活动加购次数',
                value: data.reduceCartNum ?? 0,
                change: formatComparison(data.reduceCartNumComparison)
            },
            {
                title: '活动加购参与占比',
                value: formatPercent(data.cartJoinRate),
                change: formatComparison(data.cartJoinRateComparison)
            },
            {
                title: '助力新用户占比',
                value: formatPercent(data.newUserRate),
                change: formatComparison(data.newUserRateComparison)
            },
            {
                title: '裂变转化率',
                value: formatPercent(data.conversionRate),
                change: formatComparison(data.conversionRateComparison)
            }
        ];
    });

    const numberMetricsData = computed(() => {
        const data = resultData.value;
        return [
            { label: '降价活动分享人数', value: data.reduceShareNum ?? 0 },
            { label: '助力次数', value: data.reduceHelpTimes ?? 0 },
            { label: '订单总本书', value: data.orderBookNum ?? 0 },
            { label: '订单总金额', value: formatMoney(data.orderTotalMoney) },
            { label: '降价总金额', value: formatMoney(data.reduceTotalMoney) },
            { label: '累计实付金额', value: formatMoney(data.orderPayMoney) }
        ];
    });

    const chartData = computed(() => {
        const chartList = resultData.value.chartList;
        if (!Array.isArray(chartList) || !chartList.length) {
            return { dates: [], values: [] };
        }
        return {
            dates: chartList.map((item) => item.date),
            values: chartList.map((item) => item.shareNum ?? 0)
        };
    });

    const getDateRangeForAPI = () => {
        const [start, end] = dateRange.value || [];
        return {
            startDate: dayjs(start || undefined)
                .startOf('day')
                .format('YYYY-MM-DD HH:mm:ss'),
            endDate: dayjs(end || undefined)
                .endOf('day')
                .format('YYYY-MM-DD HH:mm:ss')
        };
    };

    const changePeriod = (period) => {
        activePeriod.value = period;
        const end = dayjs();
        let start;

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

    const handleDateRangeChange = () => {
        activePeriod.value = '';
    };

    const resetFilters = () => {
        changePeriod('30d');
    };

    const fetchData = async () => {
        const { startDate, endDate } = getDateRangeForAPI();
        loading.value = true;
        try {
            const { data } = await request.get(
                '/activity/activityReduceInfo/statistic',
                {
                    params: {
                        startDate, endDate 
                    }
                }
            );

            if (data?.code !== 200) {
                ElMessage.error(data?.msg || '获取数据失败');
                return;
            }

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

    const updateChart = () => {
        if (!chartRef.value) return;

        if (!chart) {
            chart = echarts.init(chartRef.value);
        }

        chart.setOption({
            tooltip: { trigger: 'axis' },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: chartData.value.dates
            },
            yAxis: { type: 'value', min: 0 },
            series: [
                {
                    name: '分享人数',
                    type: 'line',
                    smooth: true,
                    data: chartData.value.values,
                    areaStyle: { opacity: 0.3 },
                    itemStyle: { color: '#409EFF' }
                }
            ]
        });
    };

    const handleResize = () => {
        chart?.resize();
    };

    onMounted(() => {
        fetchData();
        window.addEventListener('resize', handleResize);
    });

    onBeforeUnmount(() => {
        window.removeEventListener('resize', handleResize);
        chart?.dispose();
        chart = null;
    });
</script>

<style scoped>
    .metric-card {
        height: 140px;
        display: flex;
        flex-direction: column;
        justify-content: center;
    }
</style>
