From 16a2b7a85d1ea7888dbc2ee3d23934032c05f3e6 Mon Sep 17 00:00:00 2001
From: huminmin <mac@MacBook-Pro.local>
Date: 星期四, 23 四月 2026 14:06:59 +0800
Subject: [PATCH] 导出销售台账送货单

---
 src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java | 1046 ++++++++++++++++++++++++++++++++++++++++++++++++++++++---
 1 files changed, 981 insertions(+), 65 deletions(-)

diff --git a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
index 52ec03e..3b6ea8c 100644
--- a/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
+++ b/src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -1,34 +1,91 @@
 package com.ruoyi.sales.service.impl;
 
+import com.alibaba.excel.EasyExcel;
+import com.alibaba.excel.ExcelWriter;
+import com.alibaba.excel.write.metadata.WriteSheet;
+import com.alibaba.excel.write.metadata.fill.FillConfig;
+import com.alibaba.excel.write.metadata.fill.FillWrapper;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
+import com.baomidou.mybatisplus.core.toolkit.Wrappers;
+import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import com.deepoove.poi.XWPFTemplate;
+import com.deepoove.poi.config.Configure;
+import com.ruoyi.account.pojo.AccountIncome;
+import com.ruoyi.account.service.AccountIncomeService;
 import com.ruoyi.basic.mapper.CustomerMapper;
+import com.ruoyi.basic.mapper.ProductMapper;
+import com.ruoyi.basic.mapper.ProductModelMapper;
 import com.ruoyi.basic.pojo.Customer;
+import com.ruoyi.basic.pojo.ProductModel;
+import com.ruoyi.common.enums.FileNameType;
 import com.ruoyi.common.exception.base.BaseException;
+import com.ruoyi.common.utils.DateUtils;
+import com.ruoyi.common.utils.HackLoopTableRenderPolicy;
+import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.common.utils.StringUtils;
-import com.ruoyi.sales.dto.SalesLedgerDto;
-import com.ruoyi.sales.mapper.SalesLedgerMapper;
-import com.ruoyi.sales.mapper.SalesLedgerProductMapper;
-import com.ruoyi.sales.pojo.SalesLedger;
-import com.ruoyi.sales.pojo.SalesLedgerProduct;
+import com.ruoyi.common.utils.poi.ExcelUtil;
+import com.ruoyi.device.execl.DeviceMaintenanceExeclDto;
+import com.ruoyi.framework.security.LoginUser;
+import com.ruoyi.framework.web.domain.AjaxResult;
+import com.ruoyi.other.mapper.TempFileMapper;
+import com.ruoyi.other.pojo.TempFile;
+import com.ruoyi.production.mapper.*;
+import com.ruoyi.production.service.ProductionProductMainService;
+import com.ruoyi.project.system.domain.SysDept;
+import com.ruoyi.project.system.domain.SysUser;
+import com.ruoyi.project.system.mapper.SysDeptMapper;
+import com.ruoyi.project.system.mapper.SysUserMapper;
+import com.ruoyi.quality.mapper.QualityInspectMapper;
+import com.ruoyi.sales.dto.*;
+import com.ruoyi.sales.mapper.*;
+import com.ruoyi.sales.pojo.*;
+import com.ruoyi.sales.service.ISalesLedgerProductService;
 import com.ruoyi.sales.service.ISalesLedgerService;
-import lombok.AllArgsConstructor;
+import com.ruoyi.sales.vo.ShippingNoteVo;
+import com.ruoyi.stock.mapper.StockInventoryMapper;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.io.FilenameUtils;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.ss.util.CellRangeAddress;
+import org.apache.poi.xssf.usermodel.XSSFSheet;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.core.script.DefaultRedisScript;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.multipart.MultipartFile;
 
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
 import java.lang.reflect.Field;
 import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
 import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.YearMonth;
+import java.time.ZoneId;
 import java.time.format.DateTimeFormatter;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
 import java.util.function.Function;
 import java.util.stream.Collectors;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
 
 /**
  * 閿�鍞彴璐ervice涓氬姟灞傚鐞�
@@ -37,30 +94,94 @@
  * @date 2025-05-08
  */
 @Service
-@AllArgsConstructor
+@RequiredArgsConstructor
+@Slf4j
 public class SalesLedgerServiceImpl extends ServiceImpl<SalesLedgerMapper, SalesLedger> implements ISalesLedgerService {
+    private final AccountIncomeService accountIncomeService;
 
-    private SalesLedgerMapper salesLedgerMapper;
+    private final SalesLedgerMapper salesLedgerMapper;
 
-    private CustomerMapper customerMapper;
+    private final CustomerMapper customerMapper;
 
-    private SalesLedgerProductMapper salesLedgerProductMapper;
+    private final SalesLedgerProductMapper salesLedgerProductMapper;
+    private final SalesLedgerProductServiceImpl salesLedgerProductServiceImpl;
+
+    private final CommonFileMapper commonFileMapper;
+
+    private final TempFileMapper tempFileMapper;
+
+    private final ReceiptPaymentMapper receiptPaymentMapper;
+
+    private final ShippingInfoServiceImpl shippingInfoServiceImpl;
+
+    private final CommonFileServiceImpl commonFileService;
+
+    private final ShippingInfoMapper shippingInfoMapper;
+
+    private final InvoiceLedgerMapper invoiceLedgerMapper;
+
+    private final SalesLedgerSchedulingMapper salesLedgerSchedulingMapper;
+
+    private final SalesLedgerWorkMapper salesLedgerWorkMapper;
+
+    private final SalesLedgerProductionAccountingMapper salesLedgerProductionAccountingMapper;
+
+    private final InvoiceRegistrationProductMapper invoiceRegistrationProductMapper;
+
+    private final InvoiceRegistrationMapper invoiceRegistrationMapper;
+
+    private final ProductOrderMapper productOrderMapper;
+
+    private final ProcessRouteMapper processRouteMapper;
+    private final ProductProcessRouteMapper productProcessRouteMapper;
+
+    private final ProcessRouteItemMapper processRouteItemMapper;
+
+    private final ProductProcessRouteItemMapper productProcessRouteItemMapper;
+
+    private final ProductWorkOrderMapper productWorkOrderMapper;
+
+    private final ProductionProductMainMapper productionProductMainMapper;
+
+    private final ProductionProductOutputMapper productionProductOutputMapper;
+
+    private final ProductionProductInputMapper productionProductInputMapper;
+
+    private final QualityInspectMapper qualityInspectMapper;
+
+    private final StockInventoryMapper stockInventoryMapper;
+
+    private ISalesLedgerProductService salesLedgerProductService;
+
+
+    @Autowired
+    private SysDeptMapper sysDeptMapper;
+
+    @Value("${file.upload-dir}")
+    private String uploadDir;
 
     private static final String LOCK_PREFIX = "contract_no_lock:";
     private static final long LOCK_WAIT_TIMEOUT = 10; // 閿佺瓑寰呰秴鏃舵椂闂达紙绉掞級
     private static final long LOCK_EXPIRE_TIME = 30;  // 閿佽嚜鍔ㄨ繃鏈熸椂闂达紙绉掞級
 
     private final RedisTemplate<String, String> redisTemplate;
+    @Autowired
+    private ProductModelMapper productModelMapper;
+
+    @Autowired
+    private ProductMapper productMapper;
+    @Autowired
+    private ProductStructureMapper productStructureMapper;
+    @Autowired
+    private ProductionProductMainService productionProductMainService;
+    ;
 
     @Override
     public List<SalesLedger> selectSalesLedgerList(SalesLedgerDto salesLedgerDto) {
-        LambdaQueryWrapper<SalesLedger> queryWrapper = new LambdaQueryWrapper<>();
-        if (StringUtils.isNotBlank(salesLedgerDto.getCustomerName())) {
-            queryWrapper.eq(SalesLedger::getCustomerName, salesLedgerDto.getCustomerName());
-        }
-        return salesLedgerMapper.selectList(queryWrapper);
+        return salesLedgerMapper.selectSalesLedgerList(salesLedgerDto);
     }
 
+    @Override
     public SalesLedgerDto getSalesLedgerWithProducts(SalesLedgerDto salesLedgerDto) {
         // 1. 鏌ヨ涓昏〃
         SalesLedger salesLedger = salesLedgerMapper.selectById(salesLedgerDto.getId());
@@ -71,16 +192,636 @@
         // 2. 鏌ヨ瀛愯〃
         LambdaQueryWrapper<SalesLedgerProduct> productWrapper = new LambdaQueryWrapper<>();
         productWrapper.eq(SalesLedgerProduct::getSalesLedgerId, salesLedger.getId());
+        productWrapper.eq(SalesLedgerProduct::getType, 1);
         List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
+        for (SalesLedgerProduct product : products) {
+            product.setOriginalNoInvoiceNum(product.getNoInvoiceNum());
+            // 鎻愪緵涓存椂鏈紑绁ㄦ暟锛屾湭寮�绁ㄩ噾棰濅緵鍓嶆璁$畻
+            product.setTempnoInvoiceAmount(product.getNoInvoiceAmount());
+            product.setTempNoInvoiceNum(product.getNoInvoiceNum());
+            product.setRegister(SecurityUtils.getLoginUser().getUser().getNickName());
+            product.setRegisterDate(LocalDateTime.now());
+            // 鍙戣揣淇℃伅
+            ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new LambdaQueryWrapper<ShippingInfo>()
+                    .eq(ShippingInfo::getSalesLedgerProductId, product.getId())
+                    .orderByDesc(ShippingInfo::getCreateTime)
+                    .last("limit 1"));
+            if (shippingInfo != null) {
+                product.setShippingStatus(shippingInfo.getStatus());
+            }
 
-        // 3. 杞崲 DTO
+            ProductModel productModel = productModelMapper.selectById(product.getProductModelId());
+            product.setMaterialCode(productModel.getMaterialCode());
+        }
+
+        // 3.鏌ヨ涓婁紶鏂囦欢
+        LambdaQueryWrapper<CommonFile> salesLedgerFileWrapper = new LambdaQueryWrapper<>();
+        salesLedgerFileWrapper.eq(CommonFile::getCommonId, salesLedger.getId())
+                .eq(CommonFile::getType, FileNameType.SALE.getValue());
+        List<CommonFile> salesLedgerFiles = commonFileMapper.selectList(salesLedgerFileWrapper);
+
+        // 4. 杞崲 DTO
         SalesLedgerDto resultDto = new SalesLedgerDto();
         BeanUtils.copyProperties(salesLedger, resultDto);
         if (!products.isEmpty()) {
             resultDto.setHasChildren(true);
             resultDto.setProductData(products);
+            resultDto.setSalesLedgerFiles(salesLedgerFiles);
         }
         return resultDto;
+    }
+
+    @Override
+    public void exportShippingNote(HttpServletResponse response, List<Long> ids) {
+        try {
+            List<SalesLedger> ledgerList = salesLedgerMapper.selectBatchIds(ids);
+            String fileName = "閫佽揣鍗�.xlsx";
+            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
+            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
+            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
+
+            // 鍥哄畾浣跨敤 XSSFWorkbook
+            XSSFWorkbook workbook = new XSSFWorkbook();
+
+            for (SalesLedger ledger : ledgerList) {
+                XSSFSheet sheet = workbook.createSheet(ledger.getSalesContractNo());
+
+                sheet.setColumnWidth(0, 2500);
+                sheet.setColumnWidth(1, 4000);
+                sheet.setColumnWidth(2, 9000);
+                sheet.setColumnWidth(3, 2500);
+                sheet.setColumnWidth(4, 3000);
+                sheet.setColumnWidth(5, 4500);
+                sheet.setColumnWidth(6, 3500);
+
+                // 鏍峰紡
+                CellStyle companyTitle = createBaseStyle(workbook, "瀹嬩綋", (short) 20, true, true);
+                CellStyle billTitle = createBaseStyle(workbook, "瀹嬩綋", (short) 18, true, true);
+                CellStyle headerStyle = createBorderStyle(workbook, "瀹嬩綋", (short) 12, true, true);
+                CellStyle dataCenterStyle = createBorderStyle(workbook, "瀹嬩綋", (short) 11, false, true);
+                CellStyle noBorder = createNoBorderStyle(workbook);
+                CellStyle dashStyle = createDashBottomStyle(workbook);
+
+                // 鏍囬
+                Row row0 = sheet.createRow(0);
+                row0.createCell(0).setCellValue("婀栧崡楣忓垱鐢靛瓙鏈夐檺鍏徃");
+                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
+                fillMergeRange(sheet, 0, 0, 0, 6, companyTitle);
+
+                Row row1 = sheet.createRow(1);
+                row1.createCell(0).setCellValue("閫� 璐� 鍗�");
+                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));
+                fillMergeRange(sheet, 1, 1, 0, 6, billTitle);
+
+                Customer customer = customerMapper.selectById(ledger.getCustomerId());
+
+                Row row2 = sheet.createRow(2);
+                row2.createCell(0).setCellValue("瀹㈡埛鍚嶇О锛�" + ledger.getCustomerName());
+                row2.createCell(4).setCellValue("鍗曟嵁缂栧彿锛�" + ledger.getSalesContractNo());
+
+                Row row3 = sheet.createRow(3);
+                row3.createCell(0).setCellValue("閫佽揣鍦板潃锛�" + customer.getCompanyAddress());
+                row3.createCell(4).setCellValue("閫佽揣鏃ユ湡锛�" + formatDate(LocalDate.now()));
+
+                Row row4 = sheet.createRow(4);
+                row4.createCell(0).setCellValue("鑱旂郴鏂瑰紡锛�" + customer.getContactPerson() + " " + customer.getContactPhone());
+                row4.createCell(4).setCellValue("鑱旂郴鐢佃瘽锛�" + customer.getCompanyPhone());
+
+                Row row5 = sheet.createRow(5);
+                row5.createCell(0).setCellValue("閫佽揣鍗曚綅锛氭箹鍗楅箯鍒涚數瀛愭湁闄愬叕鍙�");
+                Row row6 = sheet.createRow(6);
+                row6.createCell(0).setCellValue("鍦板潃锛氭箹鍗楃渷鑰掗槼甯傚垱鏂板垱涓氬洯A1鏍�");
+                Row row7 = sheet.createRow(7);
+                row7.createCell(0).setCellValue("璐х墿璇︾粏淇℃伅锛�");
+
+                // 琛ㄥご
+                int tableStart = 8;
+                Row headerRow = sheet.createRow(tableStart);
+                String[] headers = {"搴忓彿", "鐗╂枡缂栧彿", "鍝佸悕/瑙勬牸", "鍗曚綅", "鏁伴噺", "璁㈠崟鍙�", "鍏卞洓鑱�"};
+                for (int i = 0; i < headers.length; i++) {
+                    Cell hc = headerRow.createCell(i);
+                    hc.setCellValue(headers[i]);
+                    hc.setCellStyle(i == 6 ? noBorder : headerStyle);
+                }
+
+                // 鏌ヨ鍟嗗搧
+                SalesLedgerProduct cond = new SalesLedgerProduct();
+                cond.setSalesLedgerId(ledger.getId());
+                List<SalesLedgerProduct> productList = salesLedgerProductServiceImpl.selectSalesLedgerProductList(cond);
+
+                BigDecimal totalQuantity = BigDecimal.ZERO;
+                for (SalesLedgerProduct product : productList) {
+                    totalQuantity = totalQuantity.add(product.getQuantity() == null ? BigDecimal.ZERO : product.getQuantity());
+                }
+
+                int currentRow = tableStart + 1;
+                String[] fourNames = {"瀛樻牴", "鍥炲崟", "瀹㈡埛", "浠撳簱"};
+                int minDataRow = 5;
+                int totalNeedRow = Math.max(minDataRow, fourNames.length);
+
+                // 鏁版嵁琛� + 鍥哄畾鍥涜仈琛�
+                for (int i = 0; i < totalNeedRow; i++) {
+                    SalesLedgerProduct p = i < productList.size() ? productList.get(i) : null;
+                    Row dataRow = sheet.createRow(currentRow);
+
+                    // 鍓�6鍒楄祴鍊�
+                    if (p != null) {
+                        String materialCode = "";
+                        if (p.getProductModelId() != null) {
+                            ProductModel m = productModelMapper.selectById(p.getProductModelId());
+                            if (m != null) {
+                                materialCode = m.getMaterialCode();
+                            }
+                        }
+                        dataRow.createCell(0).setCellValue(i + 1);
+                        dataRow.createCell(1).setCellValue(materialCode);
+                        dataRow.createCell(2).setCellValue(p.getProductCategory() + "/" + p.getSpecificationModel());
+                        dataRow.createCell(3).setCellValue(p.getUnit());
+                        dataRow.createCell(4).setCellValue(p.getQuantity() == null ? 0 : p.getQuantity().doubleValue());
+                        dataRow.createCell(5).setCellValue(ledger.getSalesContractNo());
+                    } else {
+                        for (int c = 0; c <= 5; c++) {
+                            dataRow.createCell(c);
+                        }
+                    }
+
+                    // 鍓�6鍒楁牱寮�
+                    for (int c = 0; c <= 5; c++) {
+                        dataRow.getCell(c).setCellStyle(dataCenterStyle);
+                    }
+
+                    // 鍏卞洓鑱斿垪
+                    Cell fourCell = dataRow.createCell(6);
+                    if (i < fourNames.length) {
+                        fourCell.setCellValue(fourNames[i]);
+                        fourCell.setCellStyle(dashStyle);
+                    } else {
+                        fourCell.setCellStyle(noBorder);
+                    }
+
+                    currentRow++;
+                }
+
+                // 鍚堣琛�
+                Row totalRow = sheet.createRow(currentRow);
+                sheet.addMergedRegion(new CellRangeAddress(currentRow, currentRow, 0, 3));
+                totalRow.createCell(0).setCellValue("鍚堣");
+                totalRow.createCell(4).setCellValue(totalQuantity.doubleValue());
+                fillMergeRange(sheet, currentRow, currentRow, 0, 5, dataCenterStyle);
+                totalRow.createCell(6).setCellStyle(noBorder);
+
+                // 澶囨敞
+                currentRow++;
+                Row remarkRow = sheet.createRow(currentRow);
+                remarkRow.createCell(0).setCellValue("澶囨敞锛氳吹鍙稿湪鏀惰揣鍚庤鍗冲埢鏍稿疄鏁伴噺鍙婂搧璐紝鑻ユ湁寮傝锛岃鍦�3鏃ュ唴鎻愬嚭锛屽惁鍒欒涓烘敹鍙椼��");
+                sheet.addMergedRegion(new CellRangeAddress(currentRow, currentRow, 0, 6));
+
+                currentRow++;
+                Row sign1 = sheet.createRow(currentRow);
+                sign1.createCell(0).setCellValue("閫佽揣鍗曚綅锛堢绔狅級锛�");
+                sign1.createCell(5).setCellValue("鏀惰揣鍗曚綅锛�");
+
+                currentRow++;
+                Row sign2 = sheet.createRow(currentRow);
+                sign2.createCell(0).setCellValue("閫佽揣浜猴細");
+                sign2.createCell(5).setCellValue("鏀惰揣浜猴細");
+            }
+
+            workbook.write(response.getOutputStream());
+            workbook.close();
+
+        } catch (Exception e) {
+            log.error("鎵归噺瀵煎嚭閫佽揣鍗曞紓甯�", e);
+            throw new BaseException("鎵归噺瀵煎嚭澶辫触");
+        }
+    }
+
+    // 宸ュ叿绫讳笉鍔�
+    private CellStyle createBaseStyle(Workbook workbook, String fontName, short fontSize, boolean bold, boolean center) {
+        CellStyle style = workbook.createCellStyle();
+        Font font = workbook.createFont();
+        font.setFontName(fontName);
+        font.setFontHeightInPoints(fontSize);
+        font.setBold(bold);
+        style.setFont(font);
+        if (center) {
+            style.setAlignment(HorizontalAlignment.CENTER);
+            style.setVerticalAlignment(VerticalAlignment.CENTER);
+        }
+        return style;
+    }
+
+    private CellStyle createBorderStyle(Workbook workbook, String fontName, short fontSize, boolean bold, boolean center) {
+        CellStyle style = createBaseStyle(workbook, fontName, fontSize, bold, center);
+        style.setBorderTop(BorderStyle.THIN);
+        style.setBorderBottom(BorderStyle.THIN);
+        style.setBorderLeft(BorderStyle.THIN);
+        style.setBorderRight(BorderStyle.THIN);
+        return style;
+    }
+
+    private CellStyle createNoBorderStyle(Workbook workbook) {
+        return createBaseStyle(workbook, "瀹嬩綋", (short) 11, false, false);
+    }
+
+    private CellStyle createDashBottomStyle(Workbook workbook) {
+        CellStyle style = createNoBorderStyle(workbook);
+        style.setBorderBottom(BorderStyle.DASHED);
+        return style;
+    }
+
+    private void fillMergeRange(Sheet sheet, int startR, int endR, int startC, int endC, CellStyle style) {
+        for (int r = startR; r <= endR; r++) {
+            Row row = sheet.getRow(r) == null ? sheet.createRow(r) : sheet.getRow(r);
+            for (int c = startC; c <= endC; c++) {
+                Cell cell = row.getCell(c) == null ? row.createCell(c) : row.getCell(c);
+                cell.setCellStyle(style);
+            }
+        }
+    }
+
+    public static String formatDate(LocalDate date) {
+        if (date == null) {
+            return null;
+        }
+        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
+    }
+    
+    /**
+     * 璁剧疆鍗曞厓鏍兼牱寮�
+     */
+    private void setCellStyle(Cell cell, boolean isHeader, boolean isTitle) {
+        Workbook workbook = cell.getSheet().getWorkbook();
+        CellStyle style = workbook.createCellStyle();
+        
+        // 璁剧疆瀵归綈鏂瑰紡
+        style.setAlignment(HorizontalAlignment.CENTER);
+        style.setVerticalAlignment(VerticalAlignment.CENTER);
+        
+        // 璁剧疆杈规
+        style.setBorderTop(BorderStyle.THIN);
+        style.setBorderBottom(BorderStyle.THIN);
+        style.setBorderLeft(BorderStyle.THIN);
+        style.setBorderRight(BorderStyle.THIN);
+        
+        // 璁剧疆瀛椾綋
+        Font font = workbook.createFont();
+        font.setFontName("瀹嬩綋");
+        if (isTitle) {
+            font.setFontHeightInPoints((short) 16);
+            font.setBold(true);
+        } else if (isHeader) {
+            font.setFontHeightInPoints((short) 12);
+            font.setBold(true);
+        } else {
+            font.setFontHeightInPoints((short) 11);
+        }
+        style.setFont(font);
+        
+        cell.setCellStyle(style);
+    }
+    
+    
+    /**
+     * 閫佽揣鍗曟牱寮忓鐞嗗櫒
+     */
+    public static class ShippingNoteStyleHandler implements com.alibaba.excel.write.handler.CellWriteHandler {
+        @Override
+        public void beforeCellCreate(com.alibaba.excel.write.metadata.holder.WriteSheetHolder writeSheetHolder, com.alibaba.excel.write.metadata.holder.WriteTableHolder writeTableHolder, org.apache.poi.ss.usermodel.Row row, com.alibaba.excel.metadata.Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead) {
+        }
+        
+//        @Override
+//        public void afterCellDispose(com.alibaba.excel.write.metadata.holder.WriteSheetHolder writeSheetHolder, com.alibaba.excel.write.metadata.holder.WriteTableHolder writeTableHolder, org.apache.poi.ss.usermodel.Cell cell, com.alibaba.excel.metadata.Head head, Integer relativeRowIndex, Boolean isHead) {
+//            org.apache.poi.ss.usermodel.Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
+//            org.apache.poi.ss.usermodel.Sheet sheet = writeSheetHolder.getSheet();
+//
+//            // 璁剧疆鍒楀
+//            sheet.setColumnWidth(0, 6000); // 搴忓彿
+//            sheet.setColumnWidth(1, 6000); // 鐗╂枡缂栧彿
+//            sheet.setColumnWidth(2, 10000); // 鍝佸悕/瑙勬牸
+//            sheet.setColumnWidth(3, 4000); // 鍗曚綅
+//            sheet.setColumnWidth(4, 4000); // 鏁伴噺
+//            sheet.setColumnWidth(5, 6000); // 璁㈠崟鍙�
+//            sheet.setColumnWidth(6, 4000); // 鍏卞洓鑱�
+//
+//            // 璁剧疆鍗曞厓鏍兼牱寮�
+//            org.apache.poi.ss.usermodel.CellStyle style = workbook.createCellStyle();
+//            style.setAlignment(org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER);
+//            style.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
+//            style.setBorderTop(org.apache.poi.ss.usermodel.BorderStyle.THIN);
+//            style.setBorderBottom(org.apache.poi.ss.usermodel.BorderStyle.THIN);
+//            style.setBorderLeft(org.apache.poi.ss.usermodel.BorderStyle.THIN);
+//            style.setBorderRight(org.apache.poi.ss.usermodel.BorderStyle.THIN);
+//
+//            // 璁剧疆瀛椾綋
+//            org.apache.poi.ss.usermodel.Font font = workbook.createFont();
+//            font.setFontName("瀹嬩綋");
+//            font.setFontHeightInPoints((short) 11);
+//            style.setFont(font);
+//
+//            cell.setCellStyle(style);
+//        }
+    }
+
+    @Override
+    public List<Map<String, Object>> getSalesNo() {
+        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.select(SalesLedger::getId, SalesLedger::getSalesContractNo, SalesLedger::getProjectName);
+
+        // 鑾峰彇鍘熷鏌ヨ缁撴灉
+        List<Map<String, Object>> result = salesLedgerMapper.selectMaps(queryWrapper);
+
+        // 灏嗕笅鍒掔嚎鍛藉悕杞崲涓洪┘宄板懡鍚�
+        return result.stream().map(map -> map.entrySet().stream()
+                .collect(Collectors.toMap(
+                        entry -> underlineToCamel(entry.getKey()),
+                        Map.Entry::getValue))
+        ).collect(Collectors.toList());
+    }
+
+    @Override
+    public BigDecimal getContractAmount() {
+        LocalDate now = LocalDate.now();
+        YearMonth currentMonth = YearMonth.from(now);
+
+        // 鍒涘缓LambdaQueryWrapper
+        LambdaQueryWrapper<SalesLedger> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.ge(SalesLedger::getEntryDate, currentMonth.atDay(1).atStartOfDay())  // 澶т簬绛変簬鏈湀绗竴澶�
+                .lt(SalesLedger::getEntryDate, currentMonth.plusMonths(1).atDay(1).atStartOfDay()); // 灏忎簬涓嬫湀绗竴澶�
+
+        // 鎵ц鏌ヨ骞惰绠楁�诲拰
+        List<SalesLedger> salesLedgers = salesLedgerMapper.selectList(queryWrapper);
+
+        BigDecimal totalContractAmount = salesLedgers.stream()
+                .map(SalesLedger::getContractAmount)
+                .filter(Objects::nonNull)
+                .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+        return totalContractAmount;
+    }
+
+    @Override
+    public List getTopFiveList() {
+        // 鏌ヨ鍘熷鏁版嵁
+        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
+        queryWrapper.select(SalesLedger::getCustomerId,
+                        SalesLedger::getCustomerName,
+                        SalesLedger::getContractAmount)
+                .orderByDesc(SalesLedger::getContractAmount);
+        List<SalesLedger> records = salesLedgerMapper.selectList(queryWrapper);
+
+        // 鎸夊鎴稩D鍒嗙粍骞惰仛鍚堥噾棰�
+        Map<Long, GroupedCustomer> groupedMap = new LinkedHashMap<>(); // 浣跨敤LinkedHashMap淇濇寔鎺掑簭
+        for (SalesLedger record : records) {
+            groupedMap.computeIfAbsent(record.getCustomerId(),
+                            k -> new GroupedCustomer(record.getCustomerId(), record.getCustomerName()))
+                    .addAmount(record.getContractAmount());
+        }
+
+        // 杞崲涓虹粨鏋滃垪琛ㄥ苟鍙栧墠5
+        return groupedMap.values().stream()
+                .sorted(Comparator.comparing(GroupedCustomer::getTotalAmount).reversed())
+                .limit(5)
+                .map(customer -> {
+                    Map<String, Object> result = new HashMap<>();
+                    result.put("customerId", customer.getCustomerId());
+                    result.put("customerName", customer.getCustomerName());
+                    result.put("totalAmount", customer.getTotalAmount());
+                    return result;
+                })
+                .collect(Collectors.toList());
+    }
+
+    @Override
+    public List<MonthlyAmountDto> getAmountHalfYear(Integer type) {
+
+        LocalDate now = LocalDate.now();
+        List<MonthlyAmountDto> result = new ArrayList<>();
+
+        for (int i = 5; i >= 0; i--) {
+            YearMonth yearMonth = YearMonth.from(now.minusMonths(i));
+            LocalDateTime startTime = yearMonth.atDay(1).atStartOfDay();
+            LocalDateTime endTime = yearMonth.atEndOfMonth().atTime(23, 59, 59);
+
+            //  鍥炴閲戦
+            LambdaQueryWrapper<ReceiptPayment> receiptPaymentQuery = new LambdaQueryWrapper<>();
+            receiptPaymentQuery
+                    .ge(ReceiptPayment::getCreateTime, startTime)
+                    .le(ReceiptPayment::getCreateTime, endTime);
+
+            List<ReceiptPayment> receiptPayments =
+                    receiptPaymentMapper.selectList(receiptPaymentQuery);
+
+            BigDecimal receiptAmount = receiptPayments.stream()
+                    .map(ReceiptPayment::getReceiptPaymentAmount)
+                    .filter(Objects::nonNull)
+                    .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+            //  寮�绁ㄩ噾棰�
+            LambdaQueryWrapper<InvoiceLedger> invoiceLedgerQuery = new LambdaQueryWrapper<>();
+            invoiceLedgerQuery
+                    .ge(InvoiceLedger::getCreateTime, startTime)
+                    .le(InvoiceLedger::getCreateTime, endTime);
+
+            List<InvoiceLedger> invoiceLedgers =
+                    invoiceLedgerMapper.selectList(invoiceLedgerQuery);
+
+            BigDecimal invoiceAmount = invoiceLedgers.stream()
+                    .map(InvoiceLedger::getInvoiceTotal)
+                    .filter(Objects::nonNull)
+                    .reduce(BigDecimal.ZERO, BigDecimal::add);
+
+            MonthlyAmountDto dto = new MonthlyAmountDto();
+            dto.setMonth(yearMonth.format(DateTimeFormatter.ofPattern("yyyy-MM")));
+            dto.setReceiptAmount(receiptAmount);
+            dto.setInvoiceAmount(invoiceAmount);
+
+            result.add(dto);
+        }
+
+        return result;
+    }
+
+    @Override
+    public IPage<SalesLedger> selectSalesLedgerListPage(Page page, SalesLedgerDto salesLedgerDto) {
+        return salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
+    }
+
+    @Autowired
+    private SysUserMapper sysUserMapper;
+
+    @Override
+    @Transactional(rollbackFor = Exception.class)
+    public AjaxResult importData(MultipartFile file) {
+        LoginUser loginUser = SecurityUtils.getLoginUser();
+        try {
+            InputStream inputStream = file.getInputStream();
+            ExcelUtil<SalesLedgerImportDto> salesLedgerImportDtoExcelUtil = new ExcelUtil<>(SalesLedgerImportDto.class);
+            Map<String, List<SalesLedgerImportDto>> stringListMap = salesLedgerImportDtoExcelUtil.importExcelMultiSheet(Arrays.asList("閿�鍞彴璐︽暟鎹�", "閿�鍞骇鍝佹暟鎹�"), inputStream, 0);
+            if (CollectionUtils.isEmpty(stringListMap)) return AjaxResult.error("閿�鍞〃鏍间负绌猴紒");
+            // 涓氬姟灞傚悎骞�
+            List<SalesLedgerImportDto> salesLedgerImportDtoList = stringListMap.get("閿�鍞彴璐︽暟鎹�");
+            if (CollectionUtils.isEmpty(salesLedgerImportDtoList)) return AjaxResult.error("閿�鍞彴璐︽暟鎹负绌猴紒");
+            List<SalesLedgerImportDto> salesLedgerProductImportDtoList = stringListMap.get("閿�鍞骇鍝佹暟鎹�");
+            if (CollectionUtils.isEmpty(salesLedgerProductImportDtoList)) return AjaxResult.error("閿�鍞骇鍝佹暟鎹负绌猴紒");
+            // 瀹㈡埛鏁版嵁
+            List<Customer> customers = customerMapper.selectList(new LambdaQueryWrapper<Customer>().in(Customer::getCustomerName,
+                    salesLedgerImportDtoList.stream().map(SalesLedgerImportDto::getCustomerName).collect(Collectors.toList())));
+//            // 瑙勬牸鍨嬪彿鏁版嵁
+//            List<ProductModel> productModels = productModelMapper.selectList(new LambdaQueryWrapper<ProductModel>().in(ProductModel::getModel,
+//                    salesLedgerProductImportDtoList.stream().map(SalesLedgerImportDto::getSpecificationModel).collect(Collectors.toList())));
+//            // 浜у搧澶х被鏁版嵁
+//            List<Product> productList = productMapper.selectList(new LambdaQueryWrapper<Product>().in(Product::getProductName,
+//                    salesLedgerProductImportDtoList.stream().map(SalesLedgerImportDto::getProductCategory).collect(Collectors.toList())));
+            List<Map<String, Object>> list = productModelMapper.getProductAndModelList();
+            // 褰曞叆浜烘暟鎹�
+            List<SysUser> sysUsers = sysUserMapper.selectList(new LambdaQueryWrapper<SysUser>().in(SysUser::getNickName,
+                    salesLedgerImportDtoList.stream().map(SalesLedgerImportDto::getEntryPerson).collect(Collectors.toList())));
+            for (SalesLedgerImportDto salesLedgerImportDto : salesLedgerImportDtoList) {
+                SalesLedger salesLedger1 = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>()
+                        .eq(SalesLedger::getSalesContractNo, salesLedgerImportDto.getSalesContractNo())
+                        .last("LIMIT 1"));
+                if (salesLedger1 != null) {
+                    continue;
+                }
+                SalesLedger salesLedger = new SalesLedger();
+                BeanUtils.copyProperties(salesLedgerImportDto, salesLedger);
+                salesLedger.setExecutionDate(DateUtils.toLocalDate(salesLedgerImportDto.getExecutionDate()));
+                // 閫氳繃瀹㈡埛鍚嶇О鏌ヨ瀹㈡埛ID锛屽鎴峰悎鍚屽彿
+                salesLedger.setCustomerId(customers.stream()
+                        .filter(customer -> customer.getCustomerName().equals(salesLedger.getCustomerName()))
+                        .findFirst()
+                        .map(Customer::getId)
+                        .orElse(null));
+                salesLedger.setCustomerContractNo(customers.stream()
+                        .filter(customer -> customer.getCustomerName().equals(salesLedger.getCustomerName()))
+                        .findFirst()
+                        .map(Customer::getTaxpayerIdentificationNumber)
+                        .orElse(null));
+                Long aLong = sysUsers.stream()
+                        .filter(sysUser -> sysUser.getNickName().equals(salesLedger.getEntryPerson()))
+                        .findFirst()
+                        .map(SysUser::getUserId)
+                        .orElse(null);
+                if (aLong == null)
+                    throw new RuntimeException("褰曞叆浜�:" + salesLedger.getEntryPerson() + ",鏃犲搴旂敤鎴凤紒");
+                salesLedger.setEntryPerson(aLong.toString());
+                // 閿�鍞骇鍝佹暟鎹粦瀹氾紝閫氳繃閿�鍞崟鍙疯幏鍙栧搴旈攢鍞骇鍝佹暟鎹�
+                List<SalesLedgerProductImportDto> salesLedgerProductImportDtos = salesLedgerProductImportDtoList.stream()
+                        .filter(salesLedgerProductImportDto -> salesLedgerProductImportDto.getSalesContractNo().equals(salesLedger.getSalesContractNo()))
+                        .collect(Collectors.toList());
+                if (CollectionUtils.isEmpty(salesLedgerProductImportDtos))
+                    throw new RuntimeException("閿�鍞崟鍙�:" + salesLedgerImportDto.getSalesContractNo() + ",鏃犲搴斾骇鍝佹暟鎹紒");
+                salesLedger.setContractAmount(salesLedgerProductImportDtos.stream()
+                        .map(SalesLedgerProductImportDto::getTaxInclusiveTotalPrice)
+                        .reduce(BigDecimal.ZERO, BigDecimal::add));
+                salesLedgerMapper.insert(salesLedger);
+
+
+                for (SalesLedgerProductImportDto salesLedgerProductImportDto : salesLedgerProductImportDtos) {
+                    SalesLedgerProduct salesLedgerProduct = new SalesLedgerProduct();
+                    BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
+                    salesLedgerProduct.setSalesLedgerId(salesLedger.getId());
+                    salesLedgerProduct.setType(1);
+                    // 璁$畻涓嶅惈绋庢�讳环
+                    salesLedgerProduct.setTaxExclusiveTotalPrice(salesLedgerProduct.getTaxInclusiveTotalPrice().divide(new BigDecimal(1).add(salesLedgerProduct.getTaxRate().divide(new BigDecimal(100))), 2, RoundingMode.HALF_UP));
+                    salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
+                    salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxExclusiveTotalPrice());
+                    list.stream()
+                            .filter(map -> map.get("productName").equals(salesLedgerProduct.getProductCategory()) && map.get("model").equals(salesLedgerProduct.getSpecificationModel()))
+                            .findFirst()
+                            .ifPresent(map -> {
+                                salesLedgerProduct.setProductModelId(Long.parseLong(map.get("modelId").toString()));
+                                salesLedgerProduct.setProductId(Long.parseLong(map.get("id").toString()));
+                            });
+//                    salesLedgerProduct.setProductId(productList.stream()
+//                            .filter(product -> product.getProductName().equals(salesLedgerProduct.getProductCategory()))
+//                            .findFirst()
+//                            .map(Product::getId)
+//                            .orElse(null));
+//                    salesLedgerProduct.setProductModelId(productModels.stream()
+//                            .filter(productModel -> productModel.getModel().equals(salesLedgerProduct.getSpecificationModel()))
+//                            .findFirst()
+//                            .map(ProductModel::getId)
+//                            .orElse(null));
+                    salesLedgerProduct.setRegister(loginUser.getNickName());
+                    salesLedgerProduct.setRegisterDate(LocalDateTime.now());
+                    salesLedgerProduct.setApproveStatus(0);
+                    salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProductImportDto.getTaxInclusiveTotalPrice());
+                    salesLedgerProductMapper.insert(salesLedgerProduct);
+                    // 娣诲姞鐢熶骇鏁版嵁
+                    salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
+                }
+            }
+
+            return AjaxResult.success("瀵煎叆鎴愬姛");
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return AjaxResult.success("瀵煎叆澶辫触");
+    }
+
+    @Override
+    public List<LossProductModelDto> getSalesLedgerWithProductsLoss(Long salesLedgerId) {
+
+
+        List<LossProductModelDto> lossProductModelDtos = salesLedgerProductMapper.selectProductBomStructure(salesLedgerId);
+
+
+        return lossProductModelDtos;
+    }
+
+
+    // 鍐呴儴绫荤敤浜庡瓨鍌ㄨ仛鍚堢粨鏋�
+    private static class GroupedCustomer {
+        private final Long customerId;
+        private final String customerName;
+        private BigDecimal totalAmount = BigDecimal.ZERO;
+
+        public GroupedCustomer(Long customerId, String customerName) {
+            this.customerId = customerId;
+            this.customerName = customerName;
+        }
+
+        public void addAmount(BigDecimal amount) {
+            if (amount != null) {
+                this.totalAmount = this.totalAmount.add(amount);
+            }
+        }
+
+        public Long getCustomerId() {
+            return customerId;
+        }
+
+        public String getCustomerName() {
+            return customerName;
+        }
+
+        public BigDecimal getTotalAmount() {
+            return totalAmount;
+        }
+    }
+
+    /**
+     * 涓嬪垝绾垮懡鍚嶈浆椹煎嘲鍛藉悕
+     */
+    private String underlineToCamel(String param) {
+        if (param == null || "".equals(param.trim())) {
+            return "";
+        }
+        int len = param.length();
+        StringBuilder sb = new StringBuilder(len);
+        for (int i = 0; i < len; i++) {
+            char c = param.charAt(i);
+            if (c == '_') {
+                if (++i < len) {
+                    sb.append(Character.toUpperCase(param.charAt(i)));
+                }
+            } else {
+                sb.append(Character.toLowerCase(c));
+            }
+        }
+        return sb.toString();
     }
 
     @Override
@@ -89,60 +830,195 @@
         List<Long> idList = Arrays.stream(ids)
                 .filter(Objects::nonNull)
                 .collect(Collectors.toList());
-
         if (CollectionUtils.isEmpty(idList)) {
             return 0;
         }
-        // 1. 鍏堝垹闄ゅ瓙琛ㄦ暟鎹�
-        LambdaQueryWrapper<SalesLedgerProduct> productWrapper = new LambdaQueryWrapper<>();
-        productWrapper.in(SalesLedgerProduct::getSalesLedgerId, idList);
-        salesLedgerProductMapper.delete(productWrapper);
+        // 鍒犻櫎閿�鍞鐞嗘暟鎹�
+        LambdaQueryWrapper<SalesLedgerProduct> queryWrapper = new LambdaQueryWrapper<>();
+        queryWrapper.in(SalesLedgerProduct::getSalesLedgerId, idList)
+                .select(SalesLedgerProduct::getId);
 
+        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(queryWrapper);
+        List<Long> productIds = products.stream()
+                .map(SalesLedgerProduct::getId)
+                .collect(Collectors.toList());
+        //鍒犻櫎鐢熶骇鏁版嵁
+        salesLedgerProductServiceImpl.deleteProductionData(productIds);
+
+        // 鎵归噺鍒犻櫎浜у搧瀛愯〃
+        if (!productIds.isEmpty()) {
+            salesLedgerProductMapper.deleteBatchIds(productIds);
+        }
+
+        LambdaQueryWrapper<InvoiceRegistrationProduct> wrapper = new LambdaQueryWrapper<>();
+        wrapper.in(InvoiceRegistrationProduct::getSalesLedgerId, idList);
+        List<InvoiceRegistrationProduct> invoiceRegistrationProducts = invoiceRegistrationProductMapper.selectList(wrapper);
+        List<Integer> invoiceLedgerIds = new ArrayList<>();
+        if (CollectionUtils.isNotEmpty(invoiceRegistrationProducts)) {
+            LambdaQueryWrapper<InvoiceLedger> wrapperOne = new LambdaQueryWrapper<>();
+            wrapperOne.in(InvoiceLedger::getInvoiceRegistrationProductId, invoiceRegistrationProducts.stream().map(InvoiceRegistrationProduct::getId).collect(Collectors.toList()));
+            List<InvoiceLedger> invoiceLedgers = invoiceLedgerMapper.selectList(wrapperOne);
+            if (CollectionUtils.isNotEmpty(invoiceLedgers)) {
+                invoiceLedgerIds = invoiceLedgers.stream().map(InvoiceLedger::getId).collect(Collectors.toList());
+            }
+            invoiceLedgerMapper.delete(wrapperOne);
+        }
+        invoiceRegistrationProductMapper.delete(wrapper);
+        LambdaQueryWrapper<InvoiceRegistration> wrapperTwo = new LambdaQueryWrapper<>();
+        wrapperTwo.in(InvoiceRegistration::getSalesLedgerId, idList);
+        invoiceRegistrationMapper.delete(wrapperTwo);
+
+        if (CollectionUtils.isNotEmpty(invoiceLedgerIds)) {
+            LambdaQueryWrapper<ReceiptPayment> wrapperTree = new LambdaQueryWrapper<>();
+            wrapperTree.in(ReceiptPayment::getInvoiceLedgerId, invoiceLedgerIds);
+            receiptPaymentMapper.delete(wrapperTree);
+        }
+        // 鍒犻櫎鍙戣揣鍙拌处璁板綍
+        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
+                .in(ShippingInfo::getSalesLedgerId, idList));
+        if (CollectionUtils.isNotEmpty(shippingInfos)) {
+            shippingInfoServiceImpl.delete(shippingInfos.stream().map(ShippingInfo::getId).collect(Collectors.toList()));
+        }
+        // 鍒犻櫎闄勪欢琛�
+        commonFileService.deleteByBusinessIds(idList, FileNameType.SALE.getValue());
+
+        // 鍒犻櫎鐢熶骇绠℃帶鏁版嵁
+        //鏌ヨ鐢熶骇鎶ュ伐id
+        ArrayList<Long> mainIdList = productionProductMainService.listMain(idList);
+        if (CollectionUtils.isNotEmpty(mainIdList)) {
+            mainIdList.stream().forEach(mainId -> {
+                productionProductMainService.removeProductMain(mainId);
+            });
+        }
         // 2. 鍐嶅垹闄や富琛ㄦ暟鎹�
         return salesLedgerMapper.deleteBatchIds(idList);
     }
 
+    @Override
     @Transactional(rollbackFor = Exception.class)
     public int addOrUpdateSalesLedger(SalesLedgerDto salesLedgerDto) {
-        // 1. 鏍¢獙瀹㈡埛淇℃伅
-        Customer customer = customerMapper.selectById(salesLedgerDto.getCustomerId());
-        if (customer == null) {
-            throw new BaseException("瀹㈡埛涓嶅瓨鍦�");
+        try {
+            // 1. 鏍¢獙瀹㈡埛淇℃伅
+            Customer customer = customerMapper.selectById(salesLedgerDto.getCustomerId());
+            if (customer == null) {
+                throw new BaseException("瀹㈡埛涓嶅瓨鍦�");
+            }
+
+            // 2. DTO杞珽ntity
+            SalesLedger salesLedger = convertToEntity(salesLedgerDto);
+            salesLedger.setCustomerName(customer.getCustomerName());
+            salesLedger.setTenantId(customer.getTenantId());
+            // 3. 鏂板鎴栨洿鏂颁富琛�
+            if (salesLedger.getId() == null) {
+                String contractNo = generateSalesContractNo();
+                salesLedger.setSalesContractNo(contractNo);
+                salesLedgerMapper.insert(salesLedger);
+            } else {
+                salesLedgerMapper.updateById(salesLedger);
+            }
+
+            // 4. 澶勭悊瀛愯〃鏁版嵁
+            List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
+            if (productList != null && !productList.isEmpty()) {
+                handleSalesLedgerProducts(salesLedger.getId(), productList, salesLedgerDto.getType(), salesLedgerDto.isProduce());
+                updateMainContractAmount(
+                        salesLedger.getId(),
+                        productList,
+                        SalesLedgerProduct::getTaxInclusiveTotalPrice,
+                        salesLedgerMapper,
+                        SalesLedger.class
+                );
+            }
+
+            // 5. 杩佺Щ涓存椂鏂囦欢鍒版寮忕洰褰�
+            if (salesLedgerDto.getTempFileIds() != null && !salesLedgerDto.getTempFileIds().isEmpty()) {
+                migrateTempFilesToFormal(salesLedger.getId(), salesLedgerDto.getTempFileIds());
+            }
+            return 1;
+        } catch (IOException e) {
+            throw new BaseException("鏂囦欢杩佺Щ澶辫触: " + e.getMessage());
         }
-
-        // 2. DTO杞珽ntity
-        SalesLedger salesLedger = convertToEntity(salesLedgerDto);
-        salesLedger.setCustomerName(customer.getCustomerName());
-        salesLedger.setTenantId(customer.getTenantId());
-
-        // 3. 鏂板鎴栨洿鏂颁富琛�
-        if (salesLedger.getId() == null) {
-            // 鐢熸垚鍚堝悓缂栧彿
-            String contractNo = generateSalesContractNo();
-            salesLedger.setSalesContractNo(contractNo);
-            salesLedgerMapper.insert(salesLedger);
-        } else {
-            salesLedgerMapper.updateById(salesLedger);
-        }
-
-        // 4. 澶勭悊瀛愯〃鏁版嵁
-        List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
-        if (productList != null && !productList.isEmpty()) {
-            handleSalesLedgerProducts(salesLedger.getId(), productList);
-
-            // 鉁� 璋冪敤閫氱敤鏂规硶鏇存柊涓昏〃閲戦
-            updateMainContractAmount(
-                    salesLedger.getId(),
-                    productList,
-                    SalesLedgerProduct::getTaxInclusiveTotalPrice,
-                    salesLedgerMapper,
-                    SalesLedger.class
-            );
-        }
-        return 1; // 鎿嶄綔鎴愬姛杩斿洖1
     }
 
-    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products) {
+    // 鏂囦欢杩佺Щ鏂规硶
+
+    /**
+     * 灏嗕复鏃舵枃浠惰縼绉诲埌姝e紡鐩綍
+     *
+     * @param businessId  涓氬姟ID锛堥攢鍞彴璐D锛�
+     * @param tempFileIds 涓存椂鏂囦欢ID鍒楄〃
+     * @throws IOException 鏂囦欢鎿嶄綔寮傚父
+     */
+    private void migrateTempFilesToFormal(Long businessId, List<String> tempFileIds) throws IOException {
+        if (CollectionUtils.isEmpty(tempFileIds)) {
+            return;
+        }
+
+        // 鏋勫缓姝e紡鐩綍璺緞锛堟寜涓氬姟绫诲瀷鍜屾棩鏈熷垎缁勶級
+        String formalDir = uploadDir + LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
+
+        Path formalDirPath = Paths.get(formalDir);
+
+        // 纭繚姝e紡鐩綍瀛樺湪锛堥�掑綊鍒涘缓锛�
+        if (!Files.exists(formalDirPath)) {
+            Files.createDirectories(formalDirPath);
+        }
+
+        for (String tempFileId : tempFileIds) {
+            // 鏌ヨ涓存椂鏂囦欢璁板綍
+            TempFile tempFile = tempFileMapper.selectById(tempFileId);
+            if (tempFile == null) {
+                log.warn("涓存椂鏂囦欢涓嶅瓨鍦紝璺宠繃澶勭悊: {}", tempFileId);
+                continue;
+            }
+
+            // 鏋勫缓姝e紡鏂囦欢鍚嶏紙鍖呭惈涓氬姟ID鍜屾椂闂存埑锛岄伩鍏嶅啿绐侊級
+            String originalFilename = tempFile.getOriginalName();
+            String fileExtension = FilenameUtils.getExtension(originalFilename);
+            String formalFilename = businessId + "_" +
+                    System.currentTimeMillis() + "_" +
+                    UUID.randomUUID().toString().substring(0, 8) +
+                    (StringUtils.hasText(fileExtension) ? "." + fileExtension : "");
+
+            Path formalFilePath = formalDirPath.resolve(formalFilename);
+
+            try {
+                // 鎵ц鏂囦欢杩佺Щ锛堜娇鐢ㄥ師瀛愭搷浣滅‘淇濆畨鍏ㄦ�э級
+//                Files.move(
+//                        Paths.get(tempFile.getTempPath()),
+//                        formalFilePath,
+//                        StandardCopyOption.REPLACE_EXISTING,
+//                        StandardCopyOption.ATOMIC_MOVE
+//                );
+                // 鍘熷瓙绉诲姩澶辫触锛屼娇鐢ㄥ鍒�+鍒犻櫎
+                Files.copy(Paths.get(tempFile.getTempPath()), formalFilePath, StandardCopyOption.REPLACE_EXISTING);
+                Files.deleteIfExists(Paths.get(tempFile.getTempPath()));
+                log.info("鏂囦欢杩佺Щ鎴愬姛: {} -> {}", tempFile.getTempPath(), formalFilePath);
+
+                // 鏇存柊鏂囦欢璁板綍锛堝叧鑱斿埌涓氬姟ID锛�
+                CommonFile fileRecord = new CommonFile();
+                fileRecord.setCommonId(businessId);
+                fileRecord.setName(originalFilename);
+                fileRecord.setUrl(formalFilePath.toString());
+                fileRecord.setCreateTime(LocalDateTime.now());
+                //閿�鍞�
+                fileRecord.setType(FileNameType.SALE.getValue());
+                commonFileMapper.insert(fileRecord);
+
+                // 鍒犻櫎涓存椂鏂囦欢璁板綍
+                tempFileMapper.deleteById(tempFile);
+
+                log.info("鏂囦欢杩佺Щ鎴愬姛: {} -> {}", tempFile.getTempPath(), formalFilePath);
+            } catch (IOException e) {
+                log.error("鏂囦欢杩佺Щ澶辫触: {}", tempFile.getTempPath(), e);
+                // 鍙�夋嫨鍥炴粴浜嬪姟鎴栬褰曞け璐ユ枃浠�
+                throw new IOException("鏂囦欢杩佺Щ寮傚父", e);
+            }
+        }
+    }
+
+
+    private void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products, Integer type, boolean isProduce) {
         // 鎸塈D鍒嗙粍锛屽尯鍒嗘柊澧炲拰鏇存柊鐨勮褰�
         Map<Boolean, List<SalesLedgerProduct>> partitionedProducts = products.stream()
                 .peek(p -> p.setSalesLedgerId(salesLedgerId))
@@ -151,16 +1027,49 @@
         List<SalesLedgerProduct> updateList = partitionedProducts.get(true);
         List<SalesLedgerProduct> insertList = partitionedProducts.get(false);
 
+//        List<StockInventoryDto> stockInventoryDtos = stockInventoryMapper.selectProductList();
+
         // 鎵ц鏇存柊鎿嶄綔
         if (!updateList.isEmpty()) {
             for (SalesLedgerProduct product : updateList) {
+//                // 鏌ヨ搴撳瓨鏁伴噺
+//                SalesLedgerProduct oldProduct = salesLedgerProductMapper.selectById(product.getId());
+//                BigDecimal quantityChange = product.getQuantity().subtract(oldProduct.getQuantity());
+//
+//                // 濡傛灉鏁伴噺澧炲姞浜嗭紝妫�鏌ュ簱瀛�
+//                if (quantityChange.compareTo(BigDecimal.ZERO) > 0) {
+//                    for (StockInventoryDto stockInventoryDto : stockInventoryDtos) {
+//                        if (stockInventoryDto.getProductId().equals(product.getId())) {
+//                            if (quantityChange.compareTo(stockInventoryDto.getQualitity()) > 0) {
+//                                throw new RuntimeException("搴撳瓨涓嶈冻");
+//                            }
+//                            break;
+//                        }
+//                    }
+//                }
+                product.setType(type);
                 salesLedgerProductMapper.updateById(product);
             }
         }
         // 鎵ц鎻掑叆鎿嶄綔
         if (!insertList.isEmpty()) {
             for (SalesLedgerProduct salesLedgerProduct : insertList) {
+//                for (StockInventoryDto stockInventoryDto : stockInventoryDtos) {
+//                    if (stockInventoryDto.getProductId().equals(salesLedgerProduct.getId())) {
+//                        if (salesLedgerProduct.getQuantity().compareTo(stockInventoryDto.getQualitity()) > 0) {
+//                            throw new RuntimeException("搴撳瓨涓嶈冻");
+//                        }
+//                    }
+//                }
+                salesLedgerProduct.setType(type);
+                salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
+                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
+                salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
                 salesLedgerProductMapper.insert(salesLedgerProduct);
+                // 娣诲姞鐢熶骇鏁版嵁
+                if (isProduce) {
+                    salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
+                }
             }
         }
     }
@@ -200,18 +1109,26 @@
                 throw new RuntimeException("鑾峰彇鍚堝悓缂栧彿鐢熸垚閿佸け璐ワ細瓒呮椂");
             }
 
-            // 2. 鏌ヨ褰撳ぉ宸插瓨鍦ㄧ殑搴忓垪鍙凤紙涓庡師閫昏緫涓�鑷达級
+            // 2. 鏌ヨ褰撳ぉ/鍏徃宸插瓨鍦ㄧ殑搴忓垪鍙凤紙涓庡師閫昏緫涓�鑷达級
+            Long tenantId = SecurityUtils.getLoginUser().getTenantId();
+            if (null != tenantId) {
+                //鑾峰彇鍏徃缂栧彿
+                SysDept sysDept = sysDeptMapper.selectDeptById(tenantId.longValue());
+                if (!ObjectUtils.isEmpty(sysDept)) {
+                    datePart = (StringUtils.isEmpty(sysDept.getDeptNick()) ? "" : sysDept.getDeptNick()) + datePart;
+                }
+            }
             List<Integer> existingSequences = salesLedgerMapper.selectSequencesByDate(datePart);
             int nextSequence = findFirstMissingSequence(existingSequences);
 
-            return datePart + String.format("%02d", nextSequence);
+            return datePart + String.format("%03d", nextSequence);
         } finally {
-            // 3. 閲婃斁閿侊紙浣跨敤Lua鑴氭湰淇濊瘉鍘熷瓙鎬э紝閬垮厤璇垹鍏朵粬绾跨▼鐨勯攣锛�
+            // 3. 閲婃斁閿�
             String luaScript = "if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end";
             redisTemplate.execute(
                     new DefaultRedisScript<>(luaScript, Long.class),
                     Collections.singletonList(lockKey),
-                    lockValue // 鍙湁鎸佹湁鐩稿悓鍊肩殑绾跨▼鎵嶈兘鍒犻櫎閿�
+                    lockValue
             );
         }
     }
@@ -220,7 +1137,7 @@
         if (sequences.isEmpty()) {
             return 1;
         }
-        // 鎺掑簭鍚庢煡鎵剧涓�涓己澶辩殑姝f暣鏁帮紙涓庡師閫昏緫涓�鑷达級
+        // 鎺掑簭鍚庢煡鎵剧涓�涓己澶辩殑姝f暣鏁�
         sequences.sort(Integer::compareTo);
         int next = 1;
         for (int seq : sequences) {
@@ -250,14 +1167,13 @@
                 .filter(Objects::nonNull)
                 .reduce(BigDecimal.ZERO, BigDecimal::add);
 
-        // 鏋勯�犱富琛ㄦ洿鏂板璞★紙鏀寔浠绘剰涓昏〃绫诲瀷锛�
+        // 鏋勯�犱富琛ㄦ洿鏂板璞�
         try {
             S entity = mainEntityClass.getDeclaredConstructor().newInstance();
             Field idField = mainEntityClass.getDeclaredField("id");
             idField.setAccessible(true);
             idField.set(entity, mainId);
 
-            // 璁剧疆 contractAmount 瀛楁锛屾敞鎰忚繖閲屽亣璁惧瓧娈靛悕涓� "contractAmount"
             Field amountField = mainEntityClass.getDeclaredField("contractAmount");
             amountField.setAccessible(true);
             amountField.set(entity, totalAmount);
@@ -267,4 +1183,4 @@
             throw new RuntimeException("鍔ㄦ�佹洿鏂颁富琛ㄩ噾棰濆け璐�", e);
         }
     }
-}
+}
\ No newline at end of file

--
Gitblit v1.9.3