package com.ruoyi.inventory.service.impl;

import com.ruoyi.common.annotation.SerialExecution;
import com.ruoyi.common.config.WarehouseConfig;
import com.ruoyi.common.core.domain.entity.Materials;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inventory.utils.InventoryCache;
import com.ruoyi.inventory.domain.*;
import com.ruoyi.inventory.domain.vo.OutboundTemplateVO;
import com.ruoyi.inventory.mapper.InventoryMapper;
import com.ruoyi.inventory.mapper.OutboundOrderItemsMapper;
import com.ruoyi.inventory.mapper.OutboundOrderLogMapper;
import com.ruoyi.inventory.mapper.OutboundOrdersMapper;
import com.ruoyi.inventory.service.IOutboundOrdersService;
import org.apache.commons.lang3.SystemUtils;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * 出库单主Service业务层处理
 * 最终适配版：
 * 1. 合并维度「物料ID+库存类型+库位ID」，支持相同维度多库存ID遍历扣减
 * 2. 库存加载改为按维度收集所有库存，扣减时按数量从多到少排序
 * 3. 无库位明细拆分精准匹配实际扣减的库存ID+数量
 * 4. 缓存与数据库实时同步，解决数据不一致问题
 * 5. 合并/扣减/拆分逻辑完全对齐维度，杜绝数据错乱
 *
 * @author ruoyi
 * @date 2025-12-03
 */
@Service
public class OutboundOrdersServiceImpl implements IOutboundOrdersService {
    @Autowired
    private OutboundOrdersMapper outboundOrdersMapper;

    @Autowired
    private OutboundOrderItemsMapper outboundOrderItemsMapper;
    @Autowired
    private OutboundOrderLogMapper outboundOrderLogMapper;

    @Autowired
    private OwnersServiceImpl ownersService;

    @Autowired
    private InventoryServiceImpl inventoryService;
    @Autowired
    private MaterialsServiceImpl materialsService;
    @Autowired
    private StorageLocationsServiceImpl storageLocationsService;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * 查询出库单主
     *
     * @param id 出库单主主键
     * @return 出库单主
     */
    @Override
    public OutboundOrders selectOutboundOrdersById(String id) {
        return outboundOrdersMapper.selectOutboundOrdersById(id);
    }

    /**
     * 查询出库单主列表
     *
     * @param outboundOrders 出库单主
     * @return 出库单主
     */
    @Override
    public List<OutboundOrders> selectOutboundOrdersList(OutboundOrders outboundOrders) {
        List<OutboundOrders> outboundOrders1 = outboundOrdersMapper.selectOutboundOrdersList(outboundOrders);
        return outboundOrders1;
    }

    /**
     * 新增出库单主
     *
     * @param outboundOrders 出库单主
     * @return 结果
     */
    @Transactional
    @Override
    public int insertOutboundOrders(OutboundOrders outboundOrders) {
        outboundOrders.setCreateTime(DateUtils.getNowDate());
        outboundOrders.setCreateUserCode(SystemUtils.getUserName());
        outboundOrders.setId(UUID.randomUUID().toString());
        outboundOrders.setIsImport(0L);

        int rows = outboundOrdersMapper.insertOutboundOrders(outboundOrders);
        insertOutboundOrderItems(outboundOrders);
        return rows;
    }

    /**
     * 修改出库单主（仅保留方法定义，移除更新逻辑）
     *
     * @param outboundOrders 出库单主
     * @return 结果
     */
    @Transactional
    @Override
    public int updateOutboundOrders(OutboundOrders outboundOrders) {
        outboundOrdersMapper.deleteOutboundOrderItemsByOrderId(outboundOrders.getId());
        outboundOrderLogMapper.deleteOutboundOrderLogByOrdersId(outboundOrders.getId());

        outboundOrders.setUpdateUserCode(SystemUtils.getUserName());
        outboundOrders.setUpdateTime(DateUtils.getNowDate());
        insertOutboundOrderItems(outboundOrders);
        return outboundOrdersMapper.updateOutboundOrders(outboundOrders);

    }

    /**
     * 批量删除出库单主
     *
     * @param ids 需要删除的出库单主主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOutboundOrdersByIds(String[] ids) {
        outboundOrdersMapper.deleteOutboundOrderItemsByOrderIds(ids);
        outboundOrderLogMapper.deleteOutboundOrderLogByOrdersIds(ids);
        return outboundOrdersMapper.deleteOutboundOrdersByIds(ids);
    }

    /**
     * 删除出库单主信息
     *
     * @param id 出库单主主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteOutboundOrdersById(String id) {
        outboundOrdersMapper.deleteOutboundOrderItemsByOrderId(id);
        return outboundOrdersMapper.deleteOutboundOrdersById(id);
    }

    @SerialExecution(group = "inventoryRefresh", fair = true)
    @Override
    public int ship(OutboundOrders outboundOrders) {
        // 1. 查询当前出库单的所有明细
        OutboundOrderItems query = new OutboundOrderItems();
        query.setOutboundOrderId(outboundOrders.getId());
        query.setDivisor(null);
        List<OutboundOrderItems> outboundOrderItems = outboundOrderItemsMapper.selectOutboundOrderItemsList(query);

        // 2. 更新明细和订单状态
        OutboundOrderLog outboundOrderLog = new OutboundOrderLog();
        String updateUser = SystemUtils.getUserName();
        Date updateTime = DateUtils.getNowDate();
        for (OutboundOrderItems item : outboundOrderItems) {
            item.setItemStatus(3L);
            item.setUpdateBy(updateUser);
            item.setUpdateTime(updateTime);
            outboundOrderItemsMapper.updateOutboundOrderItems(item);

            outboundOrderLog.setId(item.getId());
            outboundOrderLog.setItemStatus(item.getItemStatus());
            outboundOrderLogMapper.updateOutboundOrderLog(outboundOrderLog);
        }

        outboundOrders.setOrderStatus(2L);
        outboundOrders.setUpdateTime(updateTime);
        outboundOrders.setUpdateUserCode(updateUser);
        outboundOrdersMapper.updateOutboundOrders(outboundOrders);

        inventoryService.ship(outboundOrderItems);
        return 1;
    }

    /**
     * 核心库存扣减逻辑（最终适配版）
     * 1. 扣减维度：物料ID+库存类型+库位ID
     * 2. 相同维度多库存：按数量从多到少遍历扣减，支持全部扣完
     * 3. 无库位→有库位：自动匹配所有可用库位库存，精准扣减
     * 4. 扣减记录按单库存ID生成，支持后续明细精准拆分
     */
    private Map<String, List<Map<String, Object>>> deductInventory(List<OutboundOrderItems> outboundOrderItems, String updateUser, Date updateTime) {
        if (CollectionUtils.isEmpty(outboundOrderItems)) {
            return Collections.emptyMap();
        }

        Map<String, List<Map<String, Object>>> deductRecordMap = new HashMap<>();
        // 预加载库存：按「物料ID+库存类型+库位ID」分组，保存所有库存对象
        Map<String, List<Inventory>> inventoryGroupMap = this.loadInventoryGroupMap();
        Map<String, Long> deductQtyMap = this.buildDeductQtyMap(outboundOrderItems);

        // 库存更新Map（最终去重，保留最终状态）
        Map<String, Inventory> toUpdateInventoryMap = new LinkedHashMap<>();

        for (Map.Entry<String, Long> entry : deductQtyMap.entrySet()) {
            String key = entry.getKey();
            Long totalDeductQty = entry.getValue();
            if (totalDeductQty <= 0) continue;

            String[] keyParts = key.split("_");
            String materialId = keyParts.length > 0 ? keyParts[0] : "";
            String locationId = keyParts.length > 1 ? keyParts[1] : "";
            String inventoryType = keyParts.length > 2 ? keyParts[2] : "";
            String itemId = outboundOrderItems.stream()
                    .filter(item -> key.equals(buildDeductKey(item)))
                    .map(OutboundOrderItems::getId)
                    .findFirst()
                    .orElse(null);

            Long remainDeductQty = totalDeductQty;
            // 核心：按维度分组扣减（先无库位，后有库位）
            List<Map<String, Object>> tempDeductRecords = new ArrayList<>();

            if (StringUtils.isBlank(locationId)) {
                // 步骤1：扣无库位库存（同维度所有库存）
                String noLocKey = buildInventoryKey(materialId, "", inventoryType);
                remainDeductQty = deductByInventoryGroup(noLocKey, remainDeductQty, updateUser, updateTime, inventoryGroupMap, toUpdateInventoryMap, tempDeductRecords);

                // 步骤2：无库位不足，扣同物料+库存类型的所有有库位库存
                if (remainDeductQty > 0) {
                    List<String> hasLocKeys = inventoryGroupMap.keySet().stream()
                            .filter(k -> {
                                String[] parts = k.split("_");
                                return parts.length >= 3
                                        && parts[0].equals(materialId)
                                        && parts[2].equals(inventoryType)
                                        && StringUtils.isNotBlank(parts[1]);
                            })
                            .collect(Collectors.toList());

                    // 有库位库存按总数量从多到少排序（优先扣减库存充足的库位）
                    hasLocKeys.sort((k1, k2) -> {
                        Long qty1 = inventoryGroupMap.get(k1).stream().mapToLong(inv -> Optional.ofNullable(inv.getQuantity()).orElse(0L)).sum();
                        Long qty2 = inventoryGroupMap.get(k2).stream().mapToLong(inv -> Optional.ofNullable(inv.getQuantity()).orElse(0L)).sum();
                        return Long.compare(qty2, qty1);
                    });

                    for (String hasLocKey : hasLocKeys) {
                        if (remainDeductQty <= 0) break;
                        remainDeductQty = deductByInventoryGroup(hasLocKey, remainDeductQty, updateUser, updateTime, inventoryGroupMap, toUpdateInventoryMap, tempDeductRecords);
                    }
                }
            } else {
                // 有库位：扣指定维度库存
                String targetKey = buildInventoryKey(materialId, locationId, inventoryType);
                remainDeductQty = deductByInventoryGroup(targetKey, remainDeductQty, updateUser, updateTime, inventoryGroupMap, toUpdateInventoryMap, tempDeductRecords);
            }

            // 步骤3：剩余数量强制扣减（允许库存负数）
            if (remainDeductQty > 0 && !tempDeductRecords.isEmpty()) {
                Map<String, Object> lastRecord = tempDeductRecords.get(tempDeductRecords.size() - 1);
                String lastInvId = (String) lastRecord.get("inventoryId");
                Inventory lastInv = toUpdateInventoryMap.get(lastInvId);
                if (lastInv == null) {
                    throw new ServiceException(String.format("物料[%s]库存类型[%s]扣减负数时未找到目标库存", materialId, inventoryType));
                }

                // 累计扣减负数数量
                lastInv.setQuantity(lastInv.getQuantity() - remainDeductQty);
                lastInv.setInventoryStatus(0L);
                lastInv.setUpdateBy(updateUser);
                lastInv.setUpdateTime(updateTime);
                toUpdateInventoryMap.put(lastInvId, lastInv);

                // 更新扣减记录
                lastRecord.put("deductQty", (Long) lastRecord.get("deductQty") + remainDeductQty);
                remainDeductQty = 0L;
            }

            // 步骤4：按明细ID归集扣减记录（不合并，保持单库存ID粒度）
            if (itemId != null && !tempDeductRecords.isEmpty()) {
                deductRecordMap.put(itemId, tempDeductRecords);
            }

            // 校验扣减完成
            if (remainDeductQty > 0) {
                throw new ServiceException(String.format("物料[%s]库存类型[%s]扣减失败，剩余%d数量未扣减", materialId, inventoryType, remainDeductQty));
            }
        }

        // 批量更新库存 + 刷新缓存
        if (!toUpdateInventoryMap.isEmpty()) {
            List<Inventory> needUpdateList = new ArrayList<>(toUpdateInventoryMap.values());
            inventoryMapper.batchUpdateInventory(needUpdateList);
            // 刷新缓存：删除旧缓存，重新加载
            needUpdateList.forEach(inv -> {
                String cacheKey = buildInventoryKey(inv.getMaterialId(), inv.getLocationId(), inv.getInventoryType().toString());
                InventoryCache.removeInventory(cacheKey, inv.getId());
                InventoryCache.addInventory(cacheKey, inv);
            });
        }

        return deductRecordMap;
    }

    /**
     * 按维度分组扣减库存（核心适配：遍历同维度所有库存）
     * @param inventoryKey 维度Key
     * @param deductQty 待扣减数量
     * @return 剩余未扣减数量
     */
    private Long deductByInventoryGroup(String inventoryKey, Long deductQty, String updateUser, Date updateTime,
                                        Map<String, List<Inventory>> inventoryGroupMap, Map<String, Inventory> toUpdateInventoryMap,
                                        List<Map<String, Object>> tempDeductRecords) {
        List<Inventory> invList = inventoryGroupMap.getOrDefault(inventoryKey, new ArrayList<>());
        if (CollectionUtils.isEmpty(invList)) {
            return deductQty;
        }

        // 同维度库存按数量从多到少排序（优先扣减数量多的，减少拆分次数）
        invList.sort((a, b) -> {
            Long qtyA = Optional.ofNullable(a.getQuantity()).orElse(0L);
            Long qtyB = Optional.ofNullable(b.getQuantity()).orElse(0L);
            return Long.compare(qtyB, qtyA);
        });

        Long remainDeduct = deductQty;
        for (Inventory inv : invList) {
            if (remainDeduct <= 0) break;

            Long currentQty = Optional.ofNullable(inv.getQuantity()).orElse(0L);
            Long canDeduct = Math.min(remainDeduct, currentQty);

            // 更新库存对象
            inv.setQuantity(currentQty - canDeduct);
            inv.setInventoryStatus(inv.getQuantity() > 0 ? 1L : 0L);
            inv.setUpdateBy(updateUser);
            inv.setUpdateTime(updateTime);
            toUpdateInventoryMap.put(inv.getId(), inv);

            // 生成单库存ID的扣减记录（关键：不再合并库存ID）
            Map<String, Object> record = buildDeductRecord(inv, inv.getInventoryType().toString(), canDeduct);
            tempDeductRecords.add(record);

            remainDeduct -= canDeduct;
        }

        return remainDeduct;
    }

    /**
     * 构建扣减记录（单库存ID粒度）
     */
    private Map<String, Object> buildDeductRecord(Inventory inv, String inventoryType, Long deductQty) {
        Map<String, Object> record = new HashMap<>();
        record.put("inventoryId", inv.getId());
        record.put("locationId", inv.getLocationId());
        record.put("materialId", inv.getMaterialId());
        record.put("inventoryType", inventoryType);
        record.put("deductQty", deductQty);
        return record;
    }

    /**
     * 预加载库存分组Map（按维度Key分组，保存所有库存对象）
     */
    private Map<String, List<Inventory>> loadInventoryGroupMap() {
        // 1. 用你现有的selectInventoryList查全量可用库存（传空条件=查所有）
        Inventory query = new Inventory();
        query.setInventoryStatus(1L); // 只查可用状态库存
        query.setIsUsed(1L);          // 只查启用的库存
        List<Inventory> allInventory = inventoryMapper.selectInventoryList(query);

        // 2. 按维度分组（和你原有逻辑完全一致）
        Map<String, List<Inventory>> inventoryGroupMap = new LinkedHashMap<>();
        for (Inventory inv : allInventory) {
            String key = buildInventoryKey(
                    inv.getMaterialId(),
                    inv.getLocationId(),
                    Optional.ofNullable(inv.getInventoryType()).map(String::valueOf).orElse("")
            );
            inventoryGroupMap.computeIfAbsent(key, k -> new ArrayList<>()).add(inv);
        }
        return inventoryGroupMap;
    }

    /**
     * 构建扣减数量Map
     * Key规则：物料ID_库位ID_库存类型
     */
    private Map<String, Long> buildDeductQtyMap(List<OutboundOrderItems> items) {
        Map<String, Long> deductQtyMap = new HashMap<>();
        for (OutboundOrderItems item : items) {
            String key = buildDeductKey(item);
            Long qty = Optional.ofNullable(item.getActualQuantity()).orElse(0L);
            deductQtyMap.put(key, deductQtyMap.getOrDefault(key, 0L) + qty);
        }
        return deductQtyMap;
    }

    /**
     * 构建明细的扣减Key
     */
    private String buildDeductKey(OutboundOrderItems item) {
        return buildInventoryKey(
                item.getMaterialId(),
                item.getLocationId(),
                Optional.ofNullable(item.getInventoryType()).map(String::valueOf).orElse("")
        );
    }

    /**
     * 构建库存Key：物料ID_库位ID_库存类型
     */
    private String buildInventoryKey(String materialId, String locationId, String inventoryType) {
        return String.join("_",
                Optional.ofNullable(materialId).orElse(""),
                Optional.ofNullable(locationId).orElse(""),
                Optional.ofNullable(inventoryType).orElse("")
        );
    }

    @Override
    public List<Map<String, String>> outboundOrdersTopTenByQuantity() {
        return outboundOrdersMapper.SelectOutboundOrdersMaterialsTopTenByQuantity();
    }

    @Override
    public List<Map<String, String>> outboundOrdersTopTenByAmount() {
        return outboundOrdersMapper.SelectOutboundOrdersMaterialsTopTenByAmount();
    }

    @Override
    public String outboundOrdersCount() {
        return outboundOrdersMapper.outboundOrdersCount();
    }

    /**
     * 新增出库单明细信息
     */
    public void insertOutboundOrderItems(OutboundOrders outboundOrders) {
        List<OutboundOrderItems> outboundOrderItemsList = outboundOrders.getOutboundOrderItemsList();
        String id = outboundOrders.getId();
        if (CollectionUtils.isEmpty(outboundOrderItemsList)) {
            return;
        }

        // 库存校验：失败时抛异常
        boolean isValid = inventoryService.inventoryLockValidation(outboundOrderItemsList);
        if (!isValid) {
            throw new RuntimeException("库存被修改请重新确认");
        }

        // 合并相同维度明细（仅合并数量，库存ID不拼接）
        List<OutboundOrderItems> mergedItemsList = mergeSameInventoryItems(outboundOrderItemsList);

        // 为明细设置订单ID和主键ID
        for (OutboundOrderItems items : mergedItemsList) {
            items.setOutboundOrderId(id);
            items.setOrderId(outboundOrders.getOrderId());
            items.setId(UUID.randomUUID().toString().replace("-", ""));
        }

        // 批量插入出库单明细
        outboundOrdersMapper.batchOutboundOrderItems(mergedItemsList);

        // 拷贝明细到日志列表
        List<String> inventoryIds = new ArrayList<>();
        List<OutboundOrderLog> outboundOrderLogs = new ArrayList<>();
        for (OutboundOrderItems items : mergedItemsList) {
            OutboundOrderLog log = new OutboundOrderLog();
            BeanUtils.copyProperties(items, log);
            log.setOrderId(items.getOutboundOrderId());
            outboundOrderLogs.add(log);
            // 拆分库存ID（支持逗号分隔）
            if (StringUtils.isNotBlank(items.getInventoryId())) {
                String[] invIds = items.getInventoryId().split(",");
                for (String invId : invIds) {
                    if (StringUtils.isNotBlank(invId)) {
                        inventoryIds.add(invId.trim());
                    }
                }
            }
        }

        // 插入日志 + 刷新库存
        if (!outboundOrderLogs.isEmpty()) {
            outboundOrderLogMapper.batchOutboundOrderLog(outboundOrderLogs);
        }
        if (!inventoryIds.isEmpty()) {
            inventoryService.RefreshInventory(inventoryIds);
        }
    }

    /**
     * 合并相同维度明细（仅合并数量，不拼接库存ID）
     */
    private List<OutboundOrderItems> mergeSameInventoryItems(List<OutboundOrderItems> itemsList) {
        if (CollectionUtils.isEmpty(itemsList)) {
            return Collections.emptyList();
        }

        Map<String, OutboundOrderItems> mergeMap = new LinkedHashMap<>();
        for (OutboundOrderItems item : itemsList) {
            String mergeKey = buildInventoryKey(
                    item.getMaterialId(),
                    item.getLocationId(),
                    Optional.ofNullable(item.getInventoryType()).map(String::valueOf).orElse("")
            );

            if (mergeMap.containsKey(mergeKey)) {
                OutboundOrderItems existItem = mergeMap.get(mergeKey);
                // 仅累加数量
                Long newActualQty = Optional.ofNullable(existItem.getActualQuantity()).orElse(0L)
                        + Optional.ofNullable(item.getActualQuantity()).orElse(0L);
                existItem.setActualQuantity(newActualQty);
            } else {
                mergeMap.put(mergeKey, item);
            }
        }

        return new ArrayList<>(mergeMap.values());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importOutboundOrders(List<OutboundTemplateVO> inboundOrdersList, Boolean isUpdateSupport, String operName, Integer orderType) {
        // 1. 基础空值校验
        if (CollectionUtils.isEmpty(inboundOrdersList)) {
            throw new ServiceException("导入数据不能为空！");
        }

        // 2. 初始化变量
        int totalMainSuccess = 0;
        int totalMainFailure = 0;
        int totalItemSuccess = 0;
        int totalItemFailure = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Date now = DateUtils.getNowDate();
        Long userId = SecurityUtils.getUserId();
        String operId = userId != null ? userId.toString() : "system";

        Map<String, OutboundOrders> validMainMap = new HashMap<>();
        Map<String, List<OutboundOrderItems>> validItemMap = new HashMap<>();
        boolean hasValidateError = false;

        // 3. 预加载映射缓存
        Map<String, String> sapToMaterialIdMap = loadSapToMaterialIdMap();
        Map<String, String> locationNameToIdMap = loadLocationNameToIdMap();
        Map<String, String> ownerNameToIdMap = loadOwnerNameToIdMap();
        Map<String, List<Inventory>> inventoryGroupMap = loadInventoryGroupMap();

        // 4. 按入库单号分组
        Map<String, List<OutboundTemplateVO>> orderGroupMap = inboundOrdersList.stream()
                .filter(vo -> StringUtils.isNotBlank(vo.getOrderId()))
                .collect(Collectors.groupingBy(OutboundTemplateVO::getOrderId));

        // 5. 数据验证（仅新增逻辑）
        for (Map.Entry<String, List<OutboundTemplateVO>> entry : orderGroupMap.entrySet()) {
            String orderId = entry.getKey();
            List<OutboundTemplateVO> voList = entry.getValue();
            OutboundOrders mainDO = null;
            List<OutboundOrderItems> itemDOList = new ArrayList<>();

            try {
                OutboundTemplateVO firstVO = voList.get(0);
                // 检查出库单是否已存在
                OutboundOrders outboundOrdersQuery = new OutboundOrders();
                outboundOrdersQuery.setOrderId(orderId);
                List<OutboundOrders> existMains = outboundOrdersMapper.selectOutboundOrdersList(outboundOrdersQuery);

                if (existMains != null && !existMains.isEmpty()) {
                    throw new ServiceException(String.format("入库单号【%s】已存在，当前系统仅支持新增，不支持更新", orderId));
                }

                // 构建新出库单主数据
                mainDO = new OutboundOrders();
                BeanUtils.copyProperties(firstVO, mainDO,
                        "sapNo", "materialName", "plannedQuantity", "actualQuantity",
                        "plannedPackages", "materialUnit", "materialRemark", "warehouseName", "warehouseId");

                // 货主校验
                String ownerName = firstVO.getOwnerName();
                String ownerId = firstVO.getOwnerId();
                if (StringUtils.isNotBlank(ownerName)) {
                    String mappedOwnerId = ownerNameToIdMap.get(ownerName.trim());
                    if (StringUtils.isBlank(mappedOwnerId)) {
                        throw new ServiceException(String.format("业主【%s】不存在，无法新增入库单【%s】",
                                ownerName, orderId));
                    }
                    if (ownerId != null && !ownerId.equals(mappedOwnerId)) {
                        throw new ServiceException(String.format("入库单号【%s】的业主ID【%s】与业主名称【%s】不匹配",
                                orderId, ownerId, ownerName));
                    }
                    mainDO.setOwnerId(mappedOwnerId);
                } else if (ownerId != null) {
                    Owners ownerById = ownersService.selectOwnersById(ownerId);
                    if (ownerById == null) {
                        throw new ServiceException(String.format("入库单号【%s】的业主ID【%s】不存在",
                                orderId, ownerId));
                    }
                    mainDO.setOwnerId(ownerId);
                } else {
                    throw new ServiceException(String.format("入库单号【%s】的业主名称/ID不能为空", orderId));
                }

                // 填充主表必填字段
                mainDO.setId(UUID.randomUUID().toString());
                mainDO.setOrderId(orderId);
                mainDO.setOrderStatus(2L);
                mainDO.setCreateBy(operId);
                mainDO.setCreateTime(now);
                mainDO.setOrderTypeId(String.valueOf(orderType));
                mainDO.setCreateUserCode(operId);
                mainDO.setUpdateBy(operId);
                mainDO.setUpdateTime(now);
                mainDO.setUpdateUserCode(operId);
                mainDO.setSortNo(Optional.ofNullable(mainDO.getSortNo()).orElse(0L));
                mainDO.setIsImport(0L);
                mainDO.setInboundDate(DateUtils.getNowDate());

                // 明细校验
                for (int i = 0; i < voList.size(); i++) {
                    OutboundTemplateVO vo = voList.get(i);
                    int lineNo = i + 1;
                    OutboundOrderItems itemDO = new OutboundOrderItems();

                    BeanUtils.copyProperties(vo, itemDO,
                            "orderId", "systemNo", "orderTypeId", "batchId", "warehouseName", "warehouseId");

                    // 填充明细必填字段
                    itemDO.setId(UUID.randomUUID().toString().replace("-", ""));
                    itemDO.setOrderId(orderId);
                    itemDO.setBatchCode(Optional.ofNullable(mainDO.getBatchCode()).orElse(""));
                    itemDO.setOutboundOrderId(mainDO.getId());
                    itemDO.setCreateBy(operId);
                    itemDO.setCreateTime(now);
                    itemDO.setCreateUserCode(operId);
                    itemDO.setSortNo(0L);
                    itemDO.setItemStatus(3L);
                    itemDO.setShippedAt(mainDO.getInboundDate());

                    // 物料SAP校验
                    String sapNo = vo.getSapNo() != null ? vo.getSapNo().trim() : "";
                    if (StringUtils.isBlank(sapNo)) {
                        throw new ServiceException(String.format("入库单号【%s】第%d条明细的物料SAP号不能为空",
                                orderId, lineNo));
                    }
                    String materialId = sapToMaterialIdMap.get(sapNo);
                    if (StringUtils.isBlank(materialId)) {
                        throw new ServiceException(String.format("入库单号【%s】第%d条明细的SAP号【%s】对应的物料不存在",
                                orderId, lineNo, sapNo));
                    }
                    itemDO.setMaterialId(materialId);

                    // 库位校验
                    String locationName = vo.getLocationName() != null ? vo.getLocationName().trim() : "";
                    if (StringUtils.isNotBlank(locationName)) {
                        String locationId = locationNameToIdMap.get(locationName);
                        if (StringUtils.isBlank(locationId)) {
                            throw new ServiceException(String.format("入库单号【%s】第%d条明细的库位【%s】不存在",
                                    orderId, lineNo, locationName));
                        }
                        itemDO.setLocationId(locationId);
                    }

                    // 库存类型设置
                    itemDO.setInventoryType(orderType);
                    // 实际出库数量
                    itemDO.setActualQuantity(Optional.ofNullable(vo.getActualQuantity()).orElse(0L));

                    itemDOList.add(itemDO);
                }

                // 合并相同维度明细
                List<OutboundOrderItems> mergedItemList = mergeSameInventoryItems(itemDOList);
                validMainMap.put(orderId, mainDO);
                validItemMap.put(orderId, mergedItemList);

            } catch (Exception e) {
                hasValidateError = true;
                totalMainFailure++;
                totalItemFailure += voList.size();
                failureMsg.append(String.format("入库单号【%s】验证失败：%s；\n", orderId, e.getMessage()));
            }
        }

        // 6. 有验证失败直接抛异常
        if (hasValidateError) {
            throw new ServiceException(String.format("验证失败，导入终止！失败详情：%s", failureMsg.toString()));
        }

        // 7. 执行新增操作
        Map<String, List<OutboundOrderItems>> allItemListMap = new HashMap<>();
        for (Map.Entry<String, OutboundOrders> entry : validMainMap.entrySet()) {
            String orderId = entry.getKey();
            OutboundOrders mainDO = entry.getValue();
            List<OutboundOrderItems> itemDOList = validItemMap.get(orderId);

            // 新增主单
            outboundOrdersMapper.insertOutboundOrders(mainDO);
            totalMainSuccess++;
            successMsg.append(String.format("入库单号【%s】已新增；\n", orderId));

            // 插入明细
            if (!CollectionUtils.isEmpty(itemDOList)) {
                int itemSuccess = outboundOrderItemsMapper.batchInsertOutboundOrderItems(itemDOList);
                totalItemSuccess += itemSuccess;
                int itemFail = itemDOList.size() - itemSuccess;
                totalItemFailure += itemFail;

                successMsg.append(String.format("入库单号【%s】成功导入%d条物料明细；\n", orderId, itemSuccess));
                if (itemFail > 0) {
                    failureMsg.append(String.format("入库单号【%s】有%d条物料明细导入失败；\n", orderId, itemFail));
                }

                allItemListMap.put(orderId, itemDOList);
            }
        }

        // ========== 关键修改：移除 CompletableFuture 异步执行，改为同步调用 ==========
        // 8. 同步执行库存扣减和无库位明细拆分（原异步逻辑改为同步）
        try {
            for (Map.Entry<String, List<OutboundOrderItems>> entry : allItemListMap.entrySet()) {
                List<OutboundOrderItems> itemList = entry.getValue();
                // 执行库存扣减
                Map<String, List<Map<String, Object>>> deductRecordMap = deductInventory(itemList, operId, now);
                // 处理无库位明细拆分
                handleNoLocationItemSplit(itemList, deductRecordMap, operId, now);
            }
        } catch (Exception e) {
        }

        // 9. 结果汇总
        if (totalMainFailure > 0 || totalItemFailure > 0) {
            String finalFailureMsg = String.format(
                    "导入结果：成功新增%d个入库单，失败%d个；成功导入%d条明细，失败%d条。失败详情：%s",
                    totalMainSuccess, totalMainFailure, totalItemSuccess, totalItemFailure, failureMsg.toString()
            );
            throw new ServiceException(finalFailureMsg);
        } else {
            String finalSuccessMsg = String.format(
                    "恭喜您，数据已全部导入成功！共新增%d个入库单，成功导入%d条物料明细。详情：%s",
                    totalMainSuccess, totalItemSuccess, successMsg.toString()
            );
            return finalSuccessMsg;
        }
    }

    /**
     * 处理无库位明细拆分（精准匹配扣减记录）
     */
    private void handleNoLocationItemSplit(List<OutboundOrderItems> itemList,
                                           Map<String, List<Map<String, Object>>> deductRecordMap,
                                           String operId, Date now) {
        List<OutboundOrderItems> newItemList = new ArrayList<>();
        Set<String> orderIdSet = new HashSet<>();

        for (OutboundOrderItems item : itemList) {
            if (StringUtils.isNotBlank(item.getLocationId())) {
                continue; // 跳过有库位明细
            }
            String itemId = item.getId();
            List<Map<String, Object>> deductRecords = deductRecordMap.get(itemId);
            if (CollectionUtils.isEmpty(deductRecords)) continue;

            orderIdSet.add(item.getOutboundOrderId());
            // 按扣减记录拆分明细（一条扣减记录对应一条新明细）
            for (Map<String, Object> rec : deductRecords) {
                String inventoryId = (String) rec.get("inventoryId");
                String locId = (String) rec.get("locationId");
                Long deductQty = (Long) rec.get("deductQty");

                if (deductQty <= 0 || StringUtils.isBlank(inventoryId)) continue;

                OutboundOrderItems newItem = new OutboundOrderItems();
                BeanUtils.copyProperties(item, newItem);
                newItem.setId(UUID.randomUUID().toString().replace("-", ""));
                newItem.setLocationId(locId);
                newItem.setActualQuantity(deductQty);
                newItem.setInventoryId(inventoryId);
                newItem.setUpdateBy(operId);
                newItem.setUpdateTime(now);
                newItemList.add(newItem);
            }
        }

        // 删除原无库位明细，插入拆分后的新明细
        if (!orderIdSet.isEmpty() && !newItemList.isEmpty()) {
            orderIdSet.forEach(orderId -> outboundOrderItemsMapper.deleteOutboundOrderItemsByOrderId(orderId));
            outboundOrderItemsMapper.batchInsertOutboundOrderItems(newItemList);

            // 生成拆分后的日志
            List<OutboundOrderLog> logList = newItemList.stream().map(item -> {
                OutboundOrderLog log = new OutboundOrderLog();
                BeanUtils.copyProperties(item, log);
                log.setOrderId(item.getOutboundOrderId());
                log.setItemStatus(3L);
                return log;
            }).collect(Collectors.toList());
            outboundOrderLogMapper.batchOutboundOrderLog(logList);
        }
    }

    // ========== 预加载映射辅助方法 ==========
    private Map<String, String> loadSapToMaterialIdMap() {
        List<Materials> materialsList = materialsService.selectMaterialsList(new Materials());
        if (CollectionUtils.isEmpty(materialsList)) {
            return Collections.emptyMap();
        }
        return materialsList.stream()
                .filter(m -> StringUtils.isNotBlank(m.getSapNo()))
                .collect(Collectors.toMap(
                        m -> m.getSapNo().trim(),
                        Materials::getId,
                        (k1, k2) -> k1
                ));
    }

    private Map<String, String> loadLocationNameToIdMap() {
        StorageLocations query = new StorageLocations();
        query.setIsUsed(1L);
        List<StorageLocations> locationList = storageLocationsService.selectStorageLocationsList(query);
        if (CollectionUtils.isEmpty(locationList)) {
            return Collections.emptyMap();
        }
        return locationList.stream()
                .filter(l -> StringUtils.isNotBlank(l.getLocationCode()))
                .collect(Collectors.toMap(
                        l -> l.getLocationCode().trim(),
                        StorageLocations::getId,
                        (k1, k2) -> k1
                ));
    }

    private Map<String, String> loadOwnerNameToIdMap() {
        List<Owners> ownerList = ownersService.selectOwnersList(new Owners());
        if (CollectionUtils.isEmpty(ownerList)) {
            return Collections.emptyMap();
        }
        return ownerList.stream()
                .filter(o -> StringUtils.isNotBlank(o.getOwnerName()))
                .collect(Collectors.toMap(
                        o -> o.getOwnerName().trim(),
                        Owners::getId,
                        (k1, k2) -> k1
                ));
    }
}