<template>
    <ele-page flex-table>
        <common-table
            ref="pageRef"
            :pageConfig="pageConfig"
            :columns="columns"
            :tools="false"
        >
            <template #toolbar>
                <div class="flex mb-6">
                    <pieChart ref="pieChartRef" class="flex-1" />
                    <rank-list ref="rankListRef" />
                </div>
            </template>
        </common-table>
    </ele-page>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import pieChart from '@/views/optimization/reportAnalysis/components/pie-chart.vue';
    import rankList from '@/views/optimization/reportAnalysis/components/rank-list.vue';
    import request from '@/utils/request';
    import { ElMessage } from 'element-plus';

    defineOptions({ name: 'ReportAnalysis' });

    // 图表组件实例
    const pieChartRef = ref(null);
    const rankListRef = ref(null);

    /** 表格列配置 */
    const columns = ref([
        { label: '订单编号', prop: 'orderId', align: 'center' },
        { label: '用户UID', prop: 'userId', align: 'center' },
        { label: '取消原因', prop: 'reason', align: 'center', minWidth: 200 },
        { label: '取消时间', prop: 'cancelTime', align: 'center' }
    ]);

    /** 页面组件实例 */
    const pageRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/order/recycleOrderStatistic/cancel/list',
        fileName: '上报分析',
        cacheKey: 'reportAnalysisTable'
    });

    const fetchData = async () => {
        try {
            // 获取理由比例数据（饼图）
            const reasonResponse = await request.get(
                '/order/recycleOrderStatistic/cancel/reasonStat'
            );
            if (reasonResponse.data && reasonResponse.data.data) {
                pieChartRef.value?.updateChartData(reasonResponse.data.data);
            }

            // 获取地区榜单数据（排行榜）
            const areaResponse = await request.get(
                '/order/recycleOrderStatistic/cancel/areaRank'
            );
            if (areaResponse.data && areaResponse.data.data) {
                rankListRef.value?.updateRankData(areaResponse.data.data);
            }

            // 刷新表格
            reload();
        } catch (error) {
            ElMessage.error('获取数据失败');
            console.error('Failed to fetch statistic data:', error);
        }
    };

    //刷新表格
    function reload(where) {
        pageRef.value?.reload(where);
    }

    onMounted(() => {
        // 默认加载数据
        fetchData();
    });
</script>
