huminmin
8 天以前 7b8b2456bb15aa733b8599fce2ada5d9549ba881
src/main/java/com/ruoyi/sales/service/impl/SalesLedgerServiceImpl.java
@@ -1,52 +1,71 @@
package com.ruoyi.sales.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ruoyi.account.service.AccountIncomeService;
import com.ruoyi.approve.pojo.ApproveProcess;
import com.ruoyi.approve.service.IApproveProcessService;
import com.ruoyi.approve.vo.ApproveProcessVO;
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.CustomerRegions;
import com.ruoyi.basic.pojo.Product;
import com.ruoyi.basic.pojo.ProductModel;
import com.ruoyi.basic.service.ICustomerRegionsService;
import com.ruoyi.common.enums.FileNameType;
import com.ruoyi.common.enums.SaleEnum;
import com.ruoyi.common.enums.*;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.EnumUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.poi.ExcelUtil;
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.procurementrecord.utils.StockUtils;
import com.ruoyi.production.mapper.*;
import com.ruoyi.production.pojo.ProcessRoute;
import com.ruoyi.production.pojo.ProcessRouteItem;
import com.ruoyi.production.service.ProductionProductMainService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.purchase.dto.SimpleReturnOrderGroupDto;
import com.ruoyi.purchase.mapper.PurchaseReturnOrderProductsMapper;
import com.ruoyi.quality.mapper.QualityInspectMapper;
import com.ruoyi.quality.mapper.QualityInspectParamMapper;
import com.ruoyi.quality.mapper.QualityTestStandardMapper;
import com.ruoyi.quality.mapper.QualityTestStandardParamMapper;
import com.ruoyi.quality.pojo.QualityInspect;
import com.ruoyi.quality.pojo.QualityInspectParam;
import com.ruoyi.quality.pojo.QualityTestStandard;
import com.ruoyi.quality.pojo.QualityTestStandardParam;
import com.ruoyi.sales.dto.*;
import com.ruoyi.sales.mapper.*;
import com.ruoyi.sales.pojo.*;
import com.ruoyi.sales.service.ISalesLedgerProcessRouteService;
import com.ruoyi.sales.service.ISalesLedgerProcessRouteRecordService;
import com.ruoyi.sales.service.ISalesLedgerProductProcessBindService;
import com.ruoyi.sales.service.ISalesLedgerProductProcessService;
import com.ruoyi.sales.service.ISalesLedgerService;
import com.ruoyi.stock.dto.StockInventoryDto;
import com.ruoyi.stock.mapper.StockInRecordMapper;
import com.ruoyi.stock.mapper.StockInventoryMapper;
import com.ruoyi.stock.mapper.StockOutRecordMapper;
import com.ruoyi.stock.pojo.StockInRecord;
import com.ruoyi.stock.pojo.StockOutRecord;
import com.ruoyi.stock.service.StockInRecordService;
import com.ruoyi.stock.service.StockInventoryService;
import com.ruoyi.stock.service.StockOutRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
@@ -60,11 +79,13 @@
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@@ -72,6 +93,7 @@
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;
@@ -91,6 +113,9 @@
    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 static final int INBOUND_BIZ_TYPE_WEB = 1;
    private static final int INBOUND_BIZ_TYPE_SCAN_QUALIFIED = 2;
    private static final int INBOUND_BIZ_TYPE_SCAN_UNQUALIFIED = 3;
    private final AccountIncomeService accountIncomeService;
    private final SalesLedgerMapper salesLedgerMapper;
    private final CustomerMapper customerMapper;
@@ -118,6 +143,9 @@
    private final ProductionProductOutputMapper productionProductOutputMapper;
    private final ProductionProductInputMapper productionProductInputMapper;
    private final QualityInspectMapper qualityInspectMapper;
    private final QualityInspectParamMapper qualityInspectParamMapper;
    private final QualityTestStandardMapper qualityTestStandardMapper;
    private final QualityTestStandardParamMapper qualityTestStandardParamMapper;
    private final RedisTemplate<String, String> redisTemplate;
    private final ISalesLedgerProductProcessService salesLedgerProductProcessService;
@@ -125,6 +153,19 @@
    private final ISalesLedgerProductProcessBindService salesLedgerProductProcessBindService;
    private final ISalesLedgerProcessRouteService salesLedgerProcessRouteService;
    private final ISalesLedgerProcessRouteRecordService salesLedgerProcessRouteRecordService;
    private final StockInventoryService stockInventoryService;
    private final StockInRecordMapper stockInRecordMapper;
    private final StockOutRecordMapper stockOutRecordMapper;
    private final StockInventoryMapper stockInventoryMapper;
    private final StockInRecordService stockInRecordService;
    private final StockOutRecordService stockOutRecordService;
    private final StockUtils stockUtils;
    private final ShipmentApprovalMapper shipmentApprovalMapper;
    @Autowired
    private IApproveProcessService approveProcessService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
@@ -200,11 +241,7 @@
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(productWrapper);
        Map<Long, ProductModel> productModelMap = Collections.emptyMap();
        if (CollectionUtils.isNotEmpty(products)) {
            List<Long> productModelIds = products.stream()
                    .map(SalesLedgerProduct::getProductModelId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
            List<Long> productModelIds = products.stream().map(SalesLedgerProduct::getProductModelId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(productModelIds)) {
                List<ProductModel> productModels = productModelMapper.selectBatchIds(productModelIds);
                if (CollectionUtils.isNotEmpty(productModels)) {
@@ -220,26 +257,15 @@
            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"));
            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());
            }
            // 加工明细,先查bind表获取该产品关联的工序及数量
            List<SalesLedgerProductProcessBind> bindList = salesLedgerProductProcessBindService.list(
                    new LambdaQueryWrapper<SalesLedgerProductProcessBind>()
                            .eq(SalesLedgerProductProcessBind::getSalesLedgerProductId, product.getId()));
            List<SalesLedgerProductProcessBind> bindList = salesLedgerProductProcessBindService.list(new LambdaQueryWrapper<SalesLedgerProductProcessBind>().eq(SalesLedgerProductProcessBind::getSalesLedgerProductId, product.getId()));
            if (!bindList.isEmpty()) {
                List<Integer> processIds = bindList.stream()
                        .map(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId)
                        .collect(Collectors.toList());
                Map<Integer, Integer> processQuantityMap = bindList.stream()
                        .collect(Collectors.toMap(
                                SalesLedgerProductProcessBind::getSalesLedgerProductProcessId,
                                SalesLedgerProductProcessBind::getQuantity,
                                (a, b) -> a));
                List<Integer> processIds = bindList.stream().map(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId).collect(Collectors.toList());
                Map<Integer, Integer> processQuantityMap = bindList.stream().collect(Collectors.toMap(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId, SalesLedgerProductProcessBind::getQuantity, (a, b) -> a));
                List<SalesLedgerProductProcess> processList = salesLedgerProductProcessService.listByIds(processIds);
                processList.forEach(p -> p.setQuantity(processQuantityMap.get(p.getId())));
                product.setSalesProductProcessList(processList);
@@ -258,12 +284,12 @@
                    product.setActualTotalArea(pieceArea.multiply(quantity).setScale(2, RoundingMode.HALF_UP));
                }
            }
            product.fillRemainingQuantity();
        }
        // 3.查询上传文件
        LambdaQueryWrapper<CommonFile> salesLedgerFileWrapper = new LambdaQueryWrapper<>();
        salesLedgerFileWrapper.eq(CommonFile::getCommonId, salesLedger.getId())
                .eq(CommonFile::getType, FileNameType.SALE.getValue());
        salesLedgerFileWrapper.eq(CommonFile::getCommonId, salesLedger.getId()).eq(CommonFile::getType, FileNameType.SALE.getValue());
        List<CommonFile> salesLedgerFiles = commonFileMapper.selectList(salesLedgerFileWrapper);
        // 4. 转换 DTO
@@ -286,11 +312,7 @@
        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());
        return result.stream().map(map -> map.entrySet().stream().collect(Collectors.toMap(entry -> underlineToCamel(entry.getKey()), Map.Entry::getValue))).collect(Collectors.toList());
    }
    @Override
@@ -306,10 +328,7 @@
        // 执行查询并计算总和
        List<SalesLedger> salesLedgers = salesLedgerMapper.selectList(queryWrapper);
        BigDecimal totalContractAmount = salesLedgers.stream()
                .map(SalesLedger::getContractAmount)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalContractAmount = salesLedgers.stream().map(SalesLedger::getContractAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
        return totalContractAmount;
    }
@@ -318,32 +337,25 @@
    public List getTopFiveList() {
        // 查询原始数据
        LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(SalesLedger::getCustomerId,
                        SalesLedger::getCustomerName,
                        SalesLedger::getContractAmount)
                .orderByDesc(SalesLedger::getContractAmount);
        queryWrapper.select(SalesLedger::getCustomerId, SalesLedger::getCustomerName, SalesLedger::getContractAmount)
                .orderByDesc(SalesLedger::getContractAmount)
                .ne(SalesLedger::getReviewStatus, 2); // 排除反审核数据
        List<SalesLedger> records = salesLedgerMapper.selectList(queryWrapper);
        // 按客户ID分组并聚合金额
        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());
            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());
        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
@@ -359,31 +371,19 @@
            //  回款金额
            LambdaQueryWrapper<ReceiptPayment> receiptPaymentQuery = new LambdaQueryWrapper<>();
            receiptPaymentQuery
                    .ge(ReceiptPayment::getCreateTime, startTime)
                    .le(ReceiptPayment::getCreateTime, endTime);
            receiptPaymentQuery.ge(ReceiptPayment::getCreateTime, startTime).le(ReceiptPayment::getCreateTime, endTime);
            List<ReceiptPayment> receiptPayments =
                    receiptPaymentMapper.selectList(receiptPaymentQuery);
            List<ReceiptPayment> receiptPayments = receiptPaymentMapper.selectList(receiptPaymentQuery);
            BigDecimal receiptAmount = receiptPayments.stream()
                    .map(ReceiptPayment::getReceiptPaymentAmount)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            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);
            invoiceLedgerQuery.ge(InvoiceLedger::getCreateTime, startTime).le(InvoiceLedger::getCreateTime, endTime);
            List<InvoiceLedger> invoiceLedgers =
                    invoiceLedgerMapper.selectList(invoiceLedgerQuery);
            List<InvoiceLedger> invoiceLedgers = invoiceLedgerMapper.selectList(invoiceLedgerQuery);
            BigDecimal invoiceAmount = invoiceLedgers.stream()
                    .map(InvoiceLedger::getInvoiceTotal)
                    .filter(Objects::nonNull)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            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")));
@@ -398,152 +398,324 @@
    @Override
    public IPage<SalesLedger> selectSalesLedgerListPage(Page page, SalesLedgerDto salesLedgerDto) {
        return salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
        // 添加 reviewStatus 的筛选条件
        IPage<SalesLedger> iPage = salesLedgerMapper.selectSalesLedgerListPage(page, salesLedgerDto);
        if (CollectionUtils.isEmpty(iPage.getRecords())) {
            return iPage;
        }
        List<Long> salesLedgerIds = iPage.getRecords().stream().map(SalesLedger::getId).collect(Collectors.toList());
        boolean hasWidthHeightFilter = salesLedgerDto.getWidth() != null || salesLedgerDto.getHeight() != null;
        Map<Long, List<SalesLedgerProduct>> matchedProductsMap = Collections.emptyMap();
        if (hasWidthHeightFilter) {
            LambdaQueryWrapper<SalesLedgerProduct> productQueryWrapper = new LambdaQueryWrapper<SalesLedgerProduct>().in(SalesLedgerProduct::getSalesLedgerId, salesLedgerIds).eq(SalesLedgerProduct::getType, 1);
            if (salesLedgerDto.getWidth() != null) {
                productQueryWrapper.eq(SalesLedgerProduct::getWidth, salesLedgerDto.getWidth());
            }
            if (salesLedgerDto.getHeight() != null) {
                productQueryWrapper.eq(SalesLedgerProduct::getHeight, salesLedgerDto.getHeight());
            }
            List<SalesLedgerProduct> matchedProducts = salesLedgerProductMapper.selectList(productQueryWrapper);
            matchedProductsMap = CollectionUtils.isEmpty(matchedProducts) ? Collections.emptyMap() : matchedProducts.stream().collect(Collectors.groupingBy(SalesLedgerProduct::getSalesLedgerId));
        }
        List<SalesLedgerProductTotalsDto> productTotals = salesLedgerProductMapper.selectSalesLedgerProductTotals(salesLedgerIds, 1);
        Map<Long, SalesLedgerProductTotalsDto> productTotalsMap = CollectionUtils.isEmpty(productTotals) ? Collections.emptyMap() : productTotals.stream().filter(t -> t.getSalesLedgerId() != null).collect(Collectors.toMap(SalesLedgerProductTotalsDto::getSalesLedgerId, Function.identity(), (a, b) -> a));
        List<InvoiceLedgerDto> invoiceLedgerDtoList = invoiceLedgerMapper.invoicedTotal(salesLedgerIds);
        if (CollectionUtils.isEmpty(invoiceLedgerDtoList)) {
            invoiceLedgerDtoList = Collections.emptyList();
        }
        Map<Long, BigDecimal> invoiceTotals = invoiceLedgerDtoList.stream().filter(dto -> dto.getSalesLedgerId() != null && dto.getInvoiceTotal() != null).collect(Collectors.toMap(dto -> dto.getSalesLedgerId().longValue(), InvoiceLedgerDto::getInvoiceTotal, BigDecimal::add));
        List<ReceiptPayment> receiptPayments = Collections.emptyList();
        if (!CollectionUtils.isEmpty(salesLedgerIds)) {
            receiptPayments = receiptPaymentMapper.selectList(new LambdaQueryWrapper<ReceiptPayment>().in(ReceiptPayment::getSalesLedgerId, salesLedgerIds));
        }
        Map<Long, BigDecimal> receiptTotals = new HashMap<>();
        if (!CollectionUtils.isEmpty(receiptPayments)) {
            for (ReceiptPayment receiptPayment : receiptPayments) {
                if (receiptPayment.getSalesLedgerId() != null && receiptPayment.getReceiptPaymentAmount() != null) {
                    receiptTotals.merge(receiptPayment.getSalesLedgerId(), receiptPayment.getReceiptPaymentAmount(), BigDecimal::add);
                }
            }
        }
        for (SalesLedger salesLedger : iPage.getRecords()) {
            Long ledgerId = salesLedger.getId();
            SalesLedgerProductTotalsDto totals = productTotalsMap.get(ledgerId);
            if (totals != null) {
                salesLedger.setProductTotalQuantity(totals.getTotalQuantity() != null ? totals.getTotalQuantity() : BigDecimal.ZERO);
                salesLedger.setProductTotalArea(totals.getTotalArea() != null ? totals.getTotalArea() : BigDecimal.ZERO);
            } else {
                salesLedger.setProductTotalQuantity(BigDecimal.ZERO);
                salesLedger.setProductTotalArea(BigDecimal.ZERO);
            }
            if (hasWidthHeightFilter) {
                salesLedger.setMatchedProducts(matchedProductsMap.getOrDefault(ledgerId, Collections.emptyList()));
            }
            BigDecimal contractAmount = salesLedger.getContractAmount() == null ? BigDecimal.ZERO : salesLedger.getContractAmount();
            BigDecimal invoiceTotal = invoiceTotals.getOrDefault(ledgerId, BigDecimal.ZERO);
            BigDecimal receiptPaymentAmountTotal = receiptTotals.getOrDefault(ledgerId, BigDecimal.ZERO);
            BigDecimal noInvoiceAmountTotal = contractAmount.subtract(invoiceTotal);
            if (noInvoiceAmountTotal.compareTo(BigDecimal.ZERO) < 0) {
                noInvoiceAmountTotal = BigDecimal.ZERO;
            }
            BigDecimal noReceiptPaymentAmountTotal = invoiceTotal.subtract(receiptPaymentAmountTotal);
            if (noReceiptPaymentAmountTotal.compareTo(BigDecimal.ZERO) < 0) {
                noReceiptPaymentAmountTotal = BigDecimal.ZERO;
            }
            salesLedger.setNoInvoiceAmountTotal(noInvoiceAmountTotal);
            salesLedger.setInvoiceTotal(invoiceTotal);
            salesLedger.setReceiptPaymentAmountTotal(receiptPaymentAmountTotal);
            salesLedger.setNoReceiptAmount(noReceiptPaymentAmountTotal);
            boolean isFh = salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5;
            salesLedger.setIsFh(isFh);
            salesLedger.setIsEdit(!isFh);
            // 根据 reviewStatus 控制反审相关字段的显示
            if (salesLedger.getReviewStatus() != null && salesLedger.getReviewStatus() != 2) {
                // 当 reviewStatus 不为 2 时,隐藏反审时间、反审人和反审人ID
                salesLedger.setCounterReviewTime(null);
                salesLedger.setCounterReviewPerson(null);
                salesLedger.setCounterReviewPersonId(null);
            }
        }
        if (salesLedgerDto.getStatus() != null && salesLedgerDto.getStatus()) {
            iPage.getRecords().removeIf(salesLedger -> Objects.equals(salesLedger.getNoInvoiceAmountTotal(), new BigDecimal("0.00")));
            iPage.setTotal(iPage.getRecords().size());
        }
        return iPage;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult importData(MultipartFile file) {
    public void 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<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) {
                    throw new ServiceException("导入失败:合同号 [" + salesLedgerImportDto.getSalesContractNo() + "] 已存在,请检查后重新导入");
        Map<String, List<SalesLedgerImportDto>> stringListMap;
        try (InputStream inputStream = file.getInputStream()) {
            ExcelUtil<SalesLedgerImportDto> excelUtil = new ExcelUtil<>(SalesLedgerImportDto.class);
            stringListMap = excelUtil.importExcelMultiSheet(Arrays.asList("销售台账数据", "销售产品数据"), inputStream, 0);
        } catch (IOException e) {
            log.error("销售台账导入失败:读取/解析Excel异常", e);
            throw new ServiceException("导入失败:读取/解析Excel异常");
        } catch (Exception e) {
            log.error("销售台账导入失败:解析Excel异常", e);
            throw new ServiceException("导入失败:解析Excel异常");
        }
        if (CollectionUtils.isEmpty(stringListMap)) {
            throw new ServiceException("导入失败,销售表格为空");
        }
        // 业务层合并
        List<SalesLedgerImportDto> salesLedgerImportDtoList = stringListMap.get("销售台账数据");
        if (CollectionUtils.isEmpty(salesLedgerImportDtoList)) {
            throw new ServiceException("导入失败,销售台账数据为空");
        }
        List<SalesLedgerImportDto> salesLedgerProductImportDtoList = stringListMap.get("销售产品数据");
        if (CollectionUtils.isEmpty(salesLedgerProductImportDtoList)) {
            throw new ServiceException("导入失败,销售产品数据为空");
        }
        // 客户数据
        List<Customer> customers = customerMapper.selectList(new LambdaQueryWrapper<Customer>().in(Customer::getCustomerName, salesLedgerImportDtoList.stream().map(SalesLedgerImportDto::getCustomerName).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) {
                throw new ServiceException("导入失败:合同号 [" + salesLedgerImportDto.getSalesContractNo() + "] 已存在,请检查后重新导入");
            }
            SalesLedger salesLedger = new SalesLedger();
            BeanUtils.copyProperties(salesLedgerImportDto, salesLedger);
            // 校验:签订日期、录入日期不能为空
            if (salesLedgerImportDto.getExecutionDate() == null) {
                throw new ServiceException("导入失败:合同号[" + salesLedgerImportDto.getSalesContractNo() + "] 签订日期不能为空");
            }
            if (salesLedgerImportDto.getEntryDate() == null) {
                throw new ServiceException("导入失败:合同号[" + salesLedgerImportDto.getSalesContractNo() + "] 录入日期不能为空");
            }
            salesLedger.setExecutionDate(DateUtils.toLocalDate(salesLedgerImportDto.getExecutionDate()));
            LocalDate expectedDeliveryDate = DateUtils.toLocalDate(salesLedgerImportDto.getEntryDate()).plusDays(7);
            LocalDate importDeliveryDate = salesLedgerImportDto.getDeliveryDate() == null ? null : DateUtils.toLocalDate(salesLedgerImportDto.getDeliveryDate());
            // 交付日期为空则默认取录入日期后7天
            salesLedger.setDeliveryDate(importDeliveryDate == null ? expectedDeliveryDate : importDeliveryDate);
            // 通过客户名称查询客户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 ServiceException("录入人:" + 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 ServiceException("销售单号:" + salesLedgerImportDto.getSalesContractNo() + ",无对应产品数据!");
            }
            //  发货状态
            salesLedger.setDeliveryStatus(1);
            salesLedger.setContractAmount(BigDecimal.ZERO);
            salesLedgerMapper.insert(salesLedger);
            BigDecimal contractAmount = BigDecimal.ZERO;
            for (SalesLedgerProductImportDto salesLedgerProductImportDto : salesLedgerProductImportDtos) {
                SalesLedgerProduct salesLedgerProduct = new SalesLedgerProduct();
                BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
                salesLedgerProduct.setFloorCode(salesLedgerProductImportDto.getFloorNo());
                salesLedgerProduct.setProcessRequirement(salesLedgerProductImportDto.getProcessingRequirements());
                salesLedgerProduct.setRemark(salesLedgerProductImportDto.getRemarks());
                salesLedgerProduct.setSalesLedgerId(salesLedger.getId());
                salesLedgerProduct.setType(1);
                BigDecimal quantity = defaultDecimal(salesLedgerProduct.getQuantity());
                BigDecimal width = defaultDecimal(salesLedgerProduct.getWidth());
                BigDecimal height = defaultDecimal(salesLedgerProduct.getHeight());
                BigDecimal taxRateRaw = salesLedgerProduct.getTaxRate();
                BigDecimal taxRate = defaultDecimal(taxRateRaw);
                BigDecimal unitPrice = defaultDecimal(salesLedgerProduct.getTaxInclusiveUnitPrice());
                // 导入限制:宽/高/数量/金额(单价)/税率 不能为0或负数
                String locate = buildImportLocate(salesLedger.getSalesContractNo(), salesLedgerProductImportDto);
                assertPositive(quantity, "数量", locate);
                assertPositive(width, "宽(mm)", locate);
                assertPositive(height, "高(mm)", locate);
                assertPositive(unitPrice, "含税单价", locate);
                assertNonNegative(taxRateRaw, "税率", locate);
                BigDecimal actualPieceArea = BigDecimal.ZERO;
                if (width.compareTo(BigDecimal.ZERO) > 0 && height.compareTo(BigDecimal.ZERO) > 0) {
                    actualPieceArea = width.multiply(height).divide(new BigDecimal("1000000"), 4, RoundingMode.HALF_UP);
                }
                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 ServiceException("录入人:" + 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));
                //  发货状态
                salesLedger.setDeliveryStatus(4);
                salesLedgerMapper.insert(salesLedger);
                salesLedgerProduct.setActualPieceArea(actualPieceArea);
                salesLedgerProduct.setActualTotalArea(actualPieceArea.multiply(quantity).setScale(4, RoundingMode.HALF_UP));
                for (SalesLedgerProductImportDto salesLedgerProductImportDto : salesLedgerProductImportDtos) {
                    SalesLedgerProduct salesLedgerProduct = new SalesLedgerProduct();
                    BeanUtils.copyProperties(salesLedgerProductImportDto, salesLedgerProduct);
                    salesLedgerProduct.setFloorCode(salesLedgerProductImportDto.getFloorNo());
                    salesLedgerProduct.setProcessRequirement(salesLedgerProductImportDto.getProcessingRequirements());
                    salesLedgerProduct.setRemark(salesLedgerProductImportDto.getRemarks());
                    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.setRegister(loginUser.getNickName());
                    salesLedgerProduct.setRegisterDate(LocalDateTime.now());
                    salesLedgerProduct.setApproveStatus(0);
                    salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProductImportDto.getTaxInclusiveTotalPrice());
                    salesLedgerProductMapper.insert(salesLedgerProduct);
                BigDecimal settlePieceArea = salesLedgerProduct.getSettlePieceArea() == null ? actualPieceArea : salesLedgerProduct.getSettlePieceArea();
                salesLedgerProduct.setSettlePieceArea(settlePieceArea);
                salesLedgerProduct.setSettleTotalArea(settlePieceArea.multiply(quantity).setScale(4, RoundingMode.HALF_UP));
                    // 处理额外加工信息
                    String extraProcessing = salesLedgerProductImportDto.getExtraProcessing();
                    if (StringUtils.hasText(extraProcessing)) {
                        List<SalesLedgerProductProcess> processList = new ArrayList<>();
                        //  中英文分号
                        String[] items = extraProcessing.split("[;;]");
                        for (String item : items) {
                            if (StringUtils.hasText(item)) {
                                String[] parts = item.split("[-—~~]");
                                if (parts.length >= 2) {
                                    String processName = parts[0].trim();
                                    String qtyStr = parts[1].trim();
                                    try {
                                        BigDecimal quantity = new BigDecimal(qtyStr);
                                        SalesLedgerProductProcess process = salesLedgerProductProcessService.getOne(
                                                new LambdaQueryWrapper<SalesLedgerProductProcess>()
                                                        .eq(SalesLedgerProductProcess::getProcessName, processName)
                                                        .last("LIMIT 1")
                                        );
                                        if (process != null) {
                                            SalesLedgerProductProcess p = new SalesLedgerProductProcess();
                                            p.setId(process.getId());
                                            p.setQuantity(quantity.intValue());
                                            processList.add(p);
                                        }
                                    } catch (Exception e) {
                                        log.error("解析额外加工数量失败: {}", qtyStr);
                BigDecimal perimeter = BigDecimal.ZERO;
                if (width.compareTo(BigDecimal.ZERO) > 0 && height.compareTo(BigDecimal.ZERO) > 0) {
                    perimeter = width.add(height).multiply(new BigDecimal("2")).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
                salesLedgerProduct.setPerimeter(perimeter);
                BigDecimal extraProcessAmountPerPiece = BigDecimal.ZERO;
                list.stream().filter(Objects::nonNull).filter(map -> Objects.equals(Objects.toString(map.get("productName"), null), salesLedgerProduct.getProductCategory()) && Objects.equals(Objects.toString(map.get("model"), null), salesLedgerProduct.getSpecificationModel())).findFirst().ifPresent(map -> {
                    salesLedgerProduct.setProductModelId(Long.parseLong(map.get("modelId").toString()));
                    salesLedgerProduct.setProductId(Long.parseLong(map.get("id").toString()));
                });
                salesLedgerProduct.setRegister(loginUser.getNickName());
                salesLedgerProduct.setRegisterDate(LocalDateTime.now());
                salesLedgerProduct.setApproveStatus(0);
                salesLedgerProduct.setProductStockStatus(0);
                // 处理额外加工信息
                String extraProcessing = salesLedgerProductImportDto.getExtraProcessing();
                List<SalesLedgerProductProcess> processList = new ArrayList<>();
                if (StringUtils.hasText(extraProcessing)) {
                    //  中英文分号
                    String[] items = extraProcessing.split("[;;]");
                    for (String item : items) {
                        if (StringUtils.hasText(item)) {
                            String[] parts = item.split("[-—~~]");
                            if (parts.length >= 2) {
                                String processName = parts[0].trim();
                                String qtyStr = parts[1].trim();
                                try {
                                    BigDecimal processQty = new BigDecimal(qtyStr);
                                    SalesLedgerProductProcess process = salesLedgerProductProcessService.getOne(new LambdaQueryWrapper<SalesLedgerProductProcess>().eq(SalesLedgerProductProcess::getProcessName, processName).last("LIMIT 1"));
                                    if (process != null) {
                                        SalesLedgerProductProcess p = new SalesLedgerProductProcess();
                                        p.setId(process.getId());
                                        p.setQuantity(processQty.intValue());
                                        processList.add(p);
                                        extraProcessAmountPerPiece = extraProcessAmountPerPiece.add(defaultDecimal(process.getUnitPrice()).multiply(processQty));
                                    }
                                } catch (Exception e) {
                                    log.error("解析额外加工数量失败: {}", qtyStr);
                                }
                            }
                        }
                        if (!processList.isEmpty()) {
                            salesLedgerProductProcessBindService.updateProductProcessBind(processList, salesLedgerProduct.getId());
                        }
                    }
                    // 添加生产数据
                    salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
                }
            }
            return AjaxResult.success("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
                // 含税总价 = 单价 * 结算面积 * 数量 + 额外加工金额 * 数量
                BigDecimal taxInclusiveTotalPrice = unitPrice.multiply(settlePieceArea).multiply(quantity).add(extraProcessAmountPerPiece.multiply(quantity)).setScale(2, RoundingMode.HALF_UP);
                salesLedgerProduct.setTaxInclusiveTotalPrice(taxInclusiveTotalPrice);
                assertPositive(taxInclusiveTotalPrice, "含税总价", locate);
                // 税率允许为空,空值按0处理
                BigDecimal taxDivisor = BigDecimal.ONE.add(taxRate.divide(new BigDecimal("100"), 6, RoundingMode.HALF_UP));
                salesLedgerProduct.setTaxExclusiveTotalPrice(taxInclusiveTotalPrice.divide(taxDivisor, 2, RoundingMode.HALF_UP));
                salesLedgerProduct.setNoInvoiceNum(quantity);
                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxExclusiveTotalPrice());
                salesLedgerProduct.setPendingInvoiceTotal(taxInclusiveTotalPrice);
                salesLedgerProduct.fillRemainingQuantity();
                salesLedgerProductMapper.insert(salesLedgerProduct);
                if (!processList.isEmpty()) {
                    salesLedgerProductProcessBindService.updateProductProcessBind(processList, salesLedgerProduct.getId());
                }
                // 添加生产数据
                salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
                contractAmount = contractAmount.add(taxInclusiveTotalPrice);
            }
            salesLedger.setContractAmount(contractAmount);
            salesLedgerMapper.updateById(salesLedger);
        }
        return AjaxResult.success("导入失败");
    }
    private BigDecimal defaultDecimal(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }
    private void assertPositive(BigDecimal value, String fieldName, String locate) {
        if (value == null || value.compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("导入失败:" + locate + "【" + fieldName + "】必须大于0");
        }
    }
    private void assertNonNegative(BigDecimal value, String fieldName, String locate) {
        if (value != null && value.compareTo(BigDecimal.ZERO) < 0) {
            throw new ServiceException("导入失败:" + locate + "【" + fieldName + "】不能为负数");
        }
    }
    private String buildImportLocate(String salesContractNo, SalesLedgerProductImportDto dto) {
        StringBuilder sb = new StringBuilder();
        sb.append("销售单号[").append(salesContractNo == null ? "" : salesContractNo).append("]");
        if (dto != null) {
            if (StringUtils.hasText(dto.getProductCategory())) {
                sb.append(" 产品大类[").append(dto.getProductCategory()).append("]");
            }
            if (StringUtils.hasText(dto.getSpecificationModel())) {
                sb.append(" 规格型号[").append(dto.getSpecificationModel()).append("]");
            }
            if (StringUtils.hasText(dto.getFloorNo())) {
                sb.append(" 楼层编号[").append(dto.getFloorNo()).append("]");
            }
        }
        return sb.toString();
    }
    @Override
    public List<LossProductModelDto> getSalesLedgerWithProductsLoss(Long salesLedgerId) {
        List<LossProductModelDto> lossProductModelDtos = salesLedgerProductMapper.selectProductBomStructure(salesLedgerId);
        return lossProductModelDtos;
    }
@@ -563,13 +735,10 @@
                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"));
                product.setShippingCarNumber(shippingInfo.getShippingCarNumber());
                product.setShippingDate(shippingInfo.getShippingDate());
                ShippingInfo shippingInfo = shippingInfoMapper.selectOne(new LambdaQueryWrapper<ShippingInfo>().eq(ShippingInfo::getSalesLedgerProductId, product.getId()).orderByDesc(ShippingInfo::getCreateTime).last("limit 1"));
                if (shippingInfo != null) {
                    product.setShippingCarNumber(shippingInfo.getShippingCarNumber());
                    product.setShippingDate(shippingInfo.getShippingDate());
                    product.setShippingStatus(shippingInfo.getStatus());
                }
            }
@@ -587,21 +756,22 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saleProcessBind(SalesLedgerProcessRoute salesLedgerProcessRoute) {
        if (salesLedgerProcessRoute == null) {
    public void saleProcessBind(SalesLedgerProcessRouteDto salesLedgerProcessRouteDto) {
        if (salesLedgerProcessRouteDto == null) {
            throw new ServiceException("绑定失败,数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerProcessRoute.getSalesLedgerId());
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerProcessRouteDto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("绑定失败,销售订单不存在");
        }
        ProcessRoute processRoute = processRouteMapper.selectById(salesLedgerProcessRoute.getProcessRouteId());
        ProcessRoute processRoute = processRouteMapper.selectById(salesLedgerProcessRouteDto.getProcessRouteId());
        if (processRoute == null) {
            throw new ServiceException("绑定失败,工艺路线不存在");
        }
        //  清除已绑定的数据
        salesLedgerProcessRouteService.remove(new LambdaQueryWrapper<SalesLedgerProcessRoute>().eq(SalesLedgerProcessRoute::getSalesLedgerId, salesLedger.getId()));
        salesLedgerProcessRouteRecordService.remove(new LambdaQueryWrapper<SalesLedgerProcessRouteRecord>().eq(SalesLedgerProcessRouteRecord::getSalesLedgerId, salesLedger.getId()));
        //  将数据迁移到sales_ledger_process_route
        List<ProcessRouteItem> routeItems = processRouteItemMapper.selectList(new LambdaQueryWrapper<ProcessRouteItem>().eq(ProcessRouteItem::getRouteId, processRoute.getId()));
@@ -616,6 +786,39 @@
            salesLedgerProcessRouteList.add(ledgerProcessRoute);
        }
        salesLedgerProcessRouteService.saveBatch(salesLedgerProcessRouteList);
        List<SalesLedgerProcessRoute> savedRoutes = salesLedgerProcessRouteService.list(new LambdaQueryWrapper<SalesLedgerProcessRoute>()
            .eq(SalesLedgerProcessRoute::getSalesLedgerId, salesLedger.getId())
            .eq(SalesLedgerProcessRoute::getProcessRouteId, processRoute.getId()));
        Map<Long, SalesLedgerProcessRoute> routeMap = savedRoutes.stream()
            .filter(item -> item.getProcessRouteItemId() != null)
            .collect(Collectors.toMap(SalesLedgerProcessRoute::getProcessRouteItemId, item -> item, (a, b) -> a));
        Map<Long, SalesLedgerProcessRouteRecord> inputRecordMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(salesLedgerProcessRouteDto.getRecordList())) {
            for (SalesLedgerProcessRouteRecord record : salesLedgerProcessRouteDto.getRecordList()) {
                if (record != null && record.getProcessRouteItemId() != null) {
                    inputRecordMap.put(record.getProcessRouteItemId(), record);
                }
            }
        }
        List<SalesLedgerProcessRouteRecord> routeRecordList = new ArrayList<>();
        for (ProcessRouteItem routeItem : routeItems) {
            SalesLedgerProcessRoute route = routeMap.get(routeItem.getId());
            if (route == null || route.getId() == null) {
                continue;
            }
            SalesLedgerProcessRouteRecord inputRecord = inputRecordMap.get(routeItem.getId());
            SalesLedgerProcessRouteRecord record = new SalesLedgerProcessRouteRecord();
            record.setSalesLedgerId(salesLedger.getId());
            record.setSalesLedgerProcessRouteId(route.getId());
            Integer isCompleted = inputRecord != null && inputRecord.getIsCompleted() != null ? inputRecord.getIsCompleted() : 0;
            record.setIsCompleted(isCompleted);
            record.setCompletedTime(Objects.equals(isCompleted, 1) ? LocalDateTime.now() : null);
            routeRecordList.add(record);
        }
        salesLedgerProcessRouteRecordService.saveBatch(routeRecordList);
    }
    /**
@@ -643,21 +846,23 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSalesLedgerByIds(Long[] ids) {
        List<Long> idList = Arrays.stream(ids)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<Long> idList = Arrays.stream(ids).filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(idList)) {
            return 0;
        }
        // 校验:已审核的订单不能删除
        List<SalesLedger> ledgers = salesLedgerMapper.selectBatchIds(idList);
        for (SalesLedger ledger : ledgers) {
            if (ledger.getReviewStatus() != null && ledger.getReviewStatus() == 1) {
                throw new ServiceException("已审核的订单不能删除:" + ledger.getSalesContractNo());
            }
        }
        // 删除销售管理数据
        LambdaQueryWrapper<SalesLedgerProduct> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SalesLedgerProduct::getSalesLedgerId, idList)
                .select(SalesLedgerProduct::getId);
        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());
        List<Long> productIds = products.stream().map(SalesLedgerProduct::getId).collect(Collectors.toList());
        //删除生产数据
        salesLedgerProductServiceImpl.deleteProductionData(productIds);
@@ -693,10 +898,18 @@
            receiptPaymentMapper.delete(wrapperTree);
        }
        // 删除发货台账记录
        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(new LambdaQueryWrapper<ShippingInfo>()
                .in(ShippingInfo::getSalesLedgerId, idList));
        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()));
        }
        // 删除关联的入库/出库记录(走服务层删除,触发库存数量回退)
        List<Long> stockInRecordIds = stockInRecordMapper.selectList(new LambdaQueryWrapper<StockInRecord>().in(StockInRecord::getSalesLedgerId, idList).select(StockInRecord::getId)).stream().map(StockInRecord::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(stockInRecordIds)) {
            stockInRecordService.batchDelete(stockInRecordIds);
        }
        List<Long> stockOutRecordIds = stockOutRecordMapper.selectList(new LambdaQueryWrapper<StockOutRecord>().in(StockOutRecord::getSalesLedgerId, idList).select(StockOutRecord::getId)).stream().map(StockOutRecord::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(stockOutRecordIds)) {
            stockOutRecordService.batchDelete(stockOutRecordIds);
        }
        // 删除附件表
        commonFileService.deleteByBusinessIds(idList, FileNameType.SALE.getValue());
@@ -732,10 +945,32 @@
                String contractNo = generateSalesContractNo();
                salesLedger.setSalesContractNo(contractNo);
                salesLedger.setDeliveryStatus(1);
                salesLedger.setStockStatus(0);
                salesLedgerMapper.insert(salesLedger);
            } else {
                if (salesLedger.getDeliveryStatus() == 4) {
                if (salesLedger.getDeliveryStatus() == 5) {
                    throw new ServiceException("订单已发货,禁止编辑");
                }
                // 查询数据库中的原始记录用于校验
                SalesLedger existingLedger = salesLedgerMapper.selectById(salesLedger.getId());
                if (salesLedger.getReviewStatus() != null && salesLedger.getReviewStatus() == 1) {
                    // 审核操作:校验审核人不能是录入人(仅对未审核→已审核的转换)
                    if (existingLedger != null && existingLedger.getReviewStatus() != null && existingLedger.getReviewStatus() == 0) {
                        Long currentUserId = SecurityUtils.getUserId();
                        String entryPerson = existingLedger.getEntryPerson();
                        if (entryPerson != null && entryPerson.equals(String.valueOf(currentUserId))) {
                            throw new ServiceException("不能审核本人录入的订单");
                        }
                    }
                    salesLedger.setReviewStatus(salesLedgerDto.getReviewStatus());
                } else if (salesLedger.getReviewStatus() != null && salesLedger.getReviewStatus() == 2) {
                    handleCounterReview(salesLedger);
                } else {
                    // 未审核状态的编辑操作:校验已审核的订单不能编辑
                    if (existingLedger != null && existingLedger.getReviewStatus() != null && existingLedger.getReviewStatus() == 1) {
                        throw new ServiceException("已审核的订单不能编辑");
                    }
                    salesLedger.setReviewStatus(0);
                }
                salesLedgerMapper.updateById(salesLedger);
            }
@@ -744,13 +979,7 @@
            List<SalesLedgerProduct> productList = salesLedgerDto.getProductData();
            if (productList != null && !productList.isEmpty()) {
                handleSalesLedgerProducts(salesLedger.getId(), productList, EnumUtil.fromCode(SaleEnum.class, salesLedgerDto.getType()));
                updateMainContractAmount(
                        salesLedger.getId(),
                        productList,
                        SalesLedgerProduct::getTaxInclusiveTotalPrice,
                        salesLedgerMapper,
                        SalesLedger.class
                );
                updateMainContractAmount(salesLedger.getId(), productList, SalesLedgerProduct::getTaxInclusiveTotalPrice, salesLedgerMapper, SalesLedger.class);
            }
            // 5. 迁移临时文件到正式目录
@@ -796,10 +1025,7 @@
            // 构建正式文件名(包含业务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 : "");
            String formalFilename = businessId + "_" + System.currentTimeMillis() + "_" + UUID.randomUUID().toString().substring(0, 8) + (StringUtils.hasText(fileExtension) ? "." + fileExtension : "");
            Path formalFilePath = formalDirPath.resolve(formalFilename);
@@ -843,9 +1069,7 @@
    @Override
    public void handleSalesLedgerProducts(Long salesLedgerId, List<SalesLedgerProduct> products, SaleEnum type) {
        // 按ID分组,区分新增和更新的记录
        Map<Boolean, List<SalesLedgerProduct>> partitionedProducts = products.stream()
                .peek(p -> p.setSalesLedgerId(salesLedgerId))
                .collect(Collectors.partitioningBy(p -> p.getId() != null));
        Map<Boolean, List<SalesLedgerProduct>> partitionedProducts = products.stream().peek(p -> p.setSalesLedgerId(salesLedgerId)).collect(Collectors.partitioningBy(p -> p.getId() != null));
        List<SalesLedgerProduct> updateList = partitionedProducts.get(true);
        List<SalesLedgerProduct> insertList = partitionedProducts.get(false);
@@ -854,6 +1078,16 @@
        if (!updateList.isEmpty()) {
            for (SalesLedgerProduct product : updateList) {
                product.setType(type.getCode());
                SalesLedgerProduct db = salesLedgerProductMapper.selectById(product.getId());
                if (db != null) {
                    BigDecimal stockedQty = product.getStockedQuantity() != null ? product.getStockedQuantity() : db.getStockedQuantity();
                    BigDecimal orderQty = product.getQuantity() != null ? product.getQuantity() : db.getQuantity();
                    product.setStockedQuantity(stockedQty);
                    product.setProductStockStatus(calculateProductStockStatus(stockedQty, orderQty));
                } else {
                    product.setProductStockStatus(0);
                }
                product.fillRemainingQuantity();
                salesLedgerProductMapper.updateById(product);
                //  清空销售产品绑定的加工
                salesLedgerProductProcessBindService.updateProductProcessBind(product.getSalesProductProcessList(), product.getId());
@@ -866,6 +1100,15 @@
                salesLedgerProduct.setNoInvoiceNum(salesLedgerProduct.getQuantity());
                salesLedgerProduct.setNoInvoiceAmount(salesLedgerProduct.getTaxInclusiveTotalPrice());
                salesLedgerProduct.setPendingInvoiceTotal(salesLedgerProduct.getTaxInclusiveTotalPrice());
                BigDecimal stockedQty = salesLedgerProduct.getStockedQuantity();
                BigDecimal orderQty = salesLedgerProduct.getQuantity();
                salesLedgerProduct.setProductStockStatus(calculateProductStockStatus(stockedQty, orderQty));
                salesLedgerProduct.fillRemainingQuantity();
                ProductModel productModel = productModelMapper.selectById(salesLedgerProduct.getProductModelId());
                if (productModel == null) {
                    throw new ServiceException("新增销售台账失败,销售产品不存在");
                }
                salesLedgerProduct.setUnit(productModel.getUnit());
                salesLedgerProductMapper.insert(salesLedgerProduct);
                //  绑定产品额外加工
                //  清空销售产品绑定的加工
@@ -874,6 +1117,38 @@
//                salesLedgerProductServiceImpl.addProductionData(salesLedgerProduct);
            }
        }
        refreshSalesLedgerStockStatus(salesLedgerId);
    }
    private int calculateProductStockStatus(BigDecimal stockedQty, BigDecimal orderQty) {
        BigDecimal stocked = stockedQty == null ? BigDecimal.ZERO : stockedQty;
        BigDecimal order = orderQty == null ? BigDecimal.ZERO : orderQty;
        if (stocked.compareTo(BigDecimal.ZERO) <= 0) {
            return 0;
        }
        if (order.compareTo(BigDecimal.ZERO) > 0 && stocked.compareTo(order) < 0) {
            return 1;
        }
        return 2;
    }
    private void refreshSalesLedgerStockStatus(Long salesLedgerId) {
        if (salesLedgerId == null) return;
        SalesLedger ledger = baseMapper.selectById(salesLedgerId);
        if (ledger == null) return;
        List<SalesLedgerProduct> allProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
        if (CollectionUtils.isEmpty(allProducts)) {
            ledger.setStockStatus(0);
            baseMapper.updateById(ledger);
            return;
        }
        boolean anyInbound = allProducts.stream().anyMatch(p -> {
            BigDecimal sq = p.getStockedQuantity();
            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
        });
        boolean allFull = allProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
        ledger.setStockStatus(allFull ? 2 : (anyInbound ? 1 : 0));
        baseMapper.updateById(ledger);
    }
    private SalesLedger convertToEntity(SalesLedgerDto dto) {
@@ -928,11 +1203,7 @@
        } finally {
            // 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
            );
            redisTemplate.execute(new DefaultRedisScript<>(luaScript, Long.class), Collections.singletonList(lockKey), lockValue);
        }
    }
@@ -940,6 +1211,11 @@
    public SalesLedgerProcessRouteDto salesProcess(Long salesLedgerId) {
        SalesLedgerProcessRouteDto dto = new SalesLedgerProcessRouteDto();
        List<SalesLedgerProcessRoute> list = baseMapper.selectSalesProcess(salesLedgerId);
        List<SalesLedgerProcessRouteRecord> recordList = salesLedgerProcessRouteRecordService.list(
            new LambdaQueryWrapper<SalesLedgerProcessRouteRecord>()
                .eq(SalesLedgerProcessRouteRecord::getSalesLedgerId, salesLedgerId)
                .orderByAsc(SalesLedgerProcessRouteRecord::getId)
        );
        if (CollectionUtils.isNotEmpty(list)) {
            Long processRouteId = list.get(0).getProcessRouteId();
            ProcessRoute processRoute = processRouteMapper.selectById(processRouteId);
@@ -966,6 +1242,17 @@
            }
        }
        dto.setList(list);
        if (CollectionUtils.isNotEmpty(list) && CollectionUtils.isNotEmpty(recordList)) {
            Map<Long, Long> routeItemIdMap = list.stream()
                .filter(item -> item.getId() != null && item.getProcessRouteItemId() != null)
                .collect(Collectors.toMap(SalesLedgerProcessRoute::getId, SalesLedgerProcessRoute::getProcessRouteItemId, (a, b) -> a));
            recordList.forEach(record -> {
                if (record != null && record.getSalesLedgerProcessRouteId() != null) {
                    record.setProcessRouteItemId(routeItemIdMap.get(record.getSalesLedgerProcessRouteId()));
                }
            });
        }
        dto.setRecordList(recordList);
        return dto;
    }
@@ -989,8 +1276,7 @@
        dto.setOrderProcessRequirement(salesLedger.getRemarks());
        //  查询产品列表
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        BigDecimal totalQuantity = BigDecimal.ZERO;
        BigDecimal totalArea = BigDecimal.ZERO;
@@ -1000,8 +1286,7 @@
            SalesProcessCardDto.ProcessCardItemDto itemDto = new SalesProcessCardDto.ProcessCardItemDto();
            itemDto.setFloorCode(p.getFloorCode());
            // 组装产品描述:大类 + (规格)
            String desc = (p.getProductCategory() != null ? p.getProductCategory() : "") +
                    (StringUtils.isNotBlank(p.getSpecificationModel()) ? " " + p.getSpecificationModel() : "");
            String desc = (p.getProductCategory() != null ? p.getProductCategory() : "") + (StringUtils.isNotBlank(p.getSpecificationModel()) ? " " + p.getSpecificationModel() : "");
            itemDto.setProductDescription(desc.trim());
            itemDto.setWidth(p.getWidth());
            itemDto.setHeight(p.getHeight());
@@ -1028,22 +1313,18 @@
        dto.setTotalArea(totalArea.setScale(2, RoundingMode.HALF_UP));
        //  工艺路线
        List<SalesLedgerProcessRoute> salesLedgerProcessRoutes = salesLedgerProcessRouteService.list(
                new LambdaQueryWrapper<SalesLedgerProcessRoute>()
                        .eq(SalesLedgerProcessRoute::getSalesLedgerId, salesLedgerId)
                        .orderByAsc(SalesLedgerProcessRoute::getDragSort));
        List<SalesLedgerProcessRoute> salesLedgerProcessRoutes = salesLedgerProcessRouteService.list(new LambdaQueryWrapper<SalesLedgerProcessRoute>().eq(SalesLedgerProcessRoute::getSalesLedgerId, salesLedgerId).orderByAsc(SalesLedgerProcessRoute::getDragSort));
        List<SalesProcessCardDto.ProcessNodeDto> nodeDtos = new ArrayList<>();
        if (CollectionUtils.isEmpty(salesLedgerProcessRoutes)) {
            // 无自定义路线,取默认路线
            ProcessRoute defaultRoute = processRouteMapper.selectOne(
                    new LambdaQueryWrapper<ProcessRoute>().eq(ProcessRoute::getIsDefault, 1).last("LIMIT 1"));
            if (defaultRoute != null) {
                List<ProcessRouteItem> routeItems = processRouteItemMapper.selectList(
                        new LambdaQueryWrapper<ProcessRouteItem>()
                                .eq(ProcessRouteItem::getRouteId, defaultRoute.getId())
                                .orderByAsc(ProcessRouteItem::getDragSort));
            // 无自定义路线:先查询默认工艺路线;若无默认,获取创建时间最近的一条
            ProcessRoute fallbackRoute = processRouteMapper.selectOne(new LambdaQueryWrapper<ProcessRoute>().eq(ProcessRoute::getIsDefault, 1).last("LIMIT 1"));
            if (fallbackRoute == null) {
                fallbackRoute = processRouteMapper.selectOne(new LambdaQueryWrapper<ProcessRoute>().orderByDesc(ProcessRoute::getCreateTime).last("LIMIT 1"));
            }
            if (fallbackRoute != null) {
                List<ProcessRouteItem> routeItems = processRouteItemMapper.selectList(new LambdaQueryWrapper<ProcessRouteItem>().eq(ProcessRouteItem::getRouteId, fallbackRoute.getId()).orderByAsc(ProcessRouteItem::getDragSort));
                for (ProcessRouteItem i : routeItems) {
                    SalesProcessCardDto.ProcessNodeDto node = new SalesProcessCardDto.ProcessNodeDto();
                    node.setProcessRouteItemId(i.getId());
@@ -1054,12 +1335,9 @@
            }
        } else {
            // 使用自定义路线绑定的节点
            List<Long> itemIds = salesLedgerProcessRoutes.stream()
                    .map(SalesLedgerProcessRoute::getProcessRouteItemId)
                    .collect(Collectors.toList());
            List<Long> itemIds = salesLedgerProcessRoutes.stream().map(SalesLedgerProcessRoute::getProcessRouteItemId).collect(Collectors.toList());
            List<ProcessRouteItem> rawItems = processRouteItemMapper.selectBatchIds(itemIds);
            Map<Long, ProcessRouteItem> itemMap = rawItems.stream()
                    .collect(Collectors.toMap(ProcessRouteItem::getId, i -> i, (a, b) -> a));
            Map<Long, ProcessRouteItem> itemMap = rawItems.stream().collect(Collectors.toMap(ProcessRouteItem::getId, i -> i, (a, b) -> a));
            for (SalesLedgerProcessRoute r : salesLedgerProcessRoutes) {
                ProcessRouteItem pi = itemMap.get(r.getProcessRouteItemId());
@@ -1076,14 +1354,9 @@
        if (!nodeDtos.isEmpty()) {
            //  dragSort 进行升序排序
            nodeDtos.sort(Comparator.comparing(
                    SalesProcessCardDto.ProcessNodeDto::getDragSort,
                    Comparator.nullsLast(Comparator.naturalOrder())
            ));
            nodeDtos.sort(Comparator.comparing(SalesProcessCardDto.ProcessNodeDto::getDragSort, Comparator.nullsLast(Comparator.naturalOrder())));
            //  重新生成排序后的路径名称列表
            List<String> sortedPathNames = nodeDtos.stream()
                    .map(SalesProcessCardDto.ProcessNodeDto::getProcessRouteItemName)
                    .collect(Collectors.toList());
            List<String> sortedPathNames = nodeDtos.stream().map(SalesProcessCardDto.ProcessNodeDto::getProcessRouteItemName).collect(Collectors.toList());
            //  拼接字符串
            dto.setProcessPathDisplay(String.join(" -> ", sortedPathNames));
            // 设置顶层节点的工艺路线
@@ -1153,8 +1426,7 @@
        dto.setPrintTime(LocalDateTime.now());
        // 查询产品列表
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        if (CollectionUtils.isNotEmpty(products)) {
            SalesLedgerProduct firstProduct = products.get(0);
@@ -1169,8 +1441,7 @@
        for (SalesLedgerProduct p : products) {
            SalesOrdersDto.SalesOrderItemDto itemDto = new SalesOrdersDto.SalesOrderItemDto();
            itemDto.setFloorCode(p.getFloorCode());
            String desc = (p.getProductCategory() != null ? p.getProductCategory() : "") +
                    (StringUtils.isNotBlank(p.getSpecificationModel()) ? " " + p.getSpecificationModel() : "");
            String desc = (p.getProductCategory() != null ? p.getProductCategory() : "") + (StringUtils.isNotBlank(p.getSpecificationModel()) ? " " + p.getSpecificationModel() : "");
            itemDto.setProductDescription(desc.trim());
            itemDto.setWidth(p.getWidth());
            itemDto.setHeight(p.getHeight());
@@ -1202,13 +1473,10 @@
        List<Long> productIds = products.stream().map(SalesLedgerProduct::getId).collect(Collectors.toList());
        BigDecimal otherFeesTotal = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(productIds)) {
            List<SalesLedgerProductProcessBind> binds = salesLedgerProductProcessBindService.list(
                    new LambdaQueryWrapper<SalesLedgerProductProcessBind>().in(SalesLedgerProductProcessBind::getSalesLedgerProductId, productIds));
            List<SalesLedgerProductProcessBind> binds = salesLedgerProductProcessBindService.list(new LambdaQueryWrapper<SalesLedgerProductProcessBind>().in(SalesLedgerProductProcessBind::getSalesLedgerProductId, productIds));
            if (CollectionUtils.isNotEmpty(binds)) {
                Map<Integer, Integer> processQuantityMap = binds.stream()
                        .collect(Collectors.groupingBy(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId,
                                Collectors.summingInt(b -> b.getQuantity() != null ? b.getQuantity() : 0)));
                Map<Integer, Integer> processQuantityMap = binds.stream().collect(Collectors.groupingBy(SalesLedgerProductProcessBind::getSalesLedgerProductProcessId, Collectors.summingInt(b -> b.getQuantity() != null ? b.getQuantity() : 0)));
                List<Integer> processIds = new ArrayList<>(processQuantityMap.keySet());
                List<SalesLedgerProductProcess> processes = salesLedgerProductProcessService.listByIds(processIds);
@@ -1290,59 +1558,84 @@
//        dto.setExternalOrderNo(ledgers.get(0).getCustomerContractNo());
        //  查询所有产品
        List<SalesLedgerProduct> allProducts = salesLedgerProductMapper.selectList(
                new LambdaQueryWrapper<SalesLedgerProduct>().in(SalesLedgerProduct::getSalesLedgerId, salesLedgerIds));
        List<SalesLedgerProduct> allProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().in(SalesLedgerProduct::getSalesLedgerId, salesLedgerIds).eq(SalesLedgerProduct::getType, 1));
        if (CollectionUtils.isNotEmpty(allProducts)) {
            Map<Long, SalesLedger> ledgerMap = ledgers.stream()
                    .collect(Collectors.toMap(SalesLedger::getId, Function.identity()));
            Map<Long, List<SalesLedgerProduct>> groupedData = new LinkedHashMap<>();
            for (SalesLedgerProduct p : allProducts) {
                groupedData.computeIfAbsent(p.getSalesLedgerId(), k -> new ArrayList<>()).add(p);
            }
            Map<Long, SalesLedger> ledgerMap = ledgers.stream().collect(Collectors.toMap(SalesLedger::getId, Function.identity()));
            List<SalesInvoicesDto.InvoiceOrderGroupDto> groups = new ArrayList<>();
            BigDecimal totalQty = BigDecimal.ZERO;
            BigDecimal totalArea = BigDecimal.ZERO;
            for (Map.Entry<Long, List<SalesLedgerProduct>> ledgerEntry : groupedData.entrySet()) {
                SalesLedger ledger = ledgerMap.get(ledgerEntry.getKey());
                String orderNo = ledger != null ? ledger.getSalesContractNo() : "";
                List<SalesLedgerProduct> products = ledgerEntry.getValue();
            Map<String, List<SalesLedgerProduct>> groupedData = new LinkedHashMap<>();
            Map<String, Set<String>> groupOrderNos = new LinkedHashMap<>();
            for (SalesLedgerProduct p : allProducts) {
                String productCategory = StringUtils.defaultString(p.getProductCategory(), "");
                String specificationModel = StringUtils.defaultString(p.getSpecificationModel(), "");
                String groupKey = productCategory + "||" + specificationModel;
                groupedData.computeIfAbsent(groupKey, k -> new ArrayList<>()).add(p);
                SalesLedger ledger = ledgerMap.get(p.getSalesLedgerId());
                String orderNo = ledger != null ? StringUtils.defaultString(ledger.getSalesContractNo(), "") : "";
                if (StringUtils.isNotEmpty(orderNo)) {
                    groupOrderNos.computeIfAbsent(groupKey, k -> new LinkedHashSet<>()).add(orderNo);
                }
            }
            for (Map.Entry<String, List<SalesLedgerProduct>> productEntry : groupedData.entrySet()) {
                String key = productEntry.getKey();
                String[] parts = key.split("\\|\\|", -1);
                String productName = parts.length > 0 ? parts[0] : "";
                String specificationModel = parts.length > 1 ? parts[1] : "";
                List<SalesLedgerProduct> products = productEntry.getValue();
                SalesInvoicesDto.InvoiceOrderGroupDto group = new SalesInvoicesDto.InvoiceOrderGroupDto();
                group.setSalesContractNo(orderNo);
                if (CollectionUtils.isNotEmpty(products)) {
                    group.setProductName(products.get(0).getProductCategory());
                }
                Set<String> orderNos = groupOrderNos.getOrDefault(key, Collections.emptySet());
                group.setSalesContractNo(String.join(",", orderNos));
                group.setProductName(productName);
                group.setSpecificationModel(specificationModel);
                List<SalesInvoicesDto.InvoiceItemDto> itemDtos = new ArrayList<>();
                Map<String, SalesInvoicesDto.InvoiceItemDto> mergedItems = new LinkedHashMap<>();
                BigDecimal groupQty = BigDecimal.ZERO;
                BigDecimal groupArea = BigDecimal.ZERO;
                for (SalesLedgerProduct p : products) {
                    SalesInvoicesDto.InvoiceItemDto item = new SalesInvoicesDto.InvoiceItemDto();
                    item.setFloorCode(p.getFloorCode());
                    item.setWidthHeight((p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") +
                            " * " + (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0"));
                    item.setQuantity(p.getQuantity());
                    String widthHeight = (p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") + " * " + (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0");
                    String floorCode = StringUtils.defaultString(p.getFloorCode(), "");
                    String remark = StringUtils.defaultString(p.getRemark(), "");
                    String processReq = StringUtils.defaultString(p.getProcessRequirement(), "");
                    String itemKey = floorCode + "||" + widthHeight + "||" + remark + "||" + processReq;
                    BigDecimal qty = p.getQuantity() != null ? p.getQuantity() : BigDecimal.ZERO;
                    // 面积
                    BigDecimal area = p.getSettleTotalArea() != null ? p.getSettleTotalArea() : p.getActualTotalArea();
                    if (area == null && p.getWidth() != null && p.getHeight() != null && p.getQuantity() != null) {
                        area = p.getWidth().multiply(p.getHeight()).multiply(p.getQuantity()).divide(new BigDecimal(1000000), 2, RoundingMode.HALF_UP);
                    }
                    item.setArea(area);
                    item.setRemark(p.getRemark());
                    item.setProcessRequirement(p.getProcessRequirement());
                    area = area != null ? area : BigDecimal.ZERO;
                    itemDtos.add(item);
                    groupQty = groupQty.add(p.getQuantity() != null ? p.getQuantity() : BigDecimal.ZERO);
                    groupArea = groupArea.add(area != null ? area : BigDecimal.ZERO);
                    SalesInvoicesDto.InvoiceItemDto item = mergedItems.get(itemKey);
                    if (item == null) {
                        item = new SalesInvoicesDto.InvoiceItemDto();
                        item.setFloorCode(floorCode);
                        item.setWidthHeight(widthHeight);
                        item.setSpecificationModel(p.getSpecificationModel());
                        item.setQuantity(qty);
                        item.setArea(area);
                        item.setRemark(remark);
                        item.setProcessRequirement(processReq);
                        mergedItems.put(itemKey, item);
                    } else {
                        item.setQuantity((item.getQuantity() != null ? item.getQuantity() : BigDecimal.ZERO).add(qty));
                        item.setArea((item.getArea() != null ? item.getArea() : BigDecimal.ZERO).add(area));
                    }
                    groupQty = groupQty.add(qty);
                    groupArea = groupArea.add(area);
                }
                group.setItems(itemDtos);
                group.setItems(new ArrayList<>(mergedItems.values()));
                group.setGroupTotalQuantity(groupQty);
                group.setGroupTotalArea(groupArea.setScale(2, RoundingMode.HALF_UP));
                groups.add(group);
@@ -1375,8 +1668,7 @@
        }
        // 查询产品列表
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, salesLedgerId));
        // 查询客户地址
        String fullAddress = "";
@@ -1403,12 +1695,10 @@
                SalesLabelDto dto = new SalesLabelDto();
                dto.setCustomerName(salesLedger.getCustomerName());
                dto.setSalesContractNo(salesLedger.getSalesContractNo());
                dto.setProductName(p.getProductCategory());
                dto.setProductName(p.getSpecificationModel());
                // 宽*高=数量
                String specification = (p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") + "*" +
                        (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0") + "=" +
                        (p.getQuantity() != null ? p.getQuantity().stripTrailingZeros().toPlainString() : "0");
                String specification = (p.getWidth() != null ? p.getWidth().stripTrailingZeros().toPlainString() : "0") + "*" + (p.getHeight() != null ? p.getHeight().stripTrailingZeros().toPlainString() : "0") + "=" + (p.getQuantity() != null ? p.getQuantity().stripTrailingZeros().toPlainString() : "0");
                dto.setSpecification(specification);
                // 客户地址 + 楼层编号
@@ -1437,22 +1727,14 @@
        return next;
    }
    public <T, S> void updateMainContractAmount(
            Long mainId,
            List<T> subList,
            Function<T, BigDecimal> amountGetter,
            BaseMapper<S> mainMapper,
            Class<S> mainEntityClass) {
    public <T, S> void updateMainContractAmount(Long mainId, List<T> subList, Function<T, BigDecimal> amountGetter, BaseMapper<S> mainMapper, Class<S> mainEntityClass) {
        if (mainId == null || subList == null || subList.isEmpty()) {
            return;
        }
        // 计算子表金额总和
        BigDecimal totalAmount = subList.stream()
                .map(amountGetter)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalAmount = subList.stream().map(amountGetter).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
        // 构造主表更新对象
        try {
@@ -1500,4 +1782,2441 @@
            return totalAmount;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void salesStock(SalesProductStockDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new NullPointerException("入库失败,请选择需要入库的销售订单");
        }
        //  查询销售订单是否存在
        SalesLedger ledger = baseMapper.selectById(dto.getSalesLedgerId());
        if (ledger == null) {
            throw new ServiceException("入库失败,销售订单不存在");
        }
        if (ledger.getStockStatus() == null) {
            throw new ServiceException("入库失败,销售订单入库状态异常");
        }
        if (ledger.getStockStatus() == 3) {
            throw new ServiceException("入库失败,该销售订单正在入库审批中,请勿重复提交");
        }
        if (ledger.getStockStatus() == 2) {
            throw new ServiceException("入库失败,该销售订单已入库,请勿重复入库");
        }
        List<Long> products = dto.getSalesLedgerProducts();
        if (products == null || products.isEmpty()) {
            throw new ServiceException("入库失败,入库产品不能为空");
        }
        //  查询销售订单的产品
        List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().in(SalesLedgerProduct::getId, products));
        if (salesLedgerProducts == null || salesLedgerProducts.isEmpty()) {
            throw new ServiceException("入库失败,未查询到该销售订单的销售产品");
        }
        String approveUserIds = resolveApproveUserIds(dto.getApproveUserIds(), ledger.getId(), INBOUND_BIZ_TYPE_WEB);
        if (StringUtils.isEmpty(approveUserIds)) {
            throw new ServiceException("入库失败,请选择审批人");
        }
        String productIds = products.stream().map(String::valueOf).collect(Collectors.joining(","));
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveReason("入库审批:" + ledger.getSalesContractNo());
        approveProcessVO.setApproveRemark("salesStock:" + ledger.getId() + ":" + productIds);
        approveProcessVO.setApproveUserIds(approveUserIds);
        approveProcessVO.setApproveUser(loginUser.getUserId());
        approveProcessVO.setApproveTime(LocalDate.now().toString());
        try {
            approveProcessService.addApprove(approveProcessVO);
        } catch (Exception e) {
            throw new ServiceException("入库审批发起失败:" + e.getMessage());
        }
        // 审批中
        ledger.setStockStatus(3);
        baseMapper.updateById(ledger);
    }
    @Override
    public void executeSalesStockApproved(Long salesLedgerId, List<Long> products) {
        SalesProductStockDto dto = new SalesProductStockDto();
        dto.setSalesLedgerId(salesLedgerId);
        dto.setSalesLedgerProducts(products);
        SalesLedger ledger = baseMapper.selectById(dto.getSalesLedgerId());
        if (ledger == null) {
            throw new ServiceException("入库失败,销售订单不存在");
        }
        List<SalesLedgerProduct> salesLedgerProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().in(SalesLedgerProduct::getId, products));
        for (SalesLedgerProduct product : salesLedgerProducts) {
            if (!Objects.equals(product.getSalesLedgerId(), ledger.getId())) {
                throw new ServiceException("入库失败,存在不属于当前销售订单的产品");
            }
            if (product.getProductModelId() == null) {
                continue;
            }
            BigDecimal orderQty = product.getQuantity() == null ? BigDecimal.ZERO : product.getQuantity();
            BigDecimal oldStocked = product.getStockedQuantity() == null ? BigDecimal.ZERO : product.getStockedQuantity();
            BigDecimal inboundQty = orderQty.subtract(oldStocked);
            if (inboundQty.compareTo(BigDecimal.ZERO) < 0) {
                inboundQty = BigDecimal.ZERO;
            }
            if (inboundQty.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setRecordId(product.getId());
            stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode());
            stockInventoryDto.setQualitity(inboundQty);
            stockInventoryDto.setProductModelId(product.getProductModelId());
            stockInventoryDto.setSalesLedgerId(ledger.getId());
            stockInventoryDto.setSalesLedgerProductId(product.getId());
            stockInventoryService.addstockInventory(stockInventoryDto);
            BigDecimal newStocked = oldStocked.add(inboundQty);
            int lineStockStatus;
            if (newStocked.compareTo(BigDecimal.ZERO) <= 0) {
                lineStockStatus = 0;
            } else if (orderQty.compareTo(BigDecimal.ZERO) > 0 && newStocked.compareTo(orderQty) < 0) {
                lineStockStatus = 1;
            } else {
                lineStockStatus = 2;
            }
            product.setStockedQuantity(newStocked);
            product.setProductStockStatus(lineStockStatus);
            product.fillRemainingQuantity();
            salesLedgerProductMapper.updateById(product);
        }
        //  按销售订单产品入库情况更新主单入库状态:1-部分入库,2-已入库
        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()));
        boolean hasStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().anyMatch(item -> {
            BigDecimal sq = item.getStockedQuantity();
            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
        });
        boolean allStocked = CollectionUtils.isNotEmpty(ledgerAllProducts) && ledgerAllProducts.stream().allMatch(item -> {
            BigDecimal orderQty = item.getQuantity() == null ? BigDecimal.ZERO : item.getQuantity();
            BigDecimal stockedQty = item.getStockedQuantity() == null ? BigDecimal.ZERO : item.getStockedQuantity();
            return orderQty.compareTo(BigDecimal.ZERO) <= 0 || stockedQty.compareTo(orderQty) >= 0;
        });
        ledger.setStockStatus(allStocked ? 2 : (hasStocked ? 1 : 0));
        baseMapper.updateById(ledger);
    }
    @Override
    public List<Customer> shippedCustomers() {
        List<SalesLedger> ledgers = list(Wrappers.<SalesLedger>lambdaQuery().eq(SalesLedger::getDeliveryStatus, 5).isNotNull(SalesLedger::getCustomerId).select(SalesLedger::getCustomerId));
        if (CollectionUtils.isEmpty(ledgers)) {
            return Collections.emptyList();
        }
        Set<Long> customerIds = ledgers.stream().map(SalesLedger::getCustomerId).collect(Collectors.toCollection(LinkedHashSet::new));
        return customerMapper.selectList(Wrappers.<Customer>lambdaQuery().in(Customer::getId, customerIds).orderByAsc(Customer::getCustomerName));
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanInbound(SalesScanInboundDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new ServiceException("销售订单入库失败,入库数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("入库失败,销售订单不存在");
        }
        if (salesLedger.getStockStatus() == null) {
            throw new ServiceException("入库失败,销售订单状态异常");
        }
        if (salesLedger.getStockStatus() == 2) {
            throw new ServiceException("入库失败,该销售订单已全部入库");
        }
        if (salesLedger.getDeliveryStatus() == 5) {
            throw new ServiceException("入库失败,该销售订单已发货");
        }
        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
            throw new ServiceException("销售订单入库失败,入库产品不能为空");
        }
        //  本次入库数量可以大于订单数量,但不能为负
        Map<Long, BigDecimal> inboundQtyByLineId = new LinkedHashMap<>();
        for (SalesLedgerProduct inbound : dto.getSalesLedgerProductList()) {
            if (inbound == null || inbound.getId() == null) {
                throw new ServiceException("入库失败,销售产品信息不完整");
            }
            BigDecimal inboundQty = inbound.getStockedQuantity();
            if (inboundQty == null) {
                throw new ServiceException("入库失败,入库数量不能为空");
            }
            if (inboundQty.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("入库失败,入库数量不能为负数");
            }
            inboundQtyByLineId.merge(inbound.getId(), inboundQty, BigDecimal::add);
        }
        List<SalesLedgerProduct> selectedProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().in(SalesLedgerProduct::getId, inboundQtyByLineId.keySet()));
        if (CollectionUtils.isEmpty(selectedProducts)) {
            throw new ServiceException("入库失败,未查询到入库产品");
        }
        if (selectedProducts.size() != inboundQtyByLineId.size()) {
            throw new ServiceException("入库失败,部分产品不存在");
        }
        for (SalesLedgerProduct selectedProduct : selectedProducts) {
            if (!Objects.equals(selectedProduct.getSalesLedgerId(), salesLedger.getId())) {
                throw new ServiceException("入库失败,销售产品与订单不匹配");
            }
            if (!Objects.equals(selectedProduct.getType(), SaleEnum.SALE.getCode())) {
                throw new ServiceException("入库失败,仅支持销售订单产品行");
            }
            if (selectedProduct.getProductModelId() == null) {
                throw new ServiceException("入库失败,产品规格未维护,无法入库");
            }
            BigDecimal orderQty = selectedProduct.getQuantity() == null ? BigDecimal.ZERO : selectedProduct.getQuantity();
            BigDecimal qualifiedStocked = selectedProduct.getStockedQuantity() == null ? BigDecimal.ZERO : selectedProduct.getStockedQuantity();
            BigDecimal inboundQty = inboundQtyByLineId.getOrDefault(selectedProduct.getId(), BigDecimal.ZERO);
            if (inboundQty.compareTo(BigDecimal.ZERO) > 0 && qualifiedStocked.add(inboundQty).compareTo(orderQty) > 0) {
                throw new ServiceException("入库失败,合格入库数量之和不能大于订单数量");
            }
        }
        String approveUserIds = resolveApproveUserIds(dto.getApproveUserIds(), salesLedger.getId(), INBOUND_BIZ_TYPE_SCAN_QUALIFIED);
        if (StringUtils.isEmpty(approveUserIds)) {
            throw new ServiceException("入库失败,请选择审批人");
        }
        String lines = inboundQtyByLineId.entrySet().stream().map(e -> e.getKey() + "@" + e.getValue().stripTrailingZeros().toPlainString()).collect(Collectors.joining(","));
        String reason = "销售扫码合格入库审批:" + salesLedger.getSalesContractNo();
        String remark = "scanQualified:" + salesLedger.getId() + ":" + lines;
        ApproveProcess exist = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>().eq(ApproveProcess::getApproveType, ApproveTypeEnum.STOCK_IN.getCode()).eq(ApproveProcess::getApproveRemark, remark).eq(ApproveProcess::getApproveDelete, 0).orderByDesc(ApproveProcess::getCreateTime).last("limit 1"));
        if (exist != null && !Objects.equals(exist.getApproveStatus(), 3)) {
            throw new ServiceException("入库失败,该申请已提交审批");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveReason(reason);
        approveProcessVO.setApproveRemark(remark);
        approveProcessVO.setApproveUserIds(approveUserIds);
        approveProcessVO.setApproveUser(loginUser.getUserId());
        approveProcessVO.setApproveTime(LocalDate.now().toString());
        try {
            approveProcessService.addApprove(approveProcessVO);
        } catch (Exception e) {
            throw new ServiceException("入库审批发起失败:" + e.getMessage());
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeSalesScanInboundApproved(Long salesLedgerId, Map<Long, BigDecimal> inboundQtyByLineId) {
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerId);
        if (salesLedger == null) {
            throw new ServiceException("入库失败,销售订单不存在");
        }
        Long ledgerId = salesLedger.getId();
        for (Map.Entry<Long, BigDecimal> entry : inboundQtyByLineId.entrySet()) {
            Long salesLedgerProductId = entry.getKey();
            BigDecimal inboundThisLine = entry.getValue();
            if (inboundThisLine == null || inboundThisLine.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
            if (dbProduct == null) {
                throw new ServiceException("入库失败,销售产品不存在");
            }
            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId)) {
                throw new ServiceException("入库失败,销售产品与订单不匹配");
            }
            if (!Objects.equals(dbProduct.getType(), SaleEnum.SALE.getCode())) {
                throw new ServiceException("入库失败,仅支持销售订单产品行");
            }
            if (dbProduct.getProductModelId() == null) {
                throw new ServiceException("入库失败,产品规格未维护,无法入库");
            }
            BigDecimal oldStocked = dbProduct.getStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getStockedQuantity();
            BigDecimal newStocked = oldStocked.add(inboundThisLine);
            BigDecimal orderQty = dbProduct.getQuantity() == null ? BigDecimal.ZERO : dbProduct.getQuantity();
            if (newStocked.compareTo(orderQty) > 0) {
                throw new ServiceException("入库失败,合格入库数量之和不能大于订单数量");
            }
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setRecordId(dbProduct.getId());
            stockInventoryDto.setRecordType(StockInQualifiedRecordTypeEnum.SALE_SCAN_STOCK_IN.getCode());
            stockInventoryDto.setQualitity(inboundThisLine);
            stockInventoryDto.setProductModelId(dbProduct.getProductModelId());
            stockInventoryDto.setSalesLedgerId(ledgerId);
            stockInventoryDto.setSalesLedgerProductId(dbProduct.getId());
            stockInventoryService.addstockInventory(stockInventoryDto);
            int lineStockStatus;
            if (newStocked.compareTo(BigDecimal.ZERO) <= 0) {
                lineStockStatus = 0;
            } else if (orderQty.compareTo(BigDecimal.ZERO) > 0 && newStocked.compareTo(orderQty) < 0) {
                lineStockStatus = 1;
            } else {
                lineStockStatus = 2;
            }
            dbProduct.setStockedQuantity(newStocked);
            dbProduct.setProductStockStatus(lineStockStatus);
            dbProduct.fillRemainingQuantity();
            salesLedgerProductMapper.updateById(dbProduct);
        }
        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledgerId));
        boolean anyInbound = ledgerAllProducts.stream().anyMatch(p -> {
            BigDecimal sq = p.getStockedQuantity();
            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
        });
        boolean allLinesFull = ledgerAllProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
        salesLedger.setStockStatus(allLinesFull ? 2 : (anyInbound ? 1 : 0));
        baseMapper.updateById(salesLedger);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanInboundUnqualified(SalesScanInboundDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new ServiceException("销售订单不合格入库失败,入库数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("不合格入库失败,销售订单不存在");
        }
        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
            throw new ServiceException("不合格入库失败,该销售订单已发货");
        }
        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
            throw new ServiceException("销售订单不合格入库失败,入库产品不能为空");
        }
        Map<Long, BigDecimal> inboundQtyByLineId = new LinkedHashMap<>();
        for (SalesLedgerProduct inbound : dto.getSalesLedgerProductList()) {
            if (inbound == null || inbound.getId() == null) {
                throw new ServiceException("不合格入库失败,销售产品信息不完整");
            }
            BigDecimal inboundQty = inbound.getStockedQuantity();
            if (inboundQty == null) {
                throw new ServiceException("不合格入库失败,入库数量不能为空");
            }
            if (inboundQty.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("不合格入库失败,入库数量不能为负数");
            }
            inboundQtyByLineId.merge(inbound.getId(), inboundQty, BigDecimal::add);
        }
        List<SalesLedgerProduct> selectedProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().in(SalesLedgerProduct::getId, inboundQtyByLineId.keySet()));
        if (CollectionUtils.isEmpty(selectedProducts)) {
            throw new ServiceException("不合格入库失败,未查询到入库产品");
        }
        if (selectedProducts.size() != inboundQtyByLineId.size()) {
            throw new ServiceException("不合格入库失败,部分产品不存在");
        }
        for (SalesLedgerProduct selectedProduct : selectedProducts) {
            if (!Objects.equals(selectedProduct.getSalesLedgerId(), salesLedger.getId())) {
                throw new ServiceException("不合格入库失败,销售产品与订单不匹配");
            }
            if (!Objects.equals(selectedProduct.getType(), SaleEnum.SALE.getCode())) {
                throw new ServiceException("不合格入库失败,仅支持销售订单产品行");
            }
            if (selectedProduct.getProductModelId() == null) {
                throw new ServiceException("不合格入库失败,产品规格未维护,无法入库");
            }
            BigDecimal orderQty = selectedProduct.getQuantity() == null ? BigDecimal.ZERO : selectedProduct.getQuantity();
            BigDecimal qualifiedStocked = selectedProduct.getStockedQuantity() == null ? BigDecimal.ZERO : selectedProduct.getStockedQuantity();
            BigDecimal unqualifiedStocked = selectedProduct.getUnqualifiedStockedQuantity() == null ? BigDecimal.ZERO : selectedProduct.getUnqualifiedStockedQuantity();
            BigDecimal inboundQty = inboundQtyByLineId.getOrDefault(selectedProduct.getId(), BigDecimal.ZERO);
            BigDecimal remainForUnqualified = orderQty.subtract(qualifiedStocked);
            if (remainForUnqualified.compareTo(BigDecimal.ZERO) <= 0 && inboundQty.compareTo(BigDecimal.ZERO) > 0) {
                throw new ServiceException("不合格入库失败,该产品已无可入不合格库数量");
            }
            if (inboundQty.compareTo(BigDecimal.ZERO) > 0 && unqualifiedStocked.add(inboundQty).compareTo(orderQty) > 0) {
                throw new ServiceException("不合格入库失败,不合格入库数量之和不能大于订单数量");
            }
            if (inboundQty.compareTo(BigDecimal.ZERO) > 0 && unqualifiedStocked.add(inboundQty).compareTo(remainForUnqualified) > 0) {
                throw new ServiceException("不合格入库失败,不合格入库数量不能大于订单数量减去合格入库数量");
            }
        }
        String approveUserIds = resolveApproveUserIds(dto.getApproveUserIds(), salesLedger.getId(), INBOUND_BIZ_TYPE_SCAN_UNQUALIFIED);
        if (StringUtils.isEmpty(approveUserIds)) {
            throw new ServiceException("不合格入库失败,请选择审批人");
        }
        String lines = inboundQtyByLineId.entrySet().stream().map(e -> e.getKey() + "@" + e.getValue().stripTrailingZeros().toPlainString()).collect(Collectors.joining(","));
        String reason = "销售扫码不合格入库审批:" + salesLedger.getSalesContractNo();
        String remark = "scanUnqualified:" + salesLedger.getId() + ":" + lines;
        ApproveProcess exist = approveProcessService.getOne(new LambdaQueryWrapper<ApproveProcess>().eq(ApproveProcess::getApproveType, ApproveTypeEnum.STOCK_IN.getCode()).eq(ApproveProcess::getApproveRemark, remark).eq(ApproveProcess::getApproveDelete, 0).orderByDesc(ApproveProcess::getCreateTime).last("limit 1"));
        if (exist != null && !Objects.equals(exist.getApproveStatus(), 3)) {
            throw new ServiceException("不合格入库失败,该申请已提交审批");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(ApproveTypeEnum.STOCK_IN.getCode());
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveReason(reason);
        approveProcessVO.setApproveRemark(remark);
        approveProcessVO.setApproveUserIds(approveUserIds);
        approveProcessVO.setApproveUser(loginUser.getUserId());
        approveProcessVO.setApproveTime(LocalDate.now().toString());
        try {
            approveProcessService.addApprove(approveProcessVO);
        } catch (Exception e) {
            throw new ServiceException("不合格入库审批发起失败:" + e.getMessage());
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeSalesScanInboundUnqualifiedApproved(Long salesLedgerId, Map<Long, BigDecimal> inboundQtyByLineId) {
        SalesLedger salesLedger = baseMapper.selectById(salesLedgerId);
        if (salesLedger == null) {
            throw new ServiceException("不合格入库失败,销售订单不存在");
        }
        Long ledgerId = salesLedger.getId();
        for (Map.Entry<Long, BigDecimal> entry : inboundQtyByLineId.entrySet()) {
            Long salesLedgerProductId = entry.getKey();
            BigDecimal inboundThisLine = entry.getValue();
            if (inboundThisLine == null || inboundThisLine.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
            if (dbProduct == null) {
                throw new ServiceException("不合格入库失败,销售产品不存在");
            }
            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId)) {
                throw new ServiceException("不合格入库失败,销售产品与订单不匹配");
            }
            if (!Objects.equals(dbProduct.getType(), SaleEnum.SALE.getCode())) {
                throw new ServiceException("不合格入库失败,仅支持销售订单产品行");
            }
            if (dbProduct.getProductModelId() == null) {
                throw new ServiceException("不合格入库失败,产品规格未维护,无法入库");
            }
            BigDecimal orderQty = dbProduct.getQuantity() == null ? BigDecimal.ZERO : dbProduct.getQuantity();
            BigDecimal qualifiedStocked = dbProduct.getStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getStockedQuantity();
            BigDecimal oldUnStocked = dbProduct.getUnqualifiedStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getUnqualifiedStockedQuantity();
            BigDecimal newUnStocked = oldUnStocked.add(inboundThisLine);
            BigDecimal remainForUnqualified = orderQty.subtract(qualifiedStocked);
            if (remainForUnqualified.compareTo(BigDecimal.ZERO) <= 0) {
                throw new ServiceException("不合格入库失败,该产品已无可入不合格库数量");
            }
            if (newUnStocked.compareTo(orderQty) > 0) {
                throw new ServiceException("不合格入库失败,不合格入库数量之和不能大于订单数量");
            }
            if (newUnStocked.compareTo(remainForUnqualified) > 0) {
                throw new ServiceException("不合格入库失败,不合格入库数量不能大于订单数量减去合格入库数量");
            }
            stockUtils.addUnStock(ledgerId, dbProduct.getId(), dbProduct.getProductModelId(), inboundThisLine, StockInUnQualifiedRecordTypeEnum.SALES_SCAN_UNSTOCK_IN.getCode(), dbProduct.getId());
            dbProduct.setUnqualifiedStockedQuantity(newUnStocked);
            dbProduct.fillRemainingQuantity();
            salesLedgerProductMapper.updateById(dbProduct);
        }
    }
    private String resolveApproveUserIds(String approveUserIds, Long salesLedgerId, Integer bizType) {
        if (StringUtils.isNotEmpty(approveUserIds)) {
            return approveUserIds;
        }
        LambdaQueryWrapper<ApproveProcess> wrapper = new LambdaQueryWrapper<ApproveProcess>().eq(ApproveProcess::getApproveType, ApproveTypeEnum.STOCK_IN.getCode()).eq(ApproveProcess::getApproveDelete, 0).orderByDesc(ApproveProcess::getCreateTime).last("limit 1");
        if (Objects.equals(bizType, INBOUND_BIZ_TYPE_WEB)) {
            wrapper.likeRight(ApproveProcess::getApproveReason, "入库审批:").likeRight(ApproveProcess::getApproveRemark, "salesStock:" + salesLedgerId + ":");
        } else if (Objects.equals(bizType, INBOUND_BIZ_TYPE_SCAN_QUALIFIED)) {
            wrapper.likeRight(ApproveProcess::getApproveReason, "销售扫码合格入库审批:").likeRight(ApproveProcess::getApproveRemark, "scanQualified:" + salesLedgerId + ":");
        } else if (Objects.equals(bizType, INBOUND_BIZ_TYPE_SCAN_UNQUALIFIED)) {
            wrapper.likeRight(ApproveProcess::getApproveReason, "销售扫码不合格入库审批:").likeRight(ApproveProcess::getApproveRemark, "scanUnqualified:" + salesLedgerId + ":");
        } else {
            return null;
        }
        ApproveProcess latest = approveProcessService.getOne(wrapper);
        return latest == null ? null : latest.getApproveUserIds();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanOutbound(SalesScanInboundDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new ServiceException("销售订单出库失败,出库数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("出库失败,销售订单不存在");
        }
        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
            throw new ServiceException("出库失败,该销售订单已发货");
        }
        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 2) {
            throw new ServiceException("出库失败,该销售订单已发起发货审批,请先完成审批");
        }
        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
            throw new ServiceException("销售订单出库失败,出库产品不能为空");
        }
        String scanShippingNo = OrderUtils.countTodayByCreateTime(shippingInfoMapper, "SCAN");
        int saleType = SaleEnum.SALE.getCode();
        Map<Long, BigDecimal> outboundQtyByLineId = new LinkedHashMap<>();
        for (SalesLedgerProduct line : dto.getSalesLedgerProductList()) {
            if (line == null || line.getId() == null) {
                throw new ServiceException("出库失败,销售产品信息不完整");
            }
            BigDecimal outboundQty = line.getStockedQuantity();
            if (outboundQty == null) {
                throw new ServiceException("出库失败,出库数量不能为空");
            }
            if (outboundQty.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("出库失败,出库数量不能为负数");
            }
            outboundQtyByLineId.merge(line.getId(), outboundQty, BigDecimal::add);
        }
        Long ledgerId = salesLedger.getId();
        for (Map.Entry<Long, BigDecimal> entry : outboundQtyByLineId.entrySet()) {
            Long salesLedgerProductId = entry.getKey();
            BigDecimal outboundThisLine = entry.getValue();
            if (outboundThisLine.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
            if (dbProduct == null) {
                throw new ServiceException("出库失败,销售产品不存在");
            }
            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId) || !Objects.equals(dbProduct.getType(), saleType)) {
                throw new ServiceException("出库失败,销售产品与订单不匹配");
            }
            if (dbProduct.getProductModelId() == null) {
                throw new ServiceException("出库失败,产品规格未维护,无法出库");
            }
            BigDecimal orderQty = defaultDecimal(dbProduct.getQuantity());
            BigDecimal prevShipped = defaultDecimal(dbProduct.getShippedQuantity());
            if (prevShipped.add(outboundThisLine).compareTo(orderQty) > 0) {
                throw new ServiceException("出库失败,本次出库后累计发货数量不能大于该产品订单数量");
            }
            stockUtils.assertQualifiedAvailable(dbProduct.getProductModelId(), outboundThisLine);
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setRecordId(dbProduct.getId());
            stockInventoryDto.setRecordType(StockOutQualifiedRecordTypeEnum.SALE_SCAN_STOCK_OUT.getCode());
            stockInventoryDto.setQualitity(outboundThisLine);
            stockInventoryDto.setProductModelId(dbProduct.getProductModelId());
            stockInventoryDto.setSalesLedgerId(ledgerId);
            stockInventoryDto.setSalesLedgerProductId(dbProduct.getId());
            stockInventoryService.subtractStockInventory(stockInventoryDto);
            BigDecimal oldShipped = dbProduct.getShippedQuantity() == null ? BigDecimal.ZERO : dbProduct.getShippedQuantity();
            dbProduct.setShippedQuantity(oldShipped.add(outboundThisLine));
            dbProduct.fillRemainingQuantity();
            salesLedgerProductMapper.updateById(dbProduct);
        }
        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ledgerId));
        boolean anyInbound = ledgerAllProducts.stream().anyMatch(p -> {
            BigDecimal sq = p.getStockedQuantity();
            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
        });
        boolean allLinesFull = ledgerAllProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
        salesLedger.setStockStatus(allLinesFull ? 2 : (anyInbound ? 1 : 0));
        List<SalesLedgerProduct> saleLines = ledgerAllProducts.stream()
                .filter(p -> Objects.equals(p.getType(), saleType))
                .collect(Collectors.toList());
        boolean allDelivered = !saleLines.isEmpty() && saleLines.stream().allMatch(p -> {
            BigDecimal q = defaultDecimal(p.getQuantity());
            BigDecimal s = defaultDecimal(p.getShippedQuantity());
            return q.compareTo(BigDecimal.ZERO) <= 0 || s.compareTo(q) >= 0;
        });
        if (allDelivered) {
            salesLedger.setDeliveryStatus(5);
        } else {
            boolean anyLineShipped = saleLines.stream()
                    .anyMatch(p -> defaultDecimal(p.getShippedQuantity()).compareTo(BigDecimal.ZERO) > 0);
            if (anyLineShipped) {
                salesLedger.setDeliveryStatus(6);
            }
        }
        baseMapper.updateById(salesLedger);
        syncShippingLedgerAfterQualifiedScan(ledgerId, scanShippingNo);
    }
    /**
     * 扫码合格出库后同步发货台账记录
     */
    private void syncShippingLedgerAfterQualifiedScan(Long ledgerId, String shippingBatchNo) {
        if (shippingBatchNo == null) {
            shippingBatchNo = OrderUtils.countTodayByCreateTime(shippingInfoMapper, "SCAN");
        }
        int saleType = SaleEnum.SALE.getCode();
        List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                Wrappers.<SalesLedgerProduct>lambdaQuery()
                        .eq(SalesLedgerProduct::getSalesLedgerId, ledgerId)
                        .eq(SalesLedgerProduct::getType, saleType));
        Date now = new Date();
        for (SalesLedgerProduct p : products) {
            if (p.getShippedQuantity() == null || p.getShippedQuantity().compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            ShippingInfo row = shippingInfoMapper.selectOne(new LambdaQueryWrapper<ShippingInfo>()
                    .eq(ShippingInfo::getSalesLedgerProductId, p.getId())
                    .orderByDesc(ShippingInfo::getId)
                    .last("LIMIT 1"));
            BigDecimal lineQty = defaultDecimal(p.getQuantity());
            BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
            boolean lineFullyShipped = lineQty.compareTo(BigDecimal.ZERO) <= 0 || shipped.compareTo(lineQty) >= 0;
            String lineShipStatus = lineFullyShipped ? "已发货" : "部分发货";
            if (row == null) {
                ShippingInfo insert = new ShippingInfo();
                insert.setSalesLedgerId(ledgerId);
                insert.setSalesLedgerProductId(p.getId());
                insert.setShippingNo(shippingBatchNo);
                insert.setType("扫码出库");
                insert.setStatus(lineShipStatus);
                insert.setShippingDate(now);
                shippingInfoMapper.insert(insert);
            } else {
                if (!StringUtils.hasText(row.getType())) {
                    row.setType("扫码出库");
                }
                row.setStatus(lineShipStatus);
                row.setShippingDate(now);
                if (!StringUtils.hasText(row.getShippingNo())) {
                    row.setShippingNo(shippingBatchNo);
                }
                shippingInfoMapper.updateById(row);
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanOutboundUnqualified(SalesScanInboundDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new ServiceException("销售订单不合格出库失败,出库数据不能为空");
        }
        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("不合格出库失败,销售订单不存在");
        }
        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
            throw new ServiceException("不合格出库失败,该销售订单已发货");
        }
        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
            throw new ServiceException("销售订单不合格出库失败,出库产品不能为空");
        }
        int saleType = SaleEnum.SALE.getCode();
        Map<Long, BigDecimal> outboundQtyByLineId = new LinkedHashMap<>();
        for (SalesLedgerProduct line : dto.getSalesLedgerProductList()) {
            if (line == null || line.getId() == null) {
                throw new ServiceException("不合格出库失败,销售产品信息不完整");
            }
            BigDecimal outboundQty = line.getStockedQuantity();
            if (outboundQty == null) {
                throw new ServiceException("不合格出库失败,出库数量不能为空");
            }
            if (outboundQty.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("不合格出库失败,出库数量不能为负数");
            }
            outboundQtyByLineId.merge(line.getId(), outboundQty, BigDecimal::add);
        }
        Long ledgerId = salesLedger.getId();
        for (Map.Entry<Long, BigDecimal> entry : outboundQtyByLineId.entrySet()) {
            Long salesLedgerProductId = entry.getKey();
            BigDecimal outboundThisLine = entry.getValue();
            if (outboundThisLine.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(salesLedgerProductId);
            if (dbProduct == null) {
                throw new ServiceException("不合格出库失败,销售产品不存在");
            }
            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId) || !Objects.equals(dbProduct.getType(), saleType)) {
                throw new ServiceException("不合格出库失败,销售产品与订单不匹配");
            }
            if (dbProduct.getProductModelId() == null) {
                throw new ServiceException("不合格出库失败,产品规格未维护,无法出库");
            }
            BigDecimal unStocked = dbProduct.getUnqualifiedStockedQuantity() == null ? BigDecimal.ZERO : dbProduct.getUnqualifiedStockedQuantity();
            BigDecimal unShipped = dbProduct.getUnqualifiedShippedQuantity() == null ? BigDecimal.ZERO : dbProduct.getUnqualifiedShippedQuantity();
            BigDecimal canUnShip = unStocked.subtract(unShipped);
            if (outboundThisLine.compareTo(canUnShip) > 0) {
                throw new ServiceException("不合格出库失败,出库数量不能大于不合格入库数量");
            }
            stockUtils.assertUnqualifiedAvailable(dbProduct.getProductModelId(), outboundThisLine);
            stockUtils.subtractUnStock(ledgerId, dbProduct.getId(), dbProduct.getProductModelId(), outboundThisLine, StockOutUnQualifiedRecordTypeEnum.SALE_SCAN_UNSTOCK_OUT.getCode(), dbProduct.getId());
            dbProduct.setUnqualifiedShippedQuantity(unShipped.add(outboundThisLine));
            dbProduct.fillRemainingQuantity();
            salesLedgerProductMapper.updateById(dbProduct);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shippingImport(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入失败,导入文件数据不能为空");
        }
        List<SalesShippingImportDto> list;
        try {
            ExcelUtil<SalesShippingImportDto> excelUtil = new ExcelUtil<>(SalesShippingImportDto.class);
            list = excelUtil.importExcel(file.getInputStream());
        } catch (Exception e) {
            log.error("销售发货历史数据导入-已发货导入失败: {}", e.getMessage());
            throw new ServiceException("导入失败,数据读取异常");
        }
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("导入失败,文件数据为空");
        }
        Map<String, List<SalesShippingImportDto>> groupedByOrderNo = list.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(SalesShippingImportDto::getOrderNo, LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<SalesShippingImportDto>> entry : groupedByOrderNo.entrySet()) {
            String orderNo = entry.getKey();
            if (!StringUtils.hasText(orderNo)) {
                throw new ServiceException("导入失败,存在订单编号为空的数据");
            }
            List<SalesShippingImportDto> rowList = entry.getValue();
            if (CollectionUtils.isEmpty(rowList)) {
                continue;
            }
            SalesLedger ledger = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
            if (ledger == null) {
                throw new ServiceException("导入失败,订单编号[" + orderNo + "]不存在,无法补录已发货数据");
            }
            List<SalesLedgerProduct> dbProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
            if (CollectionUtils.isEmpty(dbProducts)) {
                throw new ServiceException("导入失败,订单编号[" + orderNo + "]没有销售产品,无法补录发货");
            }
            Map<String, List<SalesLedgerProduct>> productByCategory = dbProducts.stream().collect(Collectors.groupingBy(p -> StringUtils.hasText(p.getProductCategory()) ? p.getProductCategory().trim() : ""));
            Set<String> importedRowKeys = new HashSet<>();
            for (SalesShippingImportDto row : rowList) {
                BigDecimal shipQty = defaultDecimal(row.getQuantity());
                if (shipQty.compareTo(BigDecimal.ZERO) <= 0) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                }
                String rowKey = buildShippingRowKey(ledger.getId(), row);
                if (!importedRowKeys.add(rowKey)) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货明细行");
                }
                Map<SalesLedgerProduct, BigDecimal> allocations = allocateShippingProductLines(orderNo, row, productByCategory, dbProducts);
                for (Map.Entry<SalesLedgerProduct, BigDecimal> alloc : allocations.entrySet()) {
                    SalesLedgerProduct dbProduct = alloc.getKey();
                    BigDecimal allocQty = alloc.getValue();
                    if (dbProduct.getProductModelId() == null) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品规格未维护,无法补录出库");
                    }
                    // 历史已发货补录:直接写入入库+出库记录
                    stockUtils.addStock(
                            ledger.getId(),
                            dbProduct.getId(),
                            dbProduct.getProductModelId(),
                            allocQty,
                            StockInQualifiedRecordTypeEnum.SALE_STOCK_IN.getCode(),
                            dbProduct.getId()
                    );
                    stockUtils.substractStock(
                            ledger.getId(),
                            dbProduct.getId(),
                            dbProduct.getProductModelId(),
                            allocQty,
                            StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(),
                            dbProduct.getId()
                    );
                    BigDecimal oldShipped = defaultDecimal(dbProduct.getShippedQuantity());
                    BigDecimal newShipped = oldShipped.add(allocQty);
                    dbProduct.setStockedQuantity(defaultDecimal(dbProduct.getQuantity()));
                    dbProduct.setShippedQuantity(newShipped);
                    dbProduct.setApproveStatus(3);
                    updateProductStockStatus(dbProduct);
                    dbProduct.fillRemainingQuantity();
                    updateProductShipStatus(dbProduct);
                    salesLedgerProductMapper.updateById(dbProduct);
                    ShippingInfo shippingInfo = new ShippingInfo();
                    shippingInfo.setSalesLedgerId(ledger.getId());
                    shippingInfo.setSalesLedgerProductId(dbProduct.getId());
                    shippingInfo.setStatus("已发货");
                    shippingInfo.setShippingNo(row.getShippingNo());
                    shippingInfo.setType("货车");
                    shippingInfo.setShippingCarNumber("无");
                    shippingInfo.setShippingDate(row.getReportDate());
                    long existedShippingCount = shippingInfoMapper.selectCount(new LambdaQueryWrapper<ShippingInfo>().eq(ShippingInfo::getSalesLedgerId, ledger.getId()).eq(ShippingInfo::getSalesLedgerProductId, dbProduct.getId()).eq(StringUtils.hasText(row.getShippingNo()), ShippingInfo::getShippingNo, row.getShippingNo()).eq(row.getReportDate() != null, ShippingInfo::getShippingDate, row.getReportDate()));
                    if (existedShippingCount > 0) {
                        throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在重复发货记录,请勿重复导入");
                    }
                    shippingInfoMapper.insert(shippingInfo);
                    createShippingQualityInspect(ledger, dbProduct, row, allocQty);
                }
            }
            List<SalesLedgerProduct> latestProducts = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>().eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId()).eq(SalesLedgerProduct::getType, SaleEnum.SALE.getCode()));
            boolean allShipped = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                BigDecimal qty = defaultDecimal(p.getQuantity());
                BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
                return shipped.compareTo(qty) >= 0;
            });
            boolean anyInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().anyMatch(p -> defaultDecimal(p.getStockedQuantity()).compareTo(BigDecimal.ZERO) > 0);
            boolean allInbound = CollectionUtils.isNotEmpty(latestProducts) && latestProducts.stream().allMatch(p -> {
                BigDecimal qty = defaultDecimal(p.getQuantity());
                BigDecimal stocked = defaultDecimal(p.getStockedQuantity());
                return qty.compareTo(BigDecimal.ZERO) <= 0 || stocked.compareTo(qty) >= 0;
            });
            if (allShipped && rowList.get(0).getReportDate() != null) {
                ledger.setDeliveryDate(DateUtils.toLocalDate(rowList.get(0).getReportDate()));
            }
            ledger.setStockStatus(allInbound ? 2 : (anyInbound ? 1 : 0));
            ledger.setDeliveryStatus(allShipped ? 5 : 1);
            salesLedgerMapper.updateById(ledger);
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notShippingImport(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("导入失败,导入文件数据不能为空");
        }
        List<SalesNotShippingImportDto> list;
        try {
            ExcelUtil<SalesNotShippingImportDto> excelUtil = new ExcelUtil<>(SalesNotShippingImportDto.class);
            list = excelUtil.importExcel(file.getInputStream());
        } catch (Exception e) {
            log.error("销售发货历史数据导入-未发货导入失败: {}", e.getMessage());
            throw new ServiceException("导入失败,数据读取异常");
        }
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("导入失败,文件数据为空");
        }
        List<SysUser> allUsers = sysUserMapper.selectList(null);
        Map<String, SysUser> userByNickNameMap = allUsers.stream().filter(Objects::nonNull).filter(u -> StringUtils.hasText(u.getNickName())).collect(Collectors.toMap(SysUser::getNickName, Function.identity(), (a, b) -> a));
        Map<String, SysUser> userByUserNameMap = allUsers.stream().filter(Objects::nonNull).filter(u -> StringUtils.hasText(u.getUserName())).collect(Collectors.toMap(SysUser::getUserName, Function.identity(), (a, b) -> a));
        Map<String, Customer> customerNameMap = customerMapper.selectList(null).stream().filter(Objects::nonNull).filter(c -> StringUtils.hasText(c.getCustomerName())).collect(Collectors.toMap(Customer::getCustomerName, Function.identity(), (a, b) -> a));
        List<CustomerRegions> allRegions = customerRegionsService.list();
        CustomerRegions hebiRegion = allRegions.stream().filter(Objects::nonNull).filter(r -> "鹤壁".equals(r.getRegionsName())).findFirst().orElseGet(() -> {
            CustomerRegions region = new CustomerRegions();
            region.setRegionsName("鹤壁");
            region.setParentId(0L);
            customerRegionsService.save(region);
            return region;
        });
        Map<String, Product> productNameMap = productMapper.selectList(null).stream().filter(Objects::nonNull).filter(p -> StringUtils.hasText(p.getProductName())).collect(Collectors.toMap(Product::getProductName, Function.identity(), (a, b) -> a));
        Product finishedGoodsParent = productNameMap.get("成品");
        if (finishedGoodsParent == null || finishedGoodsParent.getId() == null) {
            finishedGoodsParent = new Product();
            finishedGoodsParent.setProductName("成品");
            finishedGoodsParent.setParentId(null);
            productMapper.insert(finishedGoodsParent);
            productNameMap.put("成品", finishedGoodsParent);
        }
        Map<String, ProductModel> productModelKeyMap = productModelMapper.selectList(null).stream().filter(Objects::nonNull).filter(m -> m.getProductId() != null && StringUtils.hasText(m.getModel())).collect(Collectors.toMap(m -> buildProductModelKey(m.getProductId(), m.getModel()), Function.identity(), (a, b) -> a));
        List<String> extraProcessNames = Arrays.asList("打孔", "挖缺", "安全角", "磨边");
        Map<String, SalesLedgerProductProcess> processMap = salesLedgerProductProcessService.list(new LambdaQueryWrapper<SalesLedgerProductProcess>().in(SalesLedgerProductProcess::getProcessName, extraProcessNames)).stream().filter(Objects::nonNull).filter(p -> StringUtils.hasText(p.getProcessName())).collect(Collectors.toMap(SalesLedgerProductProcess::getProcessName, Function.identity(), (a, b) -> a));
        List<ProcessRoute> processRoutes = processRouteMapper.selectList(new LambdaQueryWrapper<ProcessRoute>().eq(ProcessRoute::getProductModelId, 0L));
        Map<String, ProcessRoute> routeNameMap = processRoutes.stream().filter(Objects::nonNull).filter(r -> StringUtils.hasText(r.getProcessRouteName())).collect(Collectors.toMap(r -> normalizeRouteFlowKey(r.getProcessRouteName()), Function.identity(), this::chooseBetterRoute));
        Map<Long, List<ProcessRouteItem>> routeItemMap = Collections.emptyMap();
        List<Long> routeIds = processRoutes.stream().map(ProcessRoute::getId).filter(Objects::nonNull).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(routeIds)) {
            routeItemMap = processRouteItemMapper.selectList(new LambdaQueryWrapper<ProcessRouteItem>().in(ProcessRouteItem::getRouteId, routeIds).orderByAsc(ProcessRouteItem::getDragSort).orderByAsc(ProcessRouteItem::getId)).stream().filter(Objects::nonNull).collect(Collectors.groupingBy(ProcessRouteItem::getRouteId));
        }
        Map<String, List<SalesNotShippingImportDto>> groupedByOrderNo = list.stream().filter(Objects::nonNull).collect(Collectors.groupingBy(SalesNotShippingImportDto::getOrderNo, LinkedHashMap::new, Collectors.toList()));
        for (Map.Entry<String, List<SalesNotShippingImportDto>> entry : groupedByOrderNo.entrySet()) {
            String orderNo = entry.getKey();
            if (!StringUtils.hasText(orderNo)) {
                throw new ServiceException("导入失败,存在订单编号为空的数据");
            }
            List<SalesNotShippingImportDto> rowList = entry.getValue();
            if (CollectionUtils.isEmpty(rowList)) {
                continue;
            }
            SalesNotShippingImportDto first = rowList.get(0);
            SalesLedger exists = salesLedgerMapper.selectOne(new LambdaQueryWrapper<SalesLedger>().eq(SalesLedger::getSalesContractNo, orderNo).last("LIMIT 1"));
            if (exists != null) {
                throw new ServiceException("导入失败,订单编号[" + orderNo + "]已存在");
            }
            SalesLedger ledger = new SalesLedger();
            SysUser creatorUser = resolveImportUser(first.getCreator(), userByNickNameMap, userByUserNameMap, "制单员", orderNo);
            ledger.setSalesContractNo(orderNo);
            ledger.setCustomerContractNo(first.getContractNo());
            ledger.setProjectName(first.getProjectName());
            ledger.setSalesman(first.getSalesman());
            Customer customer = getOrCreateImportCustomer(first.getCustomerName(), customerNameMap, hebiRegion.getId());
            ledger.setCustomerName(customer.getCustomerName());
            ledger.setRemarks(first.getRemark());
            ledger.setEntryPerson(String.valueOf(creatorUser.getUserId()));
            ledger.setEntryDate(first.getReportDate());
            if (first.getReportDate() != null) {
                ledger.setExecutionDate(DateUtils.toLocalDate(first.getReportDate()));
            }
            ledger.setDeliveryDate(first.getDeliveryDeadline() == null ? (first.getReportDate() == null ? LocalDate.now().plusDays(7) : DateUtils.toLocalDate(first.getReportDate()).plusDays(7)) : DateUtils.toLocalDate(first.getDeliveryDeadline()));
            ledger.setDeliveryStatus(1);
            ledger.setStockStatus(0);
            ledger.setCustomerId(customer.getId());
            ledger.setCustomerContractNo(StringUtils.hasText(ledger.getCustomerContractNo()) ? ledger.getCustomerContractNo() : customer.getTaxpayerIdentificationNumber());
            ledger.setContractAmount(BigDecimal.ZERO);
            salesLedgerMapper.insert(ledger);
            bindImportProcessRoute(ledger.getId(), rowList, routeNameMap, routeItemMap);
            BigDecimal contractAmount = BigDecimal.ZERO;
            for (SalesNotShippingImportDto row : rowList) {
                SalesLedgerProduct product = new SalesLedgerProduct();
                product.setSalesLedgerId(ledger.getId());
                product.setType(SaleEnum.SALE.getCode());
                String specificationModel = buildSpecificationModel(row);
                Product importProduct = resolveOrCreateImportProduct(row, productNameMap, finishedGoodsParent, orderNo);
                ProductModel importProductModel = resolveOrCreateImportProductModel(importProduct, specificationModel, row.getGlassThickness(), productModelKeyMap);
                product.setProductCategory(row.getProductSubCategory());
                product.setSpecificationModel(specificationModel);
                product.setProductId(importProduct.getId());
                product.setProductModelId(importProductModel.getId());
                product.setFloorCode(row.getFloorNo());
                product.setWidth(defaultDecimal(row.getWidth()));
                product.setHeight(defaultDecimal(row.getHeight()));
                product.setQuantity(defaultDecimal(row.getQuantity()));
                product.setActualPieceArea(defaultDecimal(row.getActualSingleArea()));
                product.setActualTotalArea(defaultDecimal(row.getActualTotalArea()));
                product.setSettlePieceArea(defaultDecimal(row.getSettlementSingleArea()));
                product.setSettleTotalArea(defaultDecimal(row.getSettlementTotalArea()));
                product.setTaxInclusiveUnitPrice(defaultDecimal(row.getUnitPrice()));
                product.setPerimeter(defaultDecimal(row.getPerimeter()));
                product.setHeavyBox(defaultDecimal(row.getHeavyBox()));
                product.setProcessRequirement(row.getProcessRequirement());
                product.setRemark(StringUtils.hasText(row.getAuditRemark()) ? row.getAuditRemark() : row.getRemark());
                product.setApproveStatus(0);
                product.setProductStockStatus(0);
                product.setRegister(creatorUser.getNickName());
                product.setRegisterDate(row.getReportDate() == null ? LocalDateTime.now() : LocalDateTime.ofInstant(row.getReportDate().toInstant(), ZoneId.systemDefault()));
                BigDecimal qty = defaultDecimal(product.getQuantity());
                if (qty.compareTo(BigDecimal.ZERO) <= 0) {
                    throw new ServiceException("导入失败,订单编号[" + orderNo + "]存在数量小于等于0的数据");
                }
                BigDecimal lineAmount = defaultDecimal(row.getGlassAmount()).add(defaultDecimal(row.getOtherProcessFee()));
                if (lineAmount.compareTo(BigDecimal.ZERO) <= 0 && product.getTaxInclusiveUnitPrice().compareTo(BigDecimal.ZERO) > 0 && product.getSettleTotalArea().compareTo(BigDecimal.ZERO) > 0) {
                    lineAmount = product.getTaxInclusiveUnitPrice().multiply(product.getSettleTotalArea()).setScale(2, RoundingMode.HALF_UP);
                }
                product.setTaxRate(BigDecimal.ZERO);
                product.setTaxInclusiveTotalPrice(lineAmount);
                product.setTaxExclusiveTotalPrice(lineAmount);
                product.setNoInvoiceNum(qty);
                product.setNoInvoiceAmount(lineAmount);
                product.setPendingInvoiceTotal(lineAmount);
                product.fillRemainingQuantity();
                salesLedgerProductMapper.insert(product);
                List<SalesLedgerProductProcess> bindProcessList = buildImportProcessBinds(row, processMap);
                if (CollectionUtils.isNotEmpty(bindProcessList)) {
                    salesLedgerProductProcessBindService.updateProductProcessBind(bindProcessList, product.getId());
                }
                salesLedgerProductServiceImpl.addProductionData(product);
                contractAmount = contractAmount.add(lineAmount);
            }
            ledger.setContractAmount(contractAmount);
            salesLedgerMapper.updateById(ledger);
        }
    }
    private List<SalesLedgerProductProcess> buildImportProcessBinds(SalesNotShippingImportDto row, Map<String, SalesLedgerProductProcess> processMap) {
        LinkedHashMap<String, Integer> processQuantityMap = new LinkedHashMap<>();
        mergeProcessQuantity(processQuantityMap, "打孔", toProcessQuantity(row.getDrilling()));
        mergeProcessQuantity(processQuantityMap, "挖缺", toProcessQuantity(row.getNotching()));
        mergeProcessQuantity(processQuantityMap, "安全角", toProcessQuantity(row.getSafetyCorner()));
        mergeProcessQuantity(processQuantityMap, "磨边", toProcessQuantity(row.getGrindingIrregular()));
        List<SalesLedgerProductProcess> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : processQuantityMap.entrySet()) {
            if (entry.getValue() == null || entry.getValue() <= 0) {
                continue;
            }
            SalesLedgerProductProcess process = processMap.get(entry.getKey());
            if (process == null || process.getId() == null) {
                log.warn("导入工艺未找到配置, processName={}, orderNo={}", entry.getKey(), row.getOrderNo());
                continue;
            }
            SalesLedgerProductProcess bind = new SalesLedgerProductProcess();
            bind.setId(process.getId());
            bind.setQuantity(entry.getValue());
            result.add(bind);
        }
        return result;
    }
    private void bindImportProcessRoute(Long salesLedgerId, List<SalesNotShippingImportDto> rowList, Map<String, ProcessRoute> routeNameMap, Map<Long, List<ProcessRouteItem>> routeItemMap) {
        String flowKey = rowList.stream().map(SalesNotShippingImportDto::getProcessFlow).filter(StringUtils::hasText).map(this::normalizeRouteFlowKey).filter(StringUtils::hasText).findFirst().orElse("");
        if (!StringUtils.hasText(flowKey)) {
            throw new ServiceException("导入失败,订单工艺流程不能为空");
        }
        ProcessRoute route = routeNameMap.get(flowKey);
        if (route == null || route.getId() == null) {
            route = createImportProcessRoute(flowKey, routeNameMap, routeItemMap);
        }
        List<ProcessRouteItem> routeItems = routeItemMap.getOrDefault(route.getId(), Collections.emptyList());
        if (CollectionUtils.isEmpty(routeItems)) {
            route = createImportProcessRoute(flowKey, routeNameMap, routeItemMap);
            routeItems = routeItemMap.getOrDefault(route.getId(), Collections.emptyList());
            if (CollectionUtils.isEmpty(routeItems)) {
                throw new ServiceException("导入失败,工艺路线[" + flowKey + "]未配置工艺节点");
            }
        }
        List<SalesLedgerProcessRoute> bindList = new ArrayList<>();
        for (ProcessRouteItem item : routeItems) {
            SalesLedgerProcessRoute bind = new SalesLedgerProcessRoute();
            bind.setSalesLedgerId(salesLedgerId);
            bind.setProcessRouteId(route.getId());
            bind.setProcessRouteItemId(item.getId());
            bind.setDragSort(item.getDragSort());
            bindList.add(bind);
        }
        salesLedgerProcessRouteService.saveBatch(bindList);
    }
    private ProcessRoute createImportProcessRoute(String flowKey, Map<String, ProcessRoute> routeNameMap, Map<Long, List<ProcessRouteItem>> routeItemMap) {
        List<String> processNames = Arrays.stream(flowKey.split("->")).filter(StringUtils::hasText).map(String::trim).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(processNames)) {
            throw new ServiceException("导入失败,工艺路线[" + flowKey + "]解析失败");
        }
        ProcessRoute route = new ProcessRoute();
        route.setProductModelId(0L);
        route.setProcessRouteName(flowKey);
        route.setIsDefault(0);
        route.setDescription("");
        route.setProcessRouteCode("AUTO_" + System.currentTimeMillis());
        processRouteMapper.insert(route);
        List<ProcessRouteItem> routeItems = new ArrayList<>();
        for (int i = 0; i < processNames.size(); i++) {
            ProcessRouteItem item = new ProcessRouteItem();
            item.setRouteId(route.getId());
            item.setProductModelId(0L);
            item.setProcessId(0L);
            item.setProcessName(processNames.get(i));
            item.setDragSort(i + 1);
            item.setIsQuality(Boolean.TRUE);
            processRouteItemMapper.insert(item);
            routeItems.add(item);
        }
        routeNameMap.put(flowKey, route);
        routeItemMap.put(route.getId(), routeItems);
        return route;
    }
    private void mergeProcessQuantity(Map<String, Integer> processQuantityMap, String processName, Integer quantity) {
        if (!StringUtils.hasText(processName) || quantity == null || quantity <= 0) {
            return;
        }
        Integer old = processQuantityMap.get(processName);
        if (old == null || old <= 0) {
            processQuantityMap.put(processName, quantity);
        }
    }
    private String normalizeRouteFlowKey(String processFlow) {
        if (!StringUtils.hasText(processFlow)) {
            return "";
        }
        return Arrays.stream(processFlow.trim().split("\\s*(?:->|→|=>|>)\\s*")).filter(StringUtils::hasText).map(String::trim).collect(Collectors.joining("->"));
    }
    private ProcessRoute chooseBetterRoute(ProcessRoute a, ProcessRoute b) {
        if (a == null) {
            return b;
        }
        if (b == null) {
            return a;
        }
        boolean aDefault = Objects.equals(a.getIsDefault(), 1);
        boolean bDefault = Objects.equals(b.getIsDefault(), 1);
        if (aDefault != bDefault) {
            return aDefault ? a : b;
        }
        LocalDateTime aTime = a.getCreateTime();
        LocalDateTime bTime = b.getCreateTime();
        if (aTime == null) {
            return b;
        }
        if (bTime == null) {
            return a;
        }
        return bTime.isAfter(aTime) ? b : a;
    }
    private Integer toProcessQuantity(BigDecimal value) {
        if (value == null) {
            return null;
        }
        if (value.compareTo(BigDecimal.ZERO) <= 0) {
            return 0;
        }
        return value.setScale(0, RoundingMode.HALF_UP).intValue();
    }
    private SysUser resolveImportUser(String rawName, Map<String, SysUser> userByNickNameMap, Map<String, SysUser> userByUserNameMap, String fieldName, String orderNo) {
        if (!StringUtils.hasText(rawName)) {
            throw new ServiceException("导入失败,订单编号[" + orderNo + "]的[" + fieldName + "]不能为空");
        }
        String key = rawName.trim();
        SysUser user = userByNickNameMap.get(key);
        if (user == null) {
            user = userByUserNameMap.get(key);
        }
        if (user == null || user.getUserId() == null) {
            throw new ServiceException("导入失败,订单编号[" + orderNo + "]的[" + fieldName + ":" + key + "]未匹配到人员");
        }
        return user;
    }
    private Customer getOrCreateImportCustomer(String customerName, Map<String, Customer> customerNameMap, Long hebiRegionId) {
        if (!StringUtils.hasText(customerName)) {
            throw new ServiceException("导入失败,客户名称不能为空");
        }
        String key = customerName.trim();
        Customer exists = customerNameMap.get(key);
        if (exists != null && exists.getId() != null) {
            return exists;
        }
        Customer customer = new Customer();
        customer.setCustomerName(key);
        customer.setRegionsId(hebiRegionId);
        customerMapper.insert(customer);
        customerNameMap.put(key, customer);
        return customer;
    }
    private Product resolveOrCreateImportProduct(SalesNotShippingImportDto row, Map<String, Product> productNameMap, Product finishedGoodsParent, String orderNo) {
        String productName = row.getProductName();
        if (StringUtils.hasText(productName)) {
            Product product = productNameMap.get(productName.trim());
            if (product != null && product.getId() != null) {
                return product;
            }
        }
        String productSubCategory = row.getProductSubCategory();
        if (StringUtils.hasText(productSubCategory)) {
            Product product = productNameMap.get(productSubCategory.trim());
            if (product != null && product.getId() != null) {
                return product;
            }
        }
        String newProductName = buildCategoryProductName(row);
        if (!StringUtils.hasText(newProductName)) {
            throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品名称和产品分类均为空");
        }
        Product created = new Product();
        created.setParentId(finishedGoodsParent == null ? null : finishedGoodsParent.getId());
        created.setProductName(newProductName);
        productMapper.insert(created);
        productNameMap.put(newProductName, created);
        return created;
    }
    private ProductModel resolveOrCreateImportProductModel(Product product, String modelName, BigDecimal thickness, Map<String, ProductModel> productModelKeyMap) {
        if (product == null || product.getId() == null || !StringUtils.hasText(modelName)) {
            throw new ServiceException("导入失败,产品规格数据不完整");
        }
        String key = buildProductModelKey(product.getId(), modelName);
        ProductModel exists = productModelKeyMap.get(key);
        if (exists != null && exists.getId() != null) {
            return exists;
        }
        ProductModel created = new ProductModel();
        created.setProductId(product.getId());
        created.setModel(modelName.trim());
        created.setThickness(thickness);
        productModelMapper.insert(created);
        productModelKeyMap.put(key, created);
        return created;
    }
    private String buildSpecificationModel(SalesNotShippingImportDto row) {
        if (StringUtils.hasText(row.getProductName())) {
            return row.getProductName().trim();
        }
        if (StringUtils.hasText(row.getProductSubCategory())) {
            return row.getProductSubCategory().trim();
        }
        if (StringUtils.hasText(row.getProductCategory())) {
            return row.getProductCategory().trim();
        }
        return "";
    }
    private String buildCategoryProductName(SalesNotShippingImportDto row) {
        String category = row.getProductCategory();
        String subCategory = row.getProductSubCategory();
        if (StringUtils.hasText(category) && StringUtils.hasText(subCategory)) {
            return category.trim() + "-" + subCategory.trim();
        }
        if (StringUtils.hasText(subCategory)) {
            return subCategory.trim();
        }
        if (StringUtils.hasText(category)) {
            return category.trim();
        }
        return "";
    }
    private String buildProductModelKey(Long productId, String modelName) {
        return productId + "||" + modelName.trim();
    }
    private String buildCategoryProductName(SalesShippingImportDto row) {
        String category = row.getProductCategory();
        String subCategory = row.getProductSubCategory();
        if (StringUtils.hasText(category) && StringUtils.hasText(subCategory)) {
            return category.trim() + "-" + subCategory.trim();
        }
        if (StringUtils.hasText(subCategory)) {
            return subCategory.trim();
        }
        if (StringUtils.hasText(category)) {
            return category.trim();
        }
        return "";
    }
    private Integer parseInteger(String value) {
        if (!StringUtils.hasText(value)) {
            return 0;
        }
        try {
            return new BigDecimal(value.trim()).setScale(0, RoundingMode.HALF_UP).intValue();
        } catch (Exception e) {
            return 0;
        }
    }
    private Map<SalesLedgerProduct, BigDecimal> allocateShippingProductLines(String orderNo, SalesShippingImportDto row, Map<String, List<SalesLedgerProduct>> productByCategory, List<SalesLedgerProduct> allProducts) {
        String subCategory = StringUtils.hasText(row.getProductSubCategory()) ? row.getProductSubCategory().trim() : "";
        List<SalesLedgerProduct> candidates = productByCategory.getOrDefault(subCategory, Collections.emptyList());
        if (CollectionUtils.isEmpty(candidates)) {
            candidates = allProducts;
        }
        BigDecimal remaining = defaultDecimal(row.getQuantity());
        Map<SalesLedgerProduct, BigDecimal> allocations = new LinkedHashMap<>();
        for (SalesLedgerProduct p : candidates) {
            BigDecimal qty = defaultDecimal(p.getQuantity());
            BigDecimal shipped = defaultDecimal(p.getShippedQuantity());
            BigDecimal canShip = qty.subtract(shipped);
            if (canShip.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            BigDecimal alloc = remaining.min(canShip);
            if (alloc.compareTo(BigDecimal.ZERO) > 0) {
                allocations.put(p, alloc);
                remaining = remaining.subtract(alloc);
            }
            if (remaining.compareTo(BigDecimal.ZERO) <= 0) {
                return allocations;
            }
        }
        if (remaining.compareTo(BigDecimal.ZERO) > 0) {
            throw new ServiceException("导入失败,订单编号[" + orderNo + "]产品[" + subCategory + "]发货数量超出剩余可发数量");
        }
        return allocations;
    }
    private void updateProductShipStatus(SalesLedgerProduct dbProduct) {
        BigDecimal qty = defaultDecimal(dbProduct.getQuantity());
        BigDecimal shipped = defaultDecimal(dbProduct.getShippedQuantity());
        if (shipped.compareTo(BigDecimal.ZERO) <= 0) {
            dbProduct.setProductStockStatus(0);
            return;
        }
        dbProduct.setProductStockStatus(shipped.compareTo(qty) >= 0 ? 2 : 1);
    }
    private void updateProductStockStatus(SalesLedgerProduct dbProduct) {
        BigDecimal qty = defaultDecimal(dbProduct.getQuantity());
        BigDecimal stocked = defaultDecimal(dbProduct.getStockedQuantity());
        if (stocked.compareTo(BigDecimal.ZERO) <= 0) {
            dbProduct.setProductStockStatus(0);
            return;
        }
        dbProduct.setProductStockStatus(stocked.compareTo(qty) >= 0 ? 2 : 1);
    }
    private String buildShippingRowKey(Long ledgerId, SalesShippingImportDto row) {
        String shippingNo = StringUtils.hasText(row.getShippingNo()) ? row.getShippingNo().trim() : "";
        String dateStr = row.getReportDate() == null ? "" : String.valueOf(row.getReportDate().getTime());
        String subCategory = StringUtils.hasText(row.getProductSubCategory()) ? row.getProductSubCategory().trim() : "";
        return ledgerId + "|" + subCategory + "|" + shippingNo + "|" + dateStr + "|" + defaultDecimal(row.getQuantity());
    }
    private void createShippingQualityInspect(SalesLedger ledger, SalesLedgerProduct dbProduct, SalesShippingImportDto row, BigDecimal inspectQty) {
        if (ledger == null || dbProduct == null || inspectQty == null || inspectQty.compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        Date checkDate = row.getReportDate() != null ? row.getReportDate() : new Date();
        QualityInspect qualityInspect = new QualityInspect();
        qualityInspect.setInspectType(2);
        qualityInspect.setCheckTime(checkDate);
        qualityInspect.setCustomer(StringUtils.hasText(ledger.getCustomerName()) ? ledger.getCustomerName() : row.getCustomerName());
        qualityInspect.setCheckName(StringUtils.hasText(row.getCreator()) ? row.getCreator().trim() : null);
        qualityInspect.setProductId(dbProduct.getProductId());
        qualityInspect.setProductName(dbProduct.getProductCategory());
        qualityInspect.setModel(dbProduct.getSpecificationModel());
        qualityInspect.setUnit(resolveInspectUnit(dbProduct));
        qualityInspect.setQuantity(inspectQty);
        qualityInspect.setQualifiedQuantity(inspectQty);
        qualityInspect.setUnqualifiedQuantity(BigDecimal.ZERO);
        qualityInspect.setPassRate(BigDecimal.valueOf(100));
        qualityInspect.setCheckResult("合格");
        qualityInspect.setInspectState(1);
        qualityInspect.setApprovalStatus(1);
        qualityInspect.setProductModelId(dbProduct.getProductModelId());
        QualityTestStandard selectedStandard = null;
        if (dbProduct.getProductId() != null) {
            List<QualityTestStandard> standards = qualityTestStandardMapper.getQualityTestStandardByProductId(dbProduct.getProductId(), 2, null);
            if (CollectionUtils.isNotEmpty(standards)) {
                selectedStandard = standards.get(0);
                qualityInspect.setTestStandardId(selectedStandard.getId());
            }
        }
        qualityInspectMapper.insert(qualityInspect);
        if (selectedStandard == null || selectedStandard.getId() == null) {
            return;
        }
        List<QualityTestStandardParam> standardParams = qualityTestStandardParamMapper.selectList(Wrappers.<QualityTestStandardParam>lambdaQuery().eq(QualityTestStandardParam::getTestStandardId, selectedStandard.getId()));
        if (CollectionUtils.isEmpty(standardParams)) {
            return;
        }
        List<QualityInspectParam> inspectParams = standardParams.stream().map(item -> {
            QualityInspectParam param = new QualityInspectParam();
            param.setInspectId(qualityInspect.getId());
            param.setParameterItem(item.getParameterItem());
            param.setUnit(item.getUnit());
            param.setStandardValue(item.getStandardValue());
            param.setControlValue(item.getControlValue());
            param.setTestValue("无瑕疵");
            return param;
        }).collect(Collectors.toList());
        inspectParams.forEach(qualityInspectParamMapper::insert);
    }
    private String resolveInspectUnit(SalesLedgerProduct dbProduct) {
        if (dbProduct == null) {
            return null;
        }
        if (StringUtils.hasText(dbProduct.getUnit())) {
            return dbProduct.getUnit();
        }
        if (dbProduct.getProductModelId() == null) {
            return null;
        }
        ProductModel productModel = productModelMapper.selectById(dbProduct.getProductModelId());
        if (productModel == null || !StringUtils.hasText(productModel.getUnit())) {
            return null;
        }
        return productModel.getUnit();
    }
    private static final String SCAN_SHIP_REMARK_PREFIX = "SCAN_SHIP_DELIVERY_JSON:";
    private static final class ScanShipPayload {
        private String shippingNo;
        private Long ledgerId;
        private String car;
        private String express;
        private String shipType;
        private Map<Long, BigDecimal> linesQty = new LinkedHashMap<>();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void scanShipApply(SalesScanShipDto dto) {
        if (dto == null || dto.getSalesLedgerId() == null) {
            throw new ServiceException("扫码发货失败,订单不能为空");
        }
        if (StringUtils.isEmpty(dto.getApproveUserIds())) {
            throw new ServiceException("请选择审批人");
        }
        if (CollectionUtils.isEmpty(dto.getSalesLedgerProductList())) {
            throw new ServiceException("请填写发货产品行");
        }
        String shipType = StringUtils.hasText(dto.getShipType()) ? dto.getShipType().trim() : "货车";
        if ("货车".equals(shipType)) {
            if (!StringUtils.hasText(dto.getShippingCarNumber())) {
                throw new ServiceException("请填写车牌号");
            }
        } else if ("快递".equals(shipType)) {
            if (!StringUtils.hasText(dto.getExpressNumber())) {
                throw new ServiceException("请填写快递单号");
            }
        }
        SalesLedger salesLedger = baseMapper.selectById(dto.getSalesLedgerId());
        if (salesLedger == null) {
            throw new ServiceException("销售订单不存在");
        }
        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 5) {
            throw new ServiceException("该销售订单已发货");
        }
        if (salesLedger.getDeliveryStatus() != null && salesLedger.getDeliveryStatus() == 2) {
            throw new ServiceException("该销售订单已发起发货审批,请先完成审批");
        }
        List<SalesLedgerProduct> notStocked = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>()
                .eq(SalesLedgerProduct::getSalesLedgerId, salesLedger.getId())
                .eq(SalesLedgerProduct::getType, 1)
                .ne(SalesLedgerProduct::getProductStockStatus, 2));
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(notStocked)) {
            throw new ServiceException("发货失败,该销售订单存在未入库产品,请先完成全部入库后再发货");
        }
        int saleType = SaleEnum.SALE.getCode();
        Map<Long, BigDecimal> shipQtyByLineId = new LinkedHashMap<>();
        for (SalesLedgerProduct line : dto.getSalesLedgerProductList()) {
            if (line == null || line.getId() == null) {
                throw new ServiceException("产品信息不完整");
            }
            BigDecimal q = line.getStockedQuantity();
            if (q == null) {
                throw new ServiceException("发货数量不能为空");
            }
            if (q.compareTo(BigDecimal.ZERO) < 0) {
                throw new ServiceException("发货数量不能为负数");
            }
            shipQtyByLineId.merge(line.getId(), q, BigDecimal::add);
        }
        boolean anyPositive = shipQtyByLineId.values().stream().anyMatch(v -> v.compareTo(BigDecimal.ZERO) > 0);
        if (!anyPositive) {
            throw new ServiceException("请至少填写一行大于 0 的发货数量");
        }
        Long ledgerId = salesLedger.getId();
        for (Map.Entry<Long, BigDecimal> entry : shipQtyByLineId.entrySet()) {
            if (entry.getValue().compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(entry.getKey());
            if (dbProduct == null) {
                throw new ServiceException("销售产品不存在");
            }
            if (!Objects.equals(dbProduct.getSalesLedgerId(), ledgerId) || !Objects.equals(dbProduct.getType(), saleType)) {
                throw new ServiceException("销售产品与订单不匹配");
            }
            if (dbProduct.getProductModelId() == null) {
                throw new ServiceException("产品规格未维护,无法发货");
            }
            BigDecimal orderQty = defaultDecimal(dbProduct.getQuantity());
            BigDecimal prevShipped = defaultDecimal(dbProduct.getShippedQuantity());
            if (prevShipped.add(entry.getValue()).compareTo(orderQty) > 0) {
                throw new ServiceException("累计发货数量不能大于该产品订单数量");
            }
            stockUtils.assertQualifiedAvailable(dbProduct.getProductModelId(), entry.getValue());
        }
        String shNo = OrderUtils.countTodayByCreateTime(shippingInfoMapper, "SH");
        Map<Long, BigDecimal> positiveLines = new LinkedHashMap<>();
        for (Map.Entry<Long, BigDecimal> e : shipQtyByLineId.entrySet()) {
            if (e.getValue().compareTo(BigDecimal.ZERO) > 0) {
                positiveLines.put(e.getKey(), e.getValue());
            }
        }
        for (Map.Entry<Long, BigDecimal> e : positiveLines.entrySet()) {
            ShippingInfo si = new ShippingInfo();
            si.setSalesLedgerId(ledgerId);
            si.setSalesLedgerProductId(e.getKey());
            si.setShippingNo(shNo);
            si.setStatus("待审核");
            si.setType(shipType);
            if ("货车".equals(shipType)) {
                si.setShippingCarNumber(dto.getShippingCarNumber().trim());
            }
            if ("快递".equals(shipType)) {
                si.setExpressNumber(dto.getExpressNumber().trim());
            }
            shippingInfoMapper.insert(si);
        }
        String remarkJson = buildScanShipRemarkJson(shNo, ledgerId, dto, positiveLines);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ApproveProcessVO approveProcessVO = new ApproveProcessVO();
        approveProcessVO.setApproveType(7);
        approveProcessVO.setApproveDeptId(loginUser.getCurrentDeptId());
        approveProcessVO.setApproveReason("发货审批:" + salesLedger.getSalesContractNo());
        approveProcessVO.setApproveRemark(remarkJson);
        approveProcessVO.setApproveUserIds(dto.getApproveUserIds().trim());
        approveProcessVO.setApproveUser(loginUser.getUserId());
        approveProcessVO.setApproveTime(LocalDate.now().toString());
        approveProcessVO.setTempFileIds(dto.getTempFileIds());
        try {
            approveProcessService.addApprove(approveProcessVO);
        } catch (Exception e) {
            throw new ServiceException("发起发货审批失败: " + e.getMessage());
        }
        salesLedger.setDeliveryStatus(2);
        baseMapper.updateById(salesLedger);
    }
    private String buildScanShipRemarkJson(String shippingNo, Long ledgerId, SalesScanShipDto dto, Map<Long, BigDecimal> lines) {
        try {
            ObjectMapper om = new ObjectMapper();
            ObjectNode root = om.createObjectNode();
            root.put("shippingNo", shippingNo);
            root.put("ledgerId", ledgerId);
            root.put("car", dto.getShippingCarNumber() == null ? "" : dto.getShippingCarNumber().trim());
            root.put("express", dto.getExpressNumber() == null ? "" : dto.getExpressNumber().trim());
            root.put("shipType", dto.getShipType() == null ? "货车" : dto.getShipType().trim());
            ObjectNode linesNode = om.createObjectNode();
            for (Map.Entry<Long, BigDecimal> e : lines.entrySet()) {
                linesNode.put(String.valueOf(e.getKey()), e.getValue().stripTrailingZeros().toPlainString());
            }
            root.set("lines", linesNode);
            return SCAN_SHIP_REMARK_PREFIX + om.writeValueAsString(root);
        } catch (Exception e) {
            throw new ServiceException("构建发货审批参数失败");
        }
    }
    private ScanShipPayload parseScanShipPayload(String remark) {
        if (!StringUtils.hasText(remark) || !remark.startsWith(SCAN_SHIP_REMARK_PREFIX)) {
            return null;
        }
        try {
            String json = remark.substring(SCAN_SHIP_REMARK_PREFIX.length());
            ObjectMapper om = new ObjectMapper();
            JsonNode n = om.readTree(json);
            ScanShipPayload p = new ScanShipPayload();
            p.shippingNo = n.path("shippingNo").asText(null);
            p.ledgerId = n.path("ledgerId").asLong(0L);
            p.car = n.path("car").asText("");
            p.express = n.path("express").asText("");
            p.shipType = n.path("shipType").asText("货车");
            JsonNode lines = n.path("lines");
            p.linesQty = new LinkedHashMap<>();
            if (lines.isObject()) {
                Iterator<String> it = lines.fieldNames();
                while (it.hasNext()) {
                    String k = it.next();
                    p.linesQty.put(Long.valueOf(k), new BigDecimal(lines.get(k).asText()));
                }
            }
            return p;
        } catch (Exception e) {
            log.warn("解析扫码发货审批备注失败: {}", e.getMessage());
            return null;
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onScanShipDeliveryApproveOutcome(ApproveProcess approveProcess, Integer outcomeStatus) {
        if (approveProcess == null) {
            return;
        }
        ScanShipPayload ctx = parseScanShipPayload(approveProcess.getApproveRemark());
        if (ctx == null || ctx.ledgerId == null || ctx.ledgerId <= 0 || !StringUtils.hasText(ctx.shippingNo)) {
            return;
        }
        if (outcomeStatus != null && outcomeStatus == 2) {
            executeScanShipDeliveryApproved(approveProcess, ctx);
        } else if (outcomeStatus != null && outcomeStatus == 3) {
            updateScanShipBatchShippingStatus(ctx.ledgerId, ctx.shippingNo, "审核拒绝");
            SalesLedger sl = baseMapper.selectById(ctx.ledgerId);
            if (sl != null) {
                sl.setDeliveryStatus(3);
                baseMapper.updateById(sl);
            }
        } else if (outcomeStatus != null && outcomeStatus == 1) {
            updateScanShipBatchShippingStatus(ctx.ledgerId, ctx.shippingNo, "审核中");
        }
    }
    private void updateScanShipBatchShippingStatus(Long ledgerId, String shippingNo, String statusText) {
        if (ledgerId == null || !StringUtils.hasText(shippingNo)) {
            return;
        }
        shippingInfoMapper.update(null, new UpdateWrapper<ShippingInfo>().lambda()
                .set(ShippingInfo::getStatus, statusText)
                .eq(ShippingInfo::getSalesLedgerId, ledgerId)
                .eq(ShippingInfo::getShippingNo, shippingNo));
    }
    private void executeScanShipDeliveryApproved(ApproveProcess approveProcess, ScanShipPayload ctx) {
        int saleType = SaleEnum.SALE.getCode();
        Date now = new Date();
        List<ShippingInfo> batch = shippingInfoMapper.selectList(Wrappers.<ShippingInfo>lambdaQuery()
                .eq(ShippingInfo::getSalesLedgerId, ctx.ledgerId)
                .eq(ShippingInfo::getShippingNo, ctx.shippingNo));
        if (CollectionUtils.isEmpty(batch)) {
            log.warn("扫码发货审批通过但未找到发货台账 batch ledgerId={} shippingNo={}", ctx.ledgerId, ctx.shippingNo);
            return;
        }
        for (Map.Entry<Long, BigDecimal> entry : ctx.linesQty.entrySet()) {
            Long productLineId = entry.getKey();
            BigDecimal shipQty = entry.getValue();
            if (shipQty == null || shipQty.compareTo(BigDecimal.ZERO) <= 0) {
                continue;
            }
            SalesLedgerProduct dbProduct = salesLedgerProductMapper.selectById(productLineId);
            if (dbProduct == null) {
                throw new ServiceException("销售产品不存在");
            }
            ShippingInfo row = batch.stream()
                    .filter(si -> Objects.equals(si.getSalesLedgerProductId(), productLineId))
                    .findFirst()
                    .orElse(null);
            if (row == null) {
                throw new ServiceException("未找到对应发货台账行");
            }
            if (!"已发货".equals(row.getStatus())) {
                stockUtils.substractStock(ctx.ledgerId, productLineId, dbProduct.getProductModelId(), shipQty,
                        StockOutQualifiedRecordTypeEnum.SALE_SHIP_STOCK_OUT.getCode(), row.getId());
                BigDecimal oldShipped = defaultDecimal(dbProduct.getShippedQuantity());
                dbProduct.setShippedQuantity(oldShipped.add(shipQty));
                dbProduct.fillRemainingQuantity();
                salesLedgerProductMapper.updateById(dbProduct);
            }
            row.setStatus("已发货");
            row.setShippingDate(now);
            if (StringUtils.hasText(ctx.car)) {
                row.setShippingCarNumber(ctx.car.trim());
            }
            if (StringUtils.hasText(ctx.express)) {
                row.setExpressNumber(ctx.express.trim());
            }
            if (StringUtils.hasText(ctx.shipType)) {
                row.setType(ctx.shipType.trim());
            }
            shippingInfoMapper.updateById(row);
        }
        List<Long> shippingIds = batch.stream().map(ShippingInfo::getId).filter(Objects::nonNull).collect(Collectors.toList());
        commonFileService.copyApproveProcessShipAttachmentsToShippingInfos(approveProcess.getId(), shippingIds);
        List<SalesLedgerProduct> ledgerAllProducts = salesLedgerProductMapper.selectList(
                Wrappers.<SalesLedgerProduct>lambdaQuery().eq(SalesLedgerProduct::getSalesLedgerId, ctx.ledgerId));
        SalesLedger salesLedger = baseMapper.selectById(ctx.ledgerId);
        if (salesLedger == null) {
            return;
        }
        boolean anyInbound = ledgerAllProducts.stream().anyMatch(p -> {
            BigDecimal sq = p.getStockedQuantity();
            return sq != null && sq.compareTo(BigDecimal.ZERO) > 0;
        });
        boolean allLinesFull = ledgerAllProducts.stream().allMatch(p -> Objects.equals(p.getProductStockStatus(), 2));
        salesLedger.setStockStatus(allLinesFull ? 2 : (anyInbound ? 1 : 0));
        List<SalesLedgerProduct> saleLines = ledgerAllProducts.stream()
                .filter(p -> Objects.equals(p.getType(), saleType))
                .collect(Collectors.toList());
        boolean allDelivered = !saleLines.isEmpty() && saleLines.stream().allMatch(p -> {
            BigDecimal q = defaultDecimal(p.getQuantity());
            BigDecimal s = defaultDecimal(p.getShippedQuantity());
            return q.compareTo(BigDecimal.ZERO) <= 0 || s.compareTo(q) >= 0;
        });
        if (allDelivered) {
            salesLedger.setDeliveryStatus(5);
        } else {
            boolean anyLineShipped = saleLines.stream()
                    .anyMatch(p -> defaultDecimal(p.getShippedQuantity()).compareTo(BigDecimal.ZERO) > 0);
            if (anyLineShipped) {
                salesLedger.setDeliveryStatus(6);
            }
        }
        baseMapper.updateById(salesLedger);
    }
    /**
     * 处理销售台账反审逻辑
     * 1. 设置反审相关信息(时间、人员)
     * 2. 复制原销售台账及产品数据,生成新的台账
     * 3. 对原台账的库存数据进行反向操作
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Long> counterReview(CounterReviewDto dto) {
        if (dto == null || CollectionUtils.isEmpty(dto.getIds())) {
            throw new ServiceException("请选择要反审核的订单");
        }
        if (dto.getCounterReviewType() == null || (dto.getCounterReviewType() != 1 && dto.getCounterReviewType() != 2)) {
            throw new ServiceException("请选择反审核类型:作废或重新生成");
        }
        if (dto.getCounterReviewDesc() == null || dto.getCounterReviewDesc().trim().isEmpty()) {
            throw new ServiceException("请输入反审核描述");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<Long> newLedgerIds = new ArrayList<>();
        for (Long id : dto.getIds()) {
            SalesLedger originalLedger = salesLedgerMapper.selectById(id);
            if (originalLedger == null) {
                throw new ServiceException("订单不存在,无法反审核");
            }
            if (originalLedger.getReviewStatus() == null || originalLedger.getReviewStatus() != 1) {
                throw new ServiceException("订单" + originalLedger.getSalesContractNo() + "不是已审核状态,无法反审核");
            }
            // 1. 标记原订单为已反审
            originalLedger.setReviewStatus(2);
            originalLedger.setCounterReviewTime(LocalDateTime.now());
            originalLedger.setCounterReviewPerson(loginUser.getUser().getNickName());
            originalLedger.setCounterReviewPersonId(loginUser.getUserId());
            originalLedger.setCounterReviewType(dto.getCounterReviewType());
            originalLedger.setCounterReviewDesc(dto.getCounterReviewDesc());
            salesLedgerMapper.updateById(originalLedger);
            // 2. 作废库存:入库扣减、出库增加、删除记录
            processOriginalOrderStock(id);
            // 3. 清除质检记录
            clearQualityInspectRecords(id);
            // 4. 清除发货信息和发货审批记录
            clearShippingAndApprovalRecords(id);
            // 5. 取消审批流程
            cancelApproveProcesses(id, originalLedger.getSalesContractNo());
            // 6. 重新生成:创建新台账副本
            if (dto.getCounterReviewType() == 2) {
                SalesLedger newLedger = new SalesLedger();
                BeanUtils.copyProperties(originalLedger, newLedger);
                newLedger.setId(null);
                newLedger.setSalesContractNo(generateSalesContractNo());
                newLedger.setDeliveryStatus(1);
                newLedger.setStockStatus(0);
                newLedger.setReviewStatus(0);
                newLedger.setCounterReviewTime(null);
                newLedger.setCounterReviewPerson(null);
                newLedger.setCounterReviewPersonId(null);
                newLedger.setCounterReviewType(null);
                newLedger.setCounterReviewDesc(null);
                salesLedgerMapper.insert(newLedger);
                // 复制产品到新台账
                List<SalesLedgerProduct> originalProducts = salesLedgerProductMapper.selectList(
                    Wrappers.<SalesLedgerProduct>lambdaQuery()
                        .eq(SalesLedgerProduct::getSalesLedgerId, id)
                );
                for (SalesLedgerProduct originalProduct : originalProducts) {
                    SalesLedgerProduct newProduct = new SalesLedgerProduct();
                    BeanUtils.copyProperties(originalProduct, newProduct);
                    newProduct.setId(null);
                    newProduct.setSalesLedgerId(newLedger.getId());
                    newProduct.setStockedQuantity(BigDecimal.ZERO);
                    newProduct.setShippedQuantity(BigDecimal.ZERO);
                    newProduct.setUnqualifiedStockedQuantity(BigDecimal.ZERO);
                    newProduct.setUnqualifiedShippedQuantity(BigDecimal.ZERO);
                    newProduct.setReturnQuality(BigDecimal.ZERO);
                    newProduct.setAvailableQuality(newProduct.getQuantity().subtract(newProduct.getReturnQuality()));
                    newProduct.setProductStockStatus(0);
                    newProduct.fillRemainingQuantity();
                    salesLedgerProductMapper.insert(newProduct);
                }
                newLedgerIds.add(newLedger.getId());
            }
        }
        return newLedgerIds;
    }
    /**
     * 旧版反审处理(兼容 addOrUpdateSalesLedger 中 reviewStatus=2 的调用)
     */
    private void handleCounterReview(SalesLedger salesLedger) {
        // 1. 设置反审相关信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        salesLedger.setCounterReviewTime(LocalDateTime.now());
        salesLedger.setCounterReviewPerson(loginUser.getUser().getNickName());
        salesLedger.setCounterReviewPersonId(loginUser.getUserId());
        salesLedger.setReviewStatus(2);
        Long originalSalesLedgerId = salesLedger.getId();
        // 2. 查询原销售台账数据
        SalesLedger originalLedger = salesLedgerMapper.selectById(originalSalesLedgerId);
        if (originalLedger == null) {
            throw new ServiceException("原订单不存在,无法反审");
        }
        // 3. 创建新的销售台账,复制原台账数据
        SalesLedger newLedger = new SalesLedger();
        BeanUtils.copyProperties(originalLedger, newLedger);
        newLedger.setId(null); // 清空ID,准备插入新记录
        newLedger.setSalesContractNo(generateSalesContractNo()); // 生成新合同号
        newLedger.setDeliveryStatus(1); // 设置为未发货状态
        newLedger.setStockStatus(0); // 设置为未入库状态
        newLedger.setReviewStatus(0); // 设置为未审核状态
        newLedger.setCounterReviewTime(null); // 清空反审时间
        newLedger.setCounterReviewPerson(null); // 清空反审人
        newLedger.setCounterReviewPersonId(null); // 清空反审人ID
        // 4. 插入新的销售台账
        salesLedgerMapper.insert(newLedger);
        // 5. 查询并复制原台账的所有产品数据
        List<SalesLedgerProduct> originalProducts = salesLedgerProductMapper.selectList(
            Wrappers.<SalesLedgerProduct>lambdaQuery()
                .eq(SalesLedgerProduct::getSalesLedgerId, originalSalesLedgerId)
        );
        for (SalesLedgerProduct originalProduct : originalProducts) {
            // 5.1 创建新产品记录,复制原产品数据
            SalesLedgerProduct newProduct = new SalesLedgerProduct();
            BeanUtils.copyProperties(originalProduct, newProduct);
            newProduct.setId(null); // 清空ID,准备插入新记录
            newProduct.setSalesLedgerId(newLedger.getId()); // 关联到新的台账ID
            newProduct.setStockedQuantity(BigDecimal.ZERO); // 已入库数量重置为0
            newProduct.setShippedQuantity(BigDecimal.ZERO); // 已出库数量重置为0
            newProduct.setUnqualifiedStockedQuantity(BigDecimal.ZERO); // 不合格入库数量重置为0
            newProduct.setUnqualifiedShippedQuantity(BigDecimal.ZERO); // 不合格出库数量重置为0
            newProduct.setReturnQuality(BigDecimal.ZERO); // 退货数量重置为0
            newProduct.setAvailableQuality(newProduct.getQuantity().subtract(newProduct.getReturnQuality())); // 重新计算可用数量
            newProduct.setProductStockStatus(0); // 产品库存状态重置为0
            newProduct.fillRemainingQuantity(); // 重新计算剩余数量
            // 5.2 插入新产品记录
            salesLedgerProductMapper.insert(newProduct);
        }
        // 6. 处理原订单的库存数据(生成反审出入库记录)
        processOriginalOrderStock(originalSalesLedgerId);
        // 7. 清除原订单的质检记录
        clearQualityInspectRecords(originalSalesLedgerId);
        // 8. 清除原订单的发货信息和发货审批记录
        clearShippingAndApprovalRecords(originalSalesLedgerId);
        // 9. 取消原订单相关的审批流程
        cancelApproveProcesses(originalSalesLedgerId, originalLedger.getSalesContractNo());
    }
    /**
     * 清除原订单的质检记录
     */
    private void clearQualityInspectRecords(Long originalSalesLedgerId) {
        // 删除与原订单关联的质检记录
        qualityInspectMapper.delete(
            Wrappers.<QualityInspect>lambdaQuery()
                .eq(QualityInspect::getPurchaseLedgerId, originalSalesLedgerId)
        );
    }
    /**
     * 清除原订单的发货信息和发货审批记录
     */
    private void clearShippingAndApprovalRecords(Long originalSalesLedgerId) {
        // 1. 查询原订单的所有发货信息
        List<ShippingInfo> shippingInfos = shippingInfoMapper.selectList(
            Wrappers.<ShippingInfo>lambdaQuery()
                .eq(ShippingInfo::getSalesLedgerId, originalSalesLedgerId)
        );
        // 2. 删除发货审批记录
        if (!CollectionUtils.isEmpty(shippingInfos)) {
            List<Long> shippingInfoIds = shippingInfos.stream()
                .map(ShippingInfo::getId)
                .collect(Collectors.toList());
            shipmentApprovalMapper.delete(
                Wrappers.<ShipmentApproval>lambdaQuery()
                    .eq(ShipmentApproval::getSalesLedgerId, originalSalesLedgerId)
                    .or()
                    .in(ShipmentApproval::getShippingInfoId, shippingInfoIds)
            );
            // 3. 删除发货信息记录
            shippingInfoMapper.delete(
                Wrappers.<ShippingInfo>lambdaQuery()
                    .eq(ShippingInfo::getSalesLedgerId, originalSalesLedgerId)
            );
        }
    }
    /**
     * 取消原订单相关的审批流程
     */
    private void cancelApproveProcesses(Long originalSalesLedgerId, String originalSalesContractNo) {
        // 取消入库审批流程
        List<ApproveProcess> stockInApproveProcesses = approveProcessService.list(
            new LambdaQueryWrapper<ApproveProcess>()
                .eq(ApproveProcess::getApproveType, ApproveTypeEnum.STOCK_IN.getCode())
                .like(ApproveProcess::getApproveRemark, "salesStock:" + originalSalesLedgerId + ":")
                .eq(ApproveProcess::getApproveDelete, 0)
        );
        for (ApproveProcess process : stockInApproveProcesses) {
            process.setApproveStatus(3); // 设置为审批失败状态
            process.setApproveDelete(1); // 标记为已删除
            approveProcessService.updateById(process);
        }
        // 取消发货审批流程
        List<ApproveProcess> deliveryApproveProcesses = approveProcessService.list(
            new LambdaQueryWrapper<ApproveProcess>()
                .eq(ApproveProcess::getApproveType, 7) // 发货审批类型
                .like(ApproveProcess::getApproveReason, "发货审批:" + originalSalesContractNo)
                .eq(ApproveProcess::getApproveDelete, 0)
        );
        for (ApproveProcess process : deliveryApproveProcesses) {
            process.setApproveStatus(3); // 设置为审批失败状态
            process.setApproveDelete(1); // 标记为已删除
            approveProcessService.updateById(process);
        }
    }
    /**
     * 处理原订单的库存数据
     * 1. 删除原订单的所有入库记录,并扣减库存
     * 2. 删除原订单的所有出库记录,并增加库存
     */
    private void processOriginalOrderStock(Long originalSalesLedgerId) {
        // 1. 查询原订单的所有入库记录
        List<StockInRecord> stockInRecords = stockInRecordMapper.selectList(
            Wrappers.<StockInRecord>lambdaQuery()
                .eq(StockInRecord::getSalesLedgerId, originalSalesLedgerId)
        );
        // 2. 删除入库记录并扣减库存
        for (StockInRecord stockInRecord : stockInRecords) {
            // 从库存表中扣减相应数量
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setProductModelId(stockInRecord.getProductModelId());
            stockInventoryDto.setQualitity(stockInRecord.getStockInNum());
            stockInventoryMapper.updateSubtractStockInventory(stockInventoryDto);
        }
        // 3. 删除所有入库记录
        stockInRecordMapper.delete(
            Wrappers.<StockInRecord>lambdaQuery()
                .eq(StockInRecord::getSalesLedgerId, originalSalesLedgerId)
        );
        // 4. 查询原订单的所有出库记录
        List<StockOutRecord> stockOutRecords = stockOutRecordMapper.selectList(
            Wrappers.<StockOutRecord>lambdaQuery()
                .eq(StockOutRecord::getSalesLedgerId, originalSalesLedgerId)
        );
        // 5. 删除出库记录并增加库存
        for (StockOutRecord stockOutRecord : stockOutRecords) {
            // 向库存表中增加相应数量
            StockInventoryDto stockInventoryDto = new StockInventoryDto();
            stockInventoryDto.setProductModelId(stockOutRecord.getProductModelId());
            stockInventoryDto.setQualitity(stockOutRecord.getStockOutNum());
            stockInventoryMapper.updateAddStockInventory(stockInventoryDto);
        }
        // 6. 删除所有出库记录
        stockOutRecordMapper.delete(
            Wrappers.<StockOutRecord>lambdaQuery()
                .eq(StockOutRecord::getSalesLedgerId, originalSalesLedgerId)
        );
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void markOrderCompleted(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new ServiceException("请选择要标记完成的订单");
        }
        for (Long id : ids) {
            SalesLedger ledger = salesLedgerMapper.selectById(id);
            if (ledger == null) {
                throw new ServiceException("订单不存在,无法标记完成");
            }
            if (ledger.getReviewStatus() == null || ledger.getReviewStatus() != 1) {
                throw new ServiceException("订单" + ledger.getSalesContractNo() + "不是已审核状态,无法标记完成");
            }
            if (ledger.getOrderStatus() != null && ledger.getOrderStatus() == 1) {
                throw new ServiceException("订单" + ledger.getSalesContractNo() + "已完成,无需重复标记");
            }
        }
        salesLedgerMapper.update(null,
            Wrappers.<SalesLedger>lambdaUpdate()
                .in(SalesLedger::getId, ids)
                .set(SalesLedger::getOrderStatus, 1)
        );
    }
    @Override
    public void incrementPrintCount(Long id, String printType) {
        if (id == null) {
            throw new ServiceException("销售台账ID不能为空");
        }
        if (printType == null || (!"label".equals(printType) && !"document".equals(printType))) {
            throw new ServiceException("打印类型必须为 label 或 document");
        }
        SalesLedger ledger = salesLedgerMapper.selectById(id);
        if (ledger == null) {
            throw new ServiceException("销售台账不存在");
        }
        if ("label".equals(printType)) {
            int currentCount = ledger.getLabelPrintCount() == null ? 0 : ledger.getLabelPrintCount();
            salesLedgerMapper.update(null,
                Wrappers.<SalesLedger>lambdaUpdate()
                    .eq(SalesLedger::getId, id)
                    .set(SalesLedger::getLabelPrintCount, currentCount + 1)
            );
        } else {
            int currentCount = ledger.getDocumentPrintCount() == null ? 0 : ledger.getDocumentPrintCount();
            salesLedgerMapper.update(null,
                Wrappers.<SalesLedger>lambdaUpdate()
                    .eq(SalesLedger::getId, id)
                    .set(SalesLedger::getDocumentPrintCount, currentCount + 1)
            );
        }
    }
    @Override
    public void exportWithProducts(HttpServletResponse response, SalesLedgerDto salesLedgerDto) {
        try {
            // 1. 查询销售台账列表(导出使用升序排序)
            Page<SalesLedger> page = new Page<>(-1, -1);
            // 使用 Wrappers 构建升序查询
            LambdaQueryWrapper<SalesLedger> queryWrapper = Wrappers.<SalesLedger>lambdaQuery()
                .orderByAsc(SalesLedger::getEntryDate)
                .orderByAsc(SalesLedger::getId);
            // 添加查询条件
            if (salesLedgerDto.getCustomerName() != null && !salesLedgerDto.getCustomerName().isEmpty()) {
                queryWrapper.like(SalesLedger::getCustomerName, salesLedgerDto.getCustomerName());
            }
            if (salesLedgerDto.getSalesContractNo() != null && !salesLedgerDto.getSalesContractNo().isEmpty()) {
                queryWrapper.like(SalesLedger::getSalesContractNo, salesLedgerDto.getSalesContractNo());
            }
            if (salesLedgerDto.getProjectName() != null && !salesLedgerDto.getProjectName().isEmpty()) {
                queryWrapper.like(SalesLedger::getProjectName, salesLedgerDto.getProjectName());
            }
            if (salesLedgerDto.getEntryDateStart() != null && !salesLedgerDto.getEntryDateStart().isEmpty()) {
                queryWrapper.ge(SalesLedger::getEntryDate, salesLedgerDto.getEntryDateStart());
            }
            if (salesLedgerDto.getEntryDateEnd() != null && !salesLedgerDto.getEntryDateEnd().isEmpty()) {
                queryWrapper.le(SalesLedger::getEntryDate, salesLedgerDto.getEntryDateEnd());
            }
            if (salesLedgerDto.getDeliveryStatus() != null) {
                queryWrapper.eq(SalesLedger::getDeliveryStatus, salesLedgerDto.getDeliveryStatus());
            }
            if (salesLedgerDto.getStockStatus() != null) {
                queryWrapper.eq(SalesLedger::getStockStatus, salesLedgerDto.getStockStatus());
            }
            if (salesLedgerDto.getReviewStatus() != null) {
                queryWrapper.eq(SalesLedger::getReviewStatus, salesLedgerDto.getReviewStatus());
            }
            if (salesLedgerDto.getOrderStatus() != null) {
                queryWrapper.eq(SalesLedger::getOrderStatus, salesLedgerDto.getOrderStatus());
            }
            if (salesLedgerDto.getReviewStatusList() != null && !salesLedgerDto.getReviewStatusList().isEmpty()) {
                queryWrapper.and(w -> w.in(SalesLedger::getReviewStatus, salesLedgerDto.getReviewStatusList())
                    .or().isNull(SalesLedger::getReviewStatus));
            }
            IPage<SalesLedger> ledgerPage = salesLedgerMapper.selectPage(page, queryWrapper);
            List<SalesLedger> ledgerList = ledgerPage.getRecords();
            // 2. 收集数据
            List<SalesLedgerExportDto> ledgerExportList = new ArrayList<>();
            List<SalesLedgerProductExportDto> productExportList = new ArrayList<>();
            for (SalesLedger ledger : ledgerList) {
                // 转换台账数据
                SalesLedgerExportDto ledgerDto = new SalesLedgerExportDto();
                ledgerDto.setSalesContractNo(ledger.getSalesContractNo());
                ledgerDto.setCustomerContractNo(ledger.getCustomerContractNo());
                ledgerDto.setProjectName(ledger.getProjectName());
                ledgerDto.setCustomerName(ledger.getCustomerName());
                ledgerDto.setSalesman(ledger.getSalesman());
                ledgerDto.setEntryPersonName(ledger.getEntryPersonName());
                ledgerDto.setEntryDate(ledger.getEntryDate());
                ledgerDto.setExecutionDate(ledger.getExecutionDate() != null ?
                    java.sql.Date.valueOf(ledger.getExecutionDate()) : null);
                ledgerDto.setDeliveryDate(ledger.getDeliveryDate() != null ?
                    java.sql.Date.valueOf(ledger.getDeliveryDate()) : null);
                ledgerDto.setContractAmount(ledger.getContractAmount());
                ledgerDto.setRemarks(ledger.getRemarks());
                ledgerDto.setCustomerRemarks(ledger.getCustomerRemarks());
                ledgerDto.setDeliveryStatusText(getDeliveryStatusText(ledger.getDeliveryStatus()));
                ledgerDto.setStockStatusText(getStockStatusText(ledger.getStockStatus()));
                ledgerDto.setReviewStatusText(getReviewStatusText(ledger.getReviewStatus()));
                ledgerDto.setOrderStatusText(getOrderStatusText(ledger.getOrderStatus()));
                ledgerExportList.add(ledgerDto);
                // 查询该台账的产品列表
                List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(
                    Wrappers.<SalesLedgerProduct>lambdaQuery()
                        .eq(SalesLedgerProduct::getSalesLedgerId, ledger.getId())
                        .eq(SalesLedgerProduct::getType, 1)
                );
                for (SalesLedgerProduct product : products) {
                    SalesLedgerProductExportDto productDto = new SalesLedgerProductExportDto();
                    productDto.setSalesContractNo(ledger.getSalesContractNo());
                    productDto.setProductCategory(product.getProductCategory());
                    productDto.setSpecificationModel(product.getSpecificationModel());
                    productDto.setThickness(product.getThickness());
                    productDto.setFloorCode(product.getFloorCode());
                    productDto.setWidth(product.getWidth());
                    productDto.setHeight(product.getHeight());
                    productDto.setQuantity(product.getQuantity());
                    productDto.setSettlePieceArea(product.getSettlePieceArea());
                    productDto.setSettleTotalArea(product.getSettleTotalArea());
                    productDto.setTaxInclusiveUnitPrice(product.getTaxInclusiveUnitPrice());
                    productDto.setTaxRate(product.getTaxRate());
                    productDto.setTaxInclusiveTotalPrice(product.getTaxInclusiveTotalPrice());
                    productDto.setTaxExclusiveTotalPrice(product.getTaxExclusiveTotalPrice());
                    productDto.setInvoiceType(product.getInvoiceType());
                    productDto.setProcessRequirement(product.getProcessRequirement());
                    productDto.setRemark(product.getRemark());
                    productExportList.add(productDto);
                }
            }
            // 3. 使用ExcelUtil导出(内部会创建Workbook并写入响应)
            // 先创建临时文件,再合并两个sheet
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("销售台账.xlsx", "utf-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);
            org.apache.poi.xssf.usermodel.XSSFWorkbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
            // Sheet1: 销售台账 - 手动填充
            fillSheetWithData(workbook, "销售台账", SalesLedgerExportDto.class, ledgerExportList);
            // Sheet2: 产品明细 - 手动填充
            fillSheetWithData(workbook, "产品明细", SalesLedgerProductExportDto.class, productExportList);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("导出销售台账失败", e);
            throw new ServiceException("导出失败:" + e.getMessage());
        }
    }
    @Override
    public void exportProcessRoute(HttpServletResponse response, List<Long> salesLedgerIds, String completedTimeStart, String completedTimeEnd) {
        try {
            if (CollectionUtils.isEmpty(salesLedgerIds)) {
                throw new ServiceException("请选择要导出的销售台账");
            }
            LocalDateTime startTime = parseCompletedTime(completedTimeStart);
            LocalDateTime endTime = parseCompletedTime(completedTimeEnd);
            if (startTime == null && endTime == null) {
                startTime = LocalDate.now().atStartOfDay();
                endTime = LocalDateTime.now();
            } else {
                if (startTime == null) {
                    startTime = LocalDate.now().atStartOfDay();
                }
                if (endTime == null) {
                    endTime = LocalDateTime.now();
                }
            }
            LambdaQueryWrapper<SalesLedgerProcessRouteRecord> queryWrapper = Wrappers.<SalesLedgerProcessRouteRecord>lambdaQuery()
                .eq(SalesLedgerProcessRouteRecord::getIsCompleted, 1)
                .ge(SalesLedgerProcessRouteRecord::getCompletedTime, startTime)
                .le(SalesLedgerProcessRouteRecord::getCompletedTime, endTime)
                .orderByAsc(SalesLedgerProcessRouteRecord::getCompletedTime)
                .orderByAsc(SalesLedgerProcessRouteRecord::getId);
            if (CollectionUtils.isNotEmpty(salesLedgerIds)) {
                queryWrapper.in(SalesLedgerProcessRouteRecord::getSalesLedgerId, salesLedgerIds);
            }
            List<SalesLedgerProcessRouteRecord> completedRoutes = salesLedgerProcessRouteRecordService.list(queryWrapper);
            Map<Long, SalesLedger> salesLedgerMap = Collections.emptyMap();
            Map<Long, SalesLedgerProcessRoute> routeMap = Collections.emptyMap();
            Map<Long, ProcessRouteItem> processRouteItemMap = Collections.emptyMap();
            Map<Long, List<SalesLedgerProduct>> productMap = Collections.emptyMap();
            if (CollectionUtils.isNotEmpty(completedRoutes)) {
                List<Long> routeSalesLedgerIds = completedRoutes.stream()
                    .map(SalesLedgerProcessRouteRecord::getSalesLedgerId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
                List<Long> salesLedgerProcessRouteIds = completedRoutes.stream()
                    .map(SalesLedgerProcessRouteRecord::getSalesLedgerProcessRouteId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(routeSalesLedgerIds)) {
                    salesLedgerMap = salesLedgerMapper.selectBatchIds(routeSalesLedgerIds).stream()
                        .filter(Objects::nonNull)
                        .collect(Collectors.toMap(SalesLedger::getId, item -> item, (a, b) -> a));
                    List<SalesLedgerProduct> products = salesLedgerProductMapper.selectList(new LambdaQueryWrapper<SalesLedgerProduct>()
                        .in(SalesLedgerProduct::getSalesLedgerId, routeSalesLedgerIds)
                        .eq(SalesLedgerProduct::getType, 1)
                        .orderByAsc(SalesLedgerProduct::getSalesLedgerId)
                        .orderByAsc(SalesLedgerProduct::getId));
                    productMap = products.stream().collect(Collectors.groupingBy(
                        SalesLedgerProduct::getSalesLedgerId,
                        LinkedHashMap::new,
                        Collectors.toList()
                    ));
                }
                if (CollectionUtils.isNotEmpty(salesLedgerProcessRouteIds)) {
                    routeMap = salesLedgerProcessRouteService.listByIds(salesLedgerProcessRouteIds).stream()
                        .filter(Objects::nonNull)
                        .collect(Collectors.toMap(SalesLedgerProcessRoute::getId, item -> item, (a, b) -> a));
                    List<Long> processRouteItemIds = routeMap.values().stream()
                        .map(SalesLedgerProcessRoute::getProcessRouteItemId)
                        .filter(Objects::nonNull)
                        .distinct()
                        .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(processRouteItemIds)) {
                        processRouteItemMap = processRouteItemMapper.selectBatchIds(processRouteItemIds).stream()
                            .filter(Objects::nonNull)
                            .collect(Collectors.toMap(ProcessRouteItem::getId, item -> item, (a, b) -> a));
                    }
                }
            }
            Map<Long, List<SalesLedgerProcessRouteRecord>> routeGroupMap = new LinkedHashMap<>();
            for (SalesLedgerProcessRouteRecord record : completedRoutes) {
                SalesLedgerProcessRoute route = routeMap.get(record.getSalesLedgerProcessRouteId());
                if (route == null || route.getProcessRouteItemId() == null) {
                    continue;
                }
                routeGroupMap.computeIfAbsent(route.getProcessRouteItemId(), k -> new ArrayList<>()).add(record);
            }
            final Map<Long, ProcessRouteItem> finalProcessRouteItemMap = processRouteItemMap;
            LinkedHashMap<String, List<List<Object>>> sheetMap = new LinkedHashMap<>();
            List<Long> orderedProcessRouteItemIds = routeGroupMap.keySet().stream()
                .sorted((left, right) -> compareProcessRouteItem(left, right, finalProcessRouteItemMap))
                .collect(Collectors.toList());
            for (Long processRouteItemId : orderedProcessRouteItemIds) {
                ProcessRouteItem processRouteItem = finalProcessRouteItemMap.get(processRouteItemId);
                String sheetName = buildUniqueSheetName(sheetMap, processRouteItem, processRouteItemId);
                List<List<Object>> sheetData = new ArrayList<>();
                sheetData.add(buildProcessRouteHeader());
                for (SalesLedgerProcessRouteRecord route : routeGroupMap.getOrDefault(processRouteItemId, Collections.emptyList())) {
                    SalesLedger salesLedger = salesLedgerMap.get(route.getSalesLedgerId());
                    if (salesLedger == null) {
                        continue;
                    }
                    List<SalesLedgerProduct> products = productMap.getOrDefault(salesLedger.getId(), Collections.emptyList());
                    if (CollectionUtils.isEmpty(products)) {
                        sheetData.add(buildProcessRouteRow(salesLedger, null, route));
                        continue;
                    }
                    for (SalesLedgerProduct product : products) {
                        sheetData.add(buildProcessRouteRow(salesLedger, product, route));
                    }
                }
                if (sheetData.size() == 1) {
                    sheetData.add(Arrays.asList("", "", "", "", "", "", "", "", ""));
                }
                sheetMap.put(sheetName, sheetData);
            }
            if (sheetMap.isEmpty()) {
                List<List<Object>> sheetData = new ArrayList<>();
                sheetData.add(buildProcessRouteHeader());
                sheetData.add(Arrays.asList("", "", "", "", "", "", ""));
                sheetMap.put("工艺路线", sheetData);
            }
            com.ruoyi.common.utils.excel.ExcelUtils.exportManySheet(response, "销售台账工艺路线导出", sheetMap);
        } catch (Exception e) {
            log.error("导出售后台账工艺路线失败", e);
            throw new ServiceException("导出售后台账工艺路线失败:" + e.getMessage());
        }
    }
    private LocalDateTime parseCompletedTime(String value) {
        if (!StringUtils.hasText(value)) {
            return null;
        }
        String text = value.trim();
        try {
            return LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        } catch (Exception ex) {
            try {
                return LocalDateTime.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            } catch (Exception ignored) {
                return LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd")).atStartOfDay();
            }
        }
    }
    private int compareProcessRouteItem(Long left, Long right, Map<Long, ProcessRouteItem> processRouteItemMap) {
        ProcessRouteItem leftItem = processRouteItemMap.get(left);
        ProcessRouteItem rightItem = processRouteItemMap.get(right);
        int leftSort = leftItem != null && leftItem.getDragSort() != null ? leftItem.getDragSort() : Integer.MAX_VALUE;
        int rightSort = rightItem != null && rightItem.getDragSort() != null ? rightItem.getDragSort() : Integer.MAX_VALUE;
        if (leftSort != rightSort) {
            return Integer.compare(leftSort, rightSort);
        }
        String leftName = leftItem != null && StringUtils.hasText(leftItem.getProcessName()) ? leftItem.getProcessName() : "";
        String rightName = rightItem != null && StringUtils.hasText(rightItem.getProcessName()) ? rightItem.getProcessName() : "";
        int nameCompare = leftName.compareTo(rightName);
        if (nameCompare != 0) {
            return nameCompare;
        }
        return Long.compare(left, right);
    }
    private List<Object> buildProcessRouteHeader() {
        return Arrays.asList("日期", "订单编号", "客户名称", "规格", "数量", "面积", "是否是工程");
    }
    private List<Object> buildProcessRouteRow(SalesLedger salesLedger, SalesLedgerProduct product, SalesLedgerProcessRouteRecord route) {
        List<Object> row = new ArrayList<>();
        row.add(salesLedger.getEntryDate() == null ? "" : DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, salesLedger.getEntryDate()));
        row.add(salesLedger.getSalesContractNo());
        row.add(salesLedger.getCustomerName());
        row.add(product == null ? "" : product.getSpecificationModel());
        row.add(product == null ? "" : product.getQuantity());
        row.add(product == null ? "" : resolveExportArea(product));
        row.add("");
        return row;
    }
    private BigDecimal resolveExportArea(SalesLedgerProduct product) {
        if (product == null) {
            return BigDecimal.ZERO;
        }
        if (product.getSettleTotalArea() != null) {
            return product.getSettleTotalArea();
        }
        if (product.getActualTotalArea() != null) {
            return product.getActualTotalArea();
        }
        BigDecimal qty = product.getQuantity() == null ? BigDecimal.ONE : product.getQuantity();
        if (product.getSettlePieceArea() != null) {
            return product.getSettlePieceArea().multiply(qty).setScale(2, RoundingMode.HALF_UP);
        }
        if (product.getActualPieceArea() != null) {
            return product.getActualPieceArea().multiply(qty).setScale(2, RoundingMode.HALF_UP);
        }
        if (product.getWidth() != null && product.getHeight() != null) {
            BigDecimal area = product.getWidth().multiply(product.getHeight())
                .divide(new BigDecimal("1000000"), 2, RoundingMode.HALF_UP);
            return area.multiply(qty).setScale(2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO;
    }
    private String buildUniqueSheetName(Map<String, List<List<Object>>> sheetMap, ProcessRouteItem processRouteItem, Long processRouteItemId) {
        String baseName = processRouteItem != null && StringUtils.hasText(processRouteItem.getProcessName())
            ? processRouteItem.getProcessName()
            : "工序" + processRouteItemId;
        baseName = sanitizeSheetName(baseName);
        String sheetName = baseName;
        int suffix = 2;
        while (sheetMap.containsKey(sheetName)) {
            String suffixText = "_" + suffix++;
            int maxBaseLength = 31 - suffixText.length();
            String trimmedBase = baseName.length() > maxBaseLength ? baseName.substring(0, maxBaseLength) : baseName;
            sheetName = trimmedBase + suffixText;
        }
        return sheetName;
    }
    private String sanitizeSheetName(String sheetName) {
        if (!StringUtils.hasText(sheetName)) {
            return "工艺路线";
        }
        String sanitized = sheetName.replaceAll("[\\\\/?*\\[\\]:]", "_").trim();
        if (sanitized.isEmpty()) {
            sanitized = "工艺路线";
        }
        return sanitized.length() > 31 ? sanitized.substring(0, 31) : sanitized;
    }
    /**
     * 手动填充Sheet数据
     */
    private <T> void fillSheetWithData(org.apache.poi.xssf.usermodel.XSSFWorkbook workbook, String sheetName, Class<T> clazz, List<T> dataList) throws Exception {
        org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet(sheetName);
        // 获取字段上的@Excel注解
        java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
        List<java.lang.reflect.Field> excelFields = new ArrayList<>();
        for (java.lang.reflect.Field field : fields) {
            com.ruoyi.framework.aspectj.lang.annotation.Excel excel = field.getAnnotation(com.ruoyi.framework.aspectj.lang.annotation.Excel.class);
            if (excel != null) {
                excelFields.add(field);
            }
        }
        // 创建表头
        org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
        org.apache.poi.ss.usermodel.CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(org.apache.poi.ss.usermodel.IndexedColors.GREY_50_PERCENT.getIndex());
        headerStyle.setFillPattern(org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND);
        headerStyle.setAlignment(org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER);
        org.apache.poi.ss.usermodel.Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        for (int i = 0; i < excelFields.size(); i++) {
            java.lang.reflect.Field field = excelFields.get(i);
            field.setAccessible(true);
            com.ruoyi.framework.aspectj.lang.annotation.Excel excel = field.getAnnotation(com.ruoyi.framework.aspectj.lang.annotation.Excel.class);
            org.apache.poi.ss.usermodel.Cell cell = headerRow.createCell(i);
            cell.setCellValue(excel.name());
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 20 * 256);
        }
        // 创建数据行
        org.apache.poi.ss.usermodel.CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER);
        for (int rowIndex = 0; rowIndex < dataList.size(); rowIndex++) {
            T data = dataList.get(rowIndex);
            org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowIndex + 1);
            for (int colIndex = 0; colIndex < excelFields.size(); colIndex++) {
                java.lang.reflect.Field field = excelFields.get(colIndex);
                field.setAccessible(true);
                Object value = field.get(data);
                org.apache.poi.ss.usermodel.Cell cell = row.createCell(colIndex);
                if (value == null) {
                    cell.setCellValue("");
                } else if (value instanceof Number) {
                    cell.setCellValue(((Number) value).doubleValue());
                } else if (value instanceof Date) {
                    cell.setCellValue(new java.text.SimpleDateFormat("yyyy-MM-dd").format((Date) value));
                } else {
                    cell.setCellValue(value.toString());
                }
                cell.setCellStyle(dataStyle);
            }
        }
    }
    private String getDeliveryStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 1: return "未发货";
            case 2: return "审批中";
            case 3: return "审批不通过";
            case 4: return "审批通过";
            case 5: return "已发货";
            case 6: return "部分发货";
            default: return "未知";
        }
    }
    private String getStockStatusText(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "未入库";
            case 1: return "部分入库";
            case 2: return "已入库";
            case 3: return "审批中";
            default: return "未知";
        }
    }
    private String getReviewStatusText(Integer status) {
        if (status == null) return "待审核";
        switch (status) {
            case 0: return "待审核";
            case 1: return "已审核";
            case 2: return "已反审";
            default: return "待审核";
        }
    }
    private String getOrderStatusText(Integer status) {
        if (status == null || status == 0) return "进行中";
        switch (status) {
            case 0: return "进行中";
            case 1: return "已完成";
            default: return "进行中";
        }
    }
}