<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef"></base-search>

        <!-- 横向滚动操作栏 -->
        <div class="operation-scroll-bar">
            <div class="operation-scroll-container">
                <el-button
                    type="primary"
                    v-hasPermi="['salesoverview:add']"
                    @click="showAddDialog"
                    style="margin-left: 10px"
                >
                    新增销售概览
                </el-button>
                <el-button
                    type="success"
                    v-hasPermi="['salesoverview:calculate']"
                    @click="handleCalculate"
                    style="margin-left: 10px"
                    :loading="calculating"
                >
                    计算统计数据
                </el-button>
            </div>
        </div>

        <div class="main-container">
            <el-table
                :data="rows"
                border
                v-loading="data.dataListLoading"
                element-loading-text="数据加载中..."
                style="width: 100%"
                :show-overflow-tooltip="true"
            >
                <el-table-column label="ID" prop="id" min-width="80" width="100">
                    <template #default="scope">
                        {{ scope.row.id || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="采购总额(元)" prop="toalProcurementAmount" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.toalProcurementAmount !== null && scope.row.toalProcurementAmount !== undefined 
                            ? parseFloat(scope.row.toalProcurementAmount).toFixed(2) : '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="销售总额(元)" prop="toalSalesAmount" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.toalSalesAmount !== null && scope.row.toalSalesAmount !== undefined 
                            ? parseFloat(scope.row.toalSalesAmount).toFixed(2) : '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="利润(元)" prop="profits" min-width="120" width="150">
                    <template #default="scope">
                        <span :style="{ color: scope.row.profits >= 0 ? '#67C23A' : '#F56C6C' }">
                            {{ scope.row.profits !== null && scope.row.profits !== undefined 
                                ? parseFloat(scope.row.profits).toFixed(2) : '--' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="应收货款(元)" prop="accountsReceivable" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.accountsReceivable !== null && scope.row.accountsReceivable !== undefined 
                            ? parseFloat(scope.row.accountsReceivable).toFixed(2) : '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="未收货款(元)" prop="uncollectedPayment" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.uncollectedPayment !== null && scope.row.uncollectedPayment !== undefined 
                            ? parseFloat(scope.row.uncollectedPayment).toFixed(2) : '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="实收货款(元)" prop="actualPayment" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.actualPayment !== null && scope.row.actualPayment !== undefined 
                            ? parseFloat(scope.row.actualPayment).toFixed(2) : '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="采购数量(头)" prop="totalPurchase" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.totalPurchase || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="采购单数(车)" prop="totalOrder" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.totalOrder || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="销售单数(单)" prop="totalSales" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.totalSales || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" min-width="160" width="180">
                    <template #default="scope">
                        {{ scope.row.createTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="更新时间" prop="upTime" min-width="160" width="180">
                    <template #default="scope">
                        {{ scope.row.upTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="200" width="250" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" v-hasPermi="['salesoverview:edit']" @click="showEditDialog(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" v-hasPermi="['salesoverview:delete']" @click="del(scope.row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="dataListOnEmpty">暂无数据</div>
                </template>
            </el-table>
            <Pagination
                v-if="data.total > 0"
                v-model:limit="form.pageSize"
                v-model:page="form.pageNum"
                :total="data.total"
                @pagination="handlePagination"
            />
        </div>

        <!-- 新增/编辑对话框 -->
        <SalesOverviewDialog ref="dialogRef" @success="getDataList" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import baseSearch from '@/components/common/searchCustom/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import SalesOverviewDialog from './dialog.vue';
import {
    salesOverviewList,
    salesOverviewDelete,
    calculateSalesOverview,
} from '@/api/salesOverview.js';

const baseSearchRef = ref();
const dialogRef = ref();
const calculating = ref(false);
const data = reactive({
    total: 0,
    dataListLoading: false,
    tableKey: 0,
});
const rows = ref([]);
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});

const formItemList = reactive([
    {
        label: '创建时间',
        prop: 'createTime',
        type: 'daterange',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
    },
]);

const searchFrom = () => {
    form.pageNum = 1;
    getDataList();
};

const handlePagination = (paginationData) => {
    if (paginationData) {
        form.pageNum = paginationData.page || form.pageNum;
        form.pageSize = paginationData.limit || form.pageSize;
    }
    getDataList();
};

const getDataList = () => {
    data.dataListLoading = true;
    const searchParams = baseSearchRef.value.penetrateParams();

    const params = {
        ...form,
        ...searchParams,
    };

    // 处理日期范围参数
    if (searchParams.createTime && Array.isArray(searchParams.createTime) && searchParams.createTime.length === 2) {
        params.startTime = searchParams.createTime[0];
        params.endTime = searchParams.createTime[1];
        delete params.createTime;
    }

    console.log('[SALES-OVERVIEW-LIST] 请求参数:', params);
    salesOverviewList(params)
        .then((res) => {
            console.log('[SALES-OVERVIEW-LIST] 响应数据:', res);

            let responseData = res.data || res;

            if (responseData && typeof responseData === 'object' && 'total' in responseData && 'rows' in responseData) {
                rows.value = responseData.rows || [];
                data.total = responseData.total || 0;
            } else if (responseData && responseData.data) {
                rows.value = responseData.data.rows || [];
                data.total = responseData.data.total || 0;
            } else {
                rows.value = [];
                data.total = 0;
            }

            console.log('[SALES-OVERVIEW-LIST] 解析后的数据 - 总数:', data.total, '当前页数据:', rows.value.length);
        })
        .catch((error) => {
            console.error('[SALES-OVERVIEW-LIST] 请求失败:', error);
            ElMessage.error('查询失败：' + (error.message || '未知错误'));
            rows.value = [];
            data.total = 0;
        })
        .finally(() => {
            data.dataListLoading = false;
        });
};

const showAddDialog = () => {
    if (dialogRef.value) {
        dialogRef.value.onShowDialog(null);
    }
};

const showEditDialog = (row) => {
    if (dialogRef.value) {
        dialogRef.value.onShowDialog(row);
    }
};

const del = (id) => {
    ElMessageBox.confirm('确定要删除这条销售概览记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            salesOverviewDelete(id)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('删除成功');
                        getDataList();
                    } else {
                        ElMessage.error(res.msg || '删除失败');
                    }
                })
                .catch((error) => {
                    ElMessage.error('删除失败：' + (error.message || '未知错误'));
                });
        })
        .catch(() => {
            // 用户取消删除
        });
};

const handleCalculate = () => {
    ElMessageBox.confirm('确定要重新计算销售概览统计数据吗？此操作可能需要较长时间。', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            calculating.value = true;
            calculateSalesOverview()
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('计算成功');
                        getDataList();
                    } else {
                        ElMessage.error(res.msg || '计算失败');
                    }
                })
                .catch((error) => {
                    ElMessage.error('计算失败：' + (error.message || '未知错误'));
                })
                .finally(() => {
                    calculating.value = false;
                });
        })
        .catch(() => {
            // 用户取消计算
        });
};

onMounted(() => {
    getDataList();
});
</script>

<style scoped>
.operation-scroll-bar {
    margin-bottom: 20px;
}

.operation-scroll-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.main-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
}

.dataListOnEmpty {
    text-align: center;
    padding: 40px 0;
    color: #909399;
}
</style>

