wujianwei
2025-12-24 cab8f5284fd5bef35584195246f2f5dc7ad4fd38
service/src/main/java/com/ruoyi/cwgl/service/impl/ReceivableFeeManagementServiceImpl.java
@@ -1,13 +1,22 @@
package com.ruoyi.cwgl.service.impl;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.enums.SystemDataNoEnum;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.DownloadExportUtil;
import com.ruoyi.common.utils.file.DownloadExportUtil.ExprotStatus;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.cwgl.domain.ReceivableFeeDetail;
import com.ruoyi.cwgl.domain.ReceivableFeeManagementLog;
import com.ruoyi.cwgl.domain.vo.ReceivableFeeStatisticsVo;
@@ -26,6 +35,9 @@
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.core.service.BaseService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.cwgl.mapper.ReceivableFeeManagementMapper;
import com.ruoyi.cwgl.domain.ReceivableFeeManagement;
@@ -35,6 +47,8 @@
import com.ruoyi.common.core.text.Convert;
import javax.annotation.Resource;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
/**
 * 应收费用管理Service业务层处理
@@ -66,6 +80,9 @@
    @Autowired
    private IReceivableFeeManagementLogService logService;
    @Autowired
    private RedisCache redisCache;
    /**
     * 查询应收费用管理
@@ -571,14 +588,18 @@
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importReceivableFee(List<ReceivableFeeManagement> receivableFeeList, String operName) {
        if (receivableFeeList == null || receivableFeeList.isEmpty()) {
            return "导入数据不能为空!";
            throw new ServiceException("导入应收费用数据不能为空!");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        // 获取当前日期
        Date now = DateUtils.getNowDate();
        
        for (ReceivableFeeManagement receivableFee : receivableFeeList) {
            try {
@@ -587,7 +608,7 @@
                receivableFee.setSystemNo(noByKey);
                
                // 设置创建时间和创建人
                receivableFee.setCreateTime(DateUtils.getNowDate());
                receivableFee.setCreateTime(now);
                receivableFee.setCreateBy(operName);
                
                // 计算应收金额字符串描述
@@ -596,19 +617,24 @@
                    receivableFee.setReceivableAmountStr(receivableAmountStr);
                }
                
                // 新增记录(不做存在性判断)
                int result = insertReceivableFeeManagement(receivableFee);
                // 插入主表数据
                receivableFeeManagementMapper.insertReceivableFeeManagement(receivableFee);
                
                if (result > 0) {
                    successNum++;
                    successMsg.append("<br/>" + successNum + ". 系统编号 " + receivableFee.getSystemNo() + " 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + ". 系统编号 " + receivableFee.getSystemNo() + " 导入失败");
                // 处理明细数据(如果有)
                if (receivableFee.getReceivableFeeDetailList() != null && !receivableFee.getReceivableFeeDetailList().isEmpty()) {
                    for (ReceivableFeeDetail detail : receivableFee.getReceivableFeeDetailList()) {
                        detail.setReceivableFeeId(receivableFee.getId());
                        detail.setCreateBy(operName);
                        detail.setCreateTime(now);
                        receivableFeeDetailService.insertReceivableFeeDetail(detail);
                }
                }
                successNum++;
                successMsg.append("<br/>" + successNum + ".应收费用 " + receivableFee.getSystemNo() + " 导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + ". 系统编号 " + (receivableFee.getSystemNo() != null ? receivableFee.getSystemNo() : "未知") + " 导入失败:";
                String msg = "<br/>" + failureNum + ".应收费用 " + receivableFee.getSystemNo() + " 导入失败:";
                failureMsg.append(msg + e.getMessage());
                logger.error(msg, e);
            }
@@ -624,7 +650,7 @@
    }
    /**
     * 下载导入模板
     * 下载导入模板(包含Sheet1主表和Sheet2明细表)
     * 
     * @param exportKey 导出功能的唯一标识
     */
@@ -632,9 +658,210 @@
    @Async
    @Override
    public void importTemplate(String exportKey) {
        super.export(ReceivableFeeManagement.class, exportKey, "receivableFeeManagementTemplate", (pageNum) -> {
            // 返回空列表,只导出模板结构
            return new ArrayList<ReceivableFeeManagement>();
        });
        String fileName = ExcelUtil.encodeFileName("应收费用导入模板");
        // 设置当前任务为"下载中"状态
        DownloadExportUtil.deleteDownloadFile(redisCache, exportKey, ExprotStatus.XZZ.getStatus());
        try {
            // 创建多Sheet导入模板
            createMultiSheetImportTemplate(exportKey,fileName);
            // 设置下载完成状态
            DownloadExportUtil.setDownloadFile(redisCache, exportKey, fileName);
            logger.info("导入模板导出完成: {}, file: {}", exportKey, fileName);
        } catch (Exception e) {
            logger.error("导入模板导出失败: {}, error: {}", exportKey, e.getMessage(), e);
            DownloadExportUtil.deleteDownloadFile(redisCache, exportKey, ExprotStatus.XZYC.getStatus()); // 设置失败状态
            throw e;
        }
    }
    /**
     * 创建多Sheet导入模板
     * 包含Sheet1:应收费用主表模板
     * 包含Sheet2:应收费用明细表模板
     *
     * @param exportKey 导出功能的唯一标识
     * @param fileName
     */
    private void createMultiSheetImportTemplate(String exportKey, String fileName) {
        try {
            // 创建新的工作簿,包含两个Sheet
            SXSSFWorkbook workbook = new SXSSFWorkbook(1000);
            // 创建主表Sheet
            Sheet mainSheet = workbook.createSheet("应收费用主表");
            createMainSheetTemplateWithExcelUtil(mainSheet);
            // 创建明细表Sheet
            Sheet detailSheet = workbook.createSheet("应收费用明细");
            createDetailSheetTemplateWithExcelUtil(detailSheet);
            // 保存工作簿到文件
            try (OutputStream out = Files.newOutputStream(Paths.get(getAbsoluteFile(fileName)))) {
                workbook.write(out);
            }
            workbook.close();
        } catch (Exception e) {
            logger.error("创建多Sheet导入模板失败: {}", e.getMessage(), e);
            throw new UtilException("导入模板生成失败!");
        }
    }
    /**
     * 使用ExcelUtil创建主表Sheet模板
     *
     * @param sheet Sheet对象
     */
    private void createMainSheetTemplateWithExcelUtil(Sheet sheet) {
        try {
            // 使用ExcelUtil创建主表模板
            ExcelUtil<ReceivableFeeManagement> mainSheetUtil = new ExcelUtil<>(ReceivableFeeManagement.class);
            // 初始化ExcelUtil
            mainSheetUtil.initialize("应收费用主表", "应收费用主表导入模板(请勿修改序号列)", Excel.Type.EXPORT);
            // 通过反射获取workbook字段
            Field workbookField = ExcelUtil.class.getDeclaredField("workbook");
            workbookField.setAccessible(true);
            SXSSFWorkbook excelUtilWorkbook = (SXSSFWorkbook) workbookField.get(mainSheetUtil);
            // 获取ExcelUtil生成的Sheet
            Sheet generatedSheet = excelUtilWorkbook.getSheetAt(0);
            // 复制标题行到目标Sheet
            copyRow(generatedSheet.getRow(0), sheet.createRow(0));
            // 复制表头行到目标Sheet
            copyRow(generatedSheet.getRow(1), sheet.createRow(1));
            // 添加说明行
            Row instructionRow = sheet.createRow(2);
            Cell instructionCell = instructionRow.createCell(0);
            instructionCell.setCellValue("说明:序号用于关联主表和明细表,请确保主表和明细表中的序号一致");
            // 设置列宽
            for (int i = 0; i < generatedSheet.getRow(1).getLastCellNum(); i++) {
                sheet.setColumnWidth(i, generatedSheet.getColumnWidth(i));
            }
        } catch (Exception e) {
            logger.error("使用ExcelUtil创建主表模板失败: {}", e.getMessage(), e);
            throw new UtilException("主表模板生成失败!");
        }
    }
    /**
     * 使用ExcelUtil创建明细表Sheet模板
     *
     * @param sheet Sheet对象
     */
    private void createDetailSheetTemplateWithExcelUtil(Sheet sheet) {
        try {
            // 使用ExcelUtil创建明细表模板
            ExcelUtil<ReceivableFeeDetail> detailSheetUtil = new ExcelUtil<>(ReceivableFeeDetail.class);
            // 初始化ExcelUtil
            detailSheetUtil.initialize("应收费用明细", "应收费用明细表导入模板(序号与主表对应)", Excel.Type.EXPORT);
            // 通过反射获取workbook字段
            Field workbookField = ExcelUtil.class.getDeclaredField("workbook");
            workbookField.setAccessible(true);
            SXSSFWorkbook excelUtilWorkbook = (SXSSFWorkbook) workbookField.get(detailSheetUtil);
            // 获取ExcelUtil生成的Sheet
            Sheet generatedSheet = excelUtilWorkbook.getSheetAt(0);
            // 复制标题行到目标Sheet
            copyRow(generatedSheet.getRow(0), sheet.createRow(0));
            // 复制表头行到目标Sheet
            copyRow(generatedSheet.getRow(1), sheet.createRow(1));
            // 添加说明行
            Row instructionRow = sheet.createRow(2);
            Cell instructionCell = instructionRow.createCell(0);
            instructionCell.setCellValue("说明:序号必须与主表中的序号一致,用于关联主表和明细表数据");
            // 设置列宽
            for (int i = 0; i < generatedSheet.getRow(1).getLastCellNum(); i++) {
                sheet.setColumnWidth(i, generatedSheet.getColumnWidth(i));
            }
        } catch (Exception e) {
            logger.error("使用ExcelUtil创建明细表模板失败: {}", e.getMessage(), e);
            throw new UtilException("明细表模板生成失败!");
        }
    }
    /**
     * 复制行内容
     *
     * @param sourceRow 源行
     * @param targetRow 目标行
     */
    private void copyRow(Row sourceRow, Row targetRow) {
        if (sourceRow == null) return;
        targetRow.setHeight(sourceRow.getHeight());
        for (int i = 0; i < sourceRow.getLastCellNum(); i++) {
            Cell sourceCell = sourceRow.getCell(i);
            if (sourceCell != null) {
                Cell targetCell = targetRow.createCell(i);
                copyCell(sourceCell, targetCell);
            }
        }
    }
    /**
     * 复制单元格内容和样式
     *
     * @param sourceCell 源单元格
     * @param targetCell 目标单元格
     */
    private void copyCell(Cell sourceCell, Cell targetCell) {
        // 复制单元格样式
        targetCell.setCellStyle(sourceCell.getCellStyle());
        // 复制单元格值
        switch (sourceCell.getCellType()) {
            case STRING:
                targetCell.setCellValue(sourceCell.getStringCellValue());
                break;
            case NUMERIC:
                targetCell.setCellValue(sourceCell.getNumericCellValue());
                break;
            case BOOLEAN:
                targetCell.setCellValue(sourceCell.getBooleanCellValue());
                break;
            case FORMULA:
                targetCell.setCellFormula(sourceCell.getCellFormula());
                break;
            default:
                targetCell.setCellValue(sourceCell.getStringCellValue());
        }
    }
    /**
     * 获取文件的绝对路径
     *
     * @param fileName 文件名
     * @return 绝对路径
     */
    private String getAbsoluteFile(String fileName) {
        String downloadPath = RuoYiConfig.getDownloadPath();
        File desc = new File(downloadPath + File.separator + fileName);
        if (!desc.exists()) {
            if (!desc.getParentFile().exists()) {
                desc.getParentFile().mkdirs();
            }
        }
        return desc.getAbsolutePath();
    }
}