<template>
    <ele-page flex-table>
        <page-search @search="reload" />
        <common-table
            ref="pageRef"
            :pageConfig="pageConfig"
            :columns="columns"
            :tools="false"
            show-summary
            :summary-method="getSummaries"
            :flex-table="false"
        >
            <template #toolbar="{ row }">
                <div>
                    <el-button
                        type="success"
                        plain
                        v-permission="'statistic:recycleOrder:export'"
                        @click="handleExportExcel(row)"
                    >
                        导出EXCEL
                    </el-button>
                </div>
            </template>
        </common-table>
    </ele-page>
</template>

<script setup>
    import { ref, reactive } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import pageSearch from './components/page-search.vue';

    defineOptions({ name: 'RecycleOrder' });

    /** 表格列配置 */
    const columns = ref([
        { type: 'index', label: '#', align: 'center', width: 80 },
        { label: '日期', prop: 'statisticDate', align: 'center' },
        { label: '仓库', prop: 'godownName', align: 'center' },
        { label: '回收订单数', prop: 'orderNum', align: 'center' },
        { label: '回收本数', prop: 'bookNum', align: 'center' },
        { label: '订单预估金额', prop: 'recycleTotalMoney', align: 'center' },
        { label: '回收平均价格', prop: 'recycleAveragePrice', align: 'center' },
        { label: '审核订单数', prop: 'auditNum', align: 'center' },
        { label: '审核总本数', prop: 'auditGoodNum', align: 'center' },
        { label: '审核金额', prop: 'auditMoney', align: 'center' },
        { label: '审核订单预估金额', prop: 'auditTotalMoney', align: 'center' },
        { label: '审核平均单本价', prop: 'auditAverageMoney', align: 'center' },
        { label: '库存周转率', prop: 'stockTurnoverRate', align: 'center' },
        { label: '平均库存', prop: 'averageStock', align: 'center' }
    ]);

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

    const pageConfig = reactive({
        pageUrl: '/order/recycleOrderStatistic/pagelist',
        exportUrl: '/order/recycleOrderStatistic/export',
        fileName: '回收订单统计',
        cacheKey: 'recycleOrderStatisticTable'
    });

    /**
     * 自定义表格汇总计算方法
     * @param {Object} param0 - 表格数据和列信息
     * @returns {Array} - 汇总行显示的数据
     */
    function getSummaries({ columns, data }) {
        const sums = [];
        columns.forEach((column, index) => {
            if (index === 0) {
                sums[index] = '合计';
                return;
            }

            const values = data.map((item) => Number(item[column.property]));

            if (!values.length) {
                sums[index] = 'N/A';
                return;
            }

            switch (column.property) {
                case 'auditAverageMoney':
                case 'recycleAveragePrice': {
                    // 只计算有值的数据的平均值
                    const validValues = values.filter(
                        (value) => value && !isNaN(value)
                    );
                    if (validValues.length > 0) {
                        const sum = validValues.reduce(
                            (prev, curr) => prev + curr,
                            0
                        );
                        sums[index] = (sum / validValues.length).toFixed(2);
                    } else {
                        sums[index] = '';
                    }
                    break;
                }
                case 'auditGoodNum':
                case 'orderNum':
                case 'bookNum':
                case 'auditNum': {
                    // 求和
                    const sum = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + value;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = sum;
                    break;
                }
                case 'auditMoney':
                case 'recycleTotalMoney':
                case 'auditTotalMoney': {
                    // 求和，保留两位小数
                    const sum = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return prev + value;
                        } else {
                            return prev;
                        }
                    }, 0);
                    sums[index] = sum.toFixed(2);
                    break;
                }
                default:
                    sums[index] = '';
            }
        });

        return sums;
    }

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

    //导出excel
    function handleExportExcel() {
        pageRef.value?.exportData('回收订单统计', 'GET');
    }
</script>
