package com.aiotagro.cattletrade.business.service.impl;

import com.aiotagro.cattletrade.business.dto.WarehouseOutCreateDto;
import com.aiotagro.cattletrade.business.dto.WarehouseOutDto;
import com.aiotagro.cattletrade.business.dto.WarehouseOutEditDto;
import com.aiotagro.cattletrade.business.entity.Delivery;
import com.aiotagro.cattletrade.business.entity.Warehouse;
import com.aiotagro.cattletrade.business.entity.WarehouseIn;
import com.aiotagro.cattletrade.business.entity.WarehouseOut;
import com.aiotagro.cattletrade.business.mapper.DeliveryMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseInMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseMapper;
import com.aiotagro.cattletrade.business.mapper.WarehouseOutMapper;
import com.aiotagro.cattletrade.business.service.IWarehouseOutService;
import com.aiotagro.cattletrade.business.vo.WarehouseOutVo;
import com.aiotagro.common.core.utils.SecurityUtil;
import com.aiotagro.common.core.utils.StringUtils;
import com.aiotagro.common.core.utils.bean.BeanUtils;
import com.aiotagro.common.core.web.domain.AjaxResult;
import com.aiotagro.common.core.web.domain.PageResultResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 出仓管理服务实现类
 *
 * @author System
 * @date 2025-01-20
 */
@Service
public class WarehouseOutServiceImpl extends ServiceImpl<WarehouseOutMapper, WarehouseOut> implements IWarehouseOutService {

    private static final Logger logger = LoggerFactory.getLogger(WarehouseOutServiceImpl.class);

    @Autowired
    private WarehouseOutMapper warehouseOutMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private WarehouseInMapper warehouseInMapper;

    @Autowired
    private DeliveryMapper deliveryMapper;

    /**
     * 分页查询出仓列表
     */
    @Override
    public PageResultResponse<WarehouseOutVo> pageQuery(WarehouseOutDto dto) {
        Integer pageNum = dto.getPageNum() != null ? dto.getPageNum() : 1;
        Integer pageSize = dto.getPageSize() != null ? dto.getPageSize() : 10;

        // 使用PageHelper进行分页
        Page<WarehouseOut> page = PageHelper.startPage(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<WarehouseOut> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.and(wrapper -> wrapper.eq(WarehouseOut::getIsDelete, 0).or().isNull(WarehouseOut::getIsDelete));

        if (StringUtils.isNotEmpty(dto.getOutNumber())) {
            queryWrapper.like(WarehouseOut::getOutNumber, dto.getOutNumber());
        }
        if (dto.getWarehouseId() != null) {
            queryWrapper.eq(WarehouseOut::getWarehouseId, dto.getWarehouseId());
        }
        if (dto.getWarehouseInId() != null) {
            queryWrapper.eq(WarehouseOut::getWarehouseInId, dto.getWarehouseInId());
        }
        if (dto.getDeliveryId() != null) {
            queryWrapper.eq(WarehouseOut::getDeliveryId, dto.getDeliveryId());
        }
        if (dto.getStatus() != null) {
            queryWrapper.eq(WarehouseOut::getStatus, dto.getStatus());
        }
        if (StringUtils.isNotEmpty(dto.getStartTime())) {
            queryWrapper.ge(WarehouseOut::getOutTime, dto.getStartTime() + " 00:00:00");
        }
        if (StringUtils.isNotEmpty(dto.getEndTime())) {
            queryWrapper.le(WarehouseOut::getOutTime, dto.getEndTime() + " 23:59:59");
        }

        queryWrapper.orderByDesc(WarehouseOut::getCreateTime);

        // 执行查询
        List<WarehouseOut> list = warehouseOutMapper.selectList(queryWrapper);

        // 转换为VO并填充关联信息
        List<WarehouseOutVo> voList = new ArrayList<>();
        for (WarehouseOut warehouseOut : list) {
            WarehouseOutVo vo = new WarehouseOutVo();
            BeanUtils.copyProperties(warehouseOut, vo);

            // 关联查询中转仓名称
            if (warehouseOut.getWarehouseId() != null) {
                Warehouse warehouse = warehouseMapper.selectById(warehouseOut.getWarehouseId());
                if (warehouse != null) {
                    vo.setWarehouseName(warehouse.getWarehouseName());
                }
            }

            // 关联查询进仓记录（支持多个ID，用逗号分隔）
            if (warehouseOut.getWarehouseInId() != null && !warehouseOut.getWarehouseInId().trim().isEmpty()) {
                String[] warehouseInIds = warehouseOut.getWarehouseInId().split(",");
                List<String> warehouseInNumbers = new ArrayList<>();
                for (String warehouseInIdStr : warehouseInIds) {
                    try {
                        Integer warehouseInId = Integer.parseInt(warehouseInIdStr.trim());
                        WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseInId);
                        if (warehouseIn != null) {
                            warehouseInNumbers.add(warehouseIn.getInNumber());
                        }
                    } catch (NumberFormatException e) {
                        logger.warn("进仓记录ID格式错误: {}", warehouseInIdStr);
                    }
                }
                if (!warehouseInNumbers.isEmpty()) {
                    vo.setWarehouseInNumber(String.join(",", warehouseInNumbers));
                }
            }

            // 关联查询运送清单信息（车牌号、司机信息等）
            if (warehouseOut.getDeliveryId() != null) {
                Delivery delivery = deliveryMapper.selectById(warehouseOut.getDeliveryId());
                if (delivery != null) {
                    vo.setDeliveryNumber(delivery.getDeliveryNumber());
                    vo.setLicensePlate(delivery.getLicensePlate());
                    vo.setDriverName(delivery.getDriverName());
                    vo.setDriverMobile(delivery.getDriverMobile());
                }
            }

            // 设置状态描述
            vo.setStatusDesc(getStatusDesc(warehouseOut.getStatus()));

            voList.add(vo);
        }

        // 构建分页结果
        return new PageResultResponse<>(page.getTotal(), voList);
    }

    /**
     * 新增出仓记录
     */
    @Override
    @Transactional
    public AjaxResult addWarehouseOut(WarehouseOutCreateDto dto) {
        // 校验中转仓是否存在且启用
        Warehouse warehouse = warehouseMapper.selectById(dto.getWarehouseId());
        if (warehouse == null || (warehouse.getIsDelete() != null && warehouse.getIsDelete() == 1)) {
            return AjaxResult.error("中转仓不存在");
        }
        if (warehouse.getStatus() == null || warehouse.getStatus() == 0) {
            return AjaxResult.error("中转仓未启用，无法出仓");
        }

        // 如果关联了进仓记录，校验进仓记录是否存在
        if (dto.getWarehouseInId() != null) {
            WarehouseIn warehouseIn = warehouseInMapper.selectById(dto.getWarehouseInId());
            if (warehouseIn == null || (warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 1)) {
                return AjaxResult.error("进仓记录不存在");
            }
            // 校验出仓数量不能超过进仓数量
            if (dto.getCattleCount() > warehouseIn.getCattleCount()) {
                return AjaxResult.error("出仓数量不能超过进仓数量");
            }
        }

        // 生成出仓单号：OUT + 年月日 + 4位流水号
        String outNumber = generateOutNumber();

        // 创建出仓实体
        WarehouseOut warehouseOut = new WarehouseOut();
        BeanUtils.copyProperties(dto, warehouseOut);
        warehouseOut.setOutNumber(outNumber);
        warehouseOut.setStatus(1); // 默认待出仓

        // 设置创建人和创建时间
        Integer userId = SecurityUtil.getCurrentUserId();
        warehouseOut.setCreatedBy(userId);
        warehouseOut.setCreateTime(new Date());

        try {
            // 插入数据库
            int result = warehouseOutMapper.insert(warehouseOut);

            if (result > 0) {
                // 更新相关进仓记录的剩余数量
                // 优先使用 warehouseInRelations 数组，如果没有则使用 warehouseInId 和 cattleCount 进行平均分配
                if (dto.getWarehouseInRelations() != null && !dto.getWarehouseInRelations().isEmpty()) {
                    // 使用 warehouseInRelations 数组，精确更新每个进仓记录的剩余数量
                    for (com.aiotagro.cattletrade.business.dto.WarehouseInRelationDto relation : dto.getWarehouseInRelations()) {
                        if (relation.getWarehouseInId() != null && relation.getOutCount() != null && relation.getOutCount() > 0) {
                            updateSingleWarehouseInRemainingCount(relation.getWarehouseInId(), relation.getOutCount(), true);
                        }
                    }
                } else if (warehouseOut.getWarehouseInId() != null && warehouseOut.getCattleCount() != null) {
                    // 回退到平均分配逻辑（兼容旧数据）
                    updateWarehouseInRemainingCount(warehouseOut.getWarehouseInId(), warehouseOut.getCattleCount(), true);
                }
                return AjaxResult.success("新增出仓记录成功", warehouseOut);
            } else {
                return AjaxResult.error("新增出仓记录失败");
            }
        } catch (DuplicateKeyException e) {
            String errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.contains("out_number")) {
                return AjaxResult.error("出仓单号已存在，请重试");
            }
            return AjaxResult.error("数据重复：" + errorMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("新增出仓记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新出仓记录
     */
    @Override
    @Transactional
    public AjaxResult updateWarehouseOut(WarehouseOutEditDto dto) {
        logger.info("========== 更新出仓记录 - Service层 ==========");
        logger.info("接收到的DTO - ID: {}, warehouseInId: {}", dto.getId(), dto.getWarehouseInId());
        
        if (dto.getId() == null) {
            return AjaxResult.error("出仓记录ID不能为空");
        }

        // 验证出仓记录是否存在
        WarehouseOut existingWarehouseOut = warehouseOutMapper.selectById(dto.getId());
        if (existingWarehouseOut == null) {
            return AjaxResult.error("出仓记录不存在");
        }
        
        logger.info("更新前 - 原有记录 warehouse_in_id: {}", existingWarehouseOut.getWarehouseInId());

        // 校验中转仓是否存在且启用
        Warehouse warehouse = warehouseMapper.selectById(dto.getWarehouseId());
        if (warehouse == null || (warehouse.getIsDelete() != null && warehouse.getIsDelete() == 1)) {
            return AjaxResult.error("中转仓不存在");
        }
        if (warehouse.getStatus() == null || warehouse.getStatus() == 0) {
            return AjaxResult.error("中转仓未启用");
        }

        // 如果关联了进仓记录，校验进仓记录是否存在
        // 注意：warehouseInId 现在可能是多个ID（用逗号分隔），需要分别校验
        if (dto.getWarehouseInId() != null && !dto.getWarehouseInId().trim().isEmpty()) {
            String[] warehouseInIds = dto.getWarehouseInId().split(",");
            for (String warehouseInIdStr : warehouseInIds) {
                try {
                    Integer warehouseInId = Integer.parseInt(warehouseInIdStr.trim());
                    WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseInId);
                    if (warehouseIn == null || (warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 1)) {
                        logger.warn("进仓记录不存在，ID: {}", warehouseInId);
                        return AjaxResult.error("进仓记录不存在，ID: " + warehouseInId);
                    }
                    // 注意：多对多关系时，不能简单比较总数，需要在关联表中校验
                    // 这里暂时保留原有逻辑，后续可以优化
                    logger.info("校验进仓记录 - ID: {}, 进仓数量: {}", warehouseInId, warehouseIn.getCattleCount());
                } catch (NumberFormatException e) {
                    logger.warn("进仓记录ID格式错误: {}", warehouseInIdStr, e);
                    return AjaxResult.error("进仓记录ID格式错误: " + warehouseInIdStr);
                }
            }
        }

        // 更新出仓信息
        WarehouseOut warehouseOut = new WarehouseOut();
        BeanUtils.copyProperties(dto, warehouseOut);
        
        logger.info("BeanUtils.copyProperties 后 - warehouseOut.warehouseInId: {}", warehouseOut.getWarehouseInId());
        logger.info("DTO中的warehouseInId类型: {}, 值: {}", 
            dto.getWarehouseInId() != null ? dto.getWarehouseInId().getClass().getName() : "null", 
            dto.getWarehouseInId());

        // 设置更新人和更新时间
        Integer userId = SecurityUtil.getCurrentUserId();
        warehouseOut.setUpdatedBy(userId);
        warehouseOut.setUpdateTime(new Date());
        
        logger.info("准备保存到数据库 - warehouseOut对象详情:");
        logger.info("  - id: {}", warehouseOut.getId());
        logger.info("  - warehouseId: {}", warehouseOut.getWarehouseId());
        logger.info("  - warehouseInId: {} (类型: {})", 
            warehouseOut.getWarehouseInId(), 
            warehouseOut.getWarehouseInId() != null ? warehouseOut.getWarehouseInId().getClass().getName() : "null");
        logger.info("  - cattleCount: {}", warehouseOut.getCattleCount());
        logger.info("  - deliveryId: {}", warehouseOut.getDeliveryId());

        try {
            // 先恢复旧的出仓数量（增加剩余数量）
            if (existingWarehouseOut.getWarehouseInId() != null && existingWarehouseOut.getCattleCount() != null) {
                updateWarehouseInRemainingCount(existingWarehouseOut.getWarehouseInId(), existingWarehouseOut.getCattleCount(), false);
            }
            
            // 更新数据库
            int result = warehouseOutMapper.updateById(warehouseOut);
            
            logger.info("数据库更新结果: {}", result > 0 ? "成功" : "失败");
            
            // 查询更新后的数据，验证是否保存成功
            if (result > 0) {
                WarehouseOut updatedRecord = warehouseOutMapper.selectById(dto.getId());
                if (updatedRecord != null) {
                    logger.info("更新后查询数据库 - warehouse_in_id: {}", updatedRecord.getWarehouseInId());
                }
            }

            if (result > 0) {
                // 减去新的出仓数量（减少剩余数量）
                // 优先使用 warehouseInRelations 数组，如果没有则使用 warehouseInId 和 cattleCount 进行平均分配
                if (dto.getWarehouseInRelations() != null && !dto.getWarehouseInRelations().isEmpty()) {
                    // 使用 warehouseInRelations 数组，精确更新每个进仓记录的剩余数量
                    for (com.aiotagro.cattletrade.business.dto.WarehouseInRelationDto relation : dto.getWarehouseInRelations()) {
                        if (relation.getWarehouseInId() != null && relation.getOutCount() != null && relation.getOutCount() > 0) {
                            updateSingleWarehouseInRemainingCount(relation.getWarehouseInId(), relation.getOutCount(), true);
                        }
                    }
                } else if (warehouseOut.getWarehouseInId() != null && warehouseOut.getCattleCount() != null) {
                    // 回退到平均分配逻辑（兼容旧数据）
                    updateWarehouseInRemainingCount(warehouseOut.getWarehouseInId(), warehouseOut.getCattleCount(), true);
                }
                logger.info("========== 更新出仓记录成功 ==========");
                return AjaxResult.success("更新出仓记录成功");
            } else {
                logger.warn("========== 更新出仓记录失败 - 影响行数为0 ==========");
                return AjaxResult.error("更新出仓记录失败");
            }
        } catch (Exception e) {
            logger.error("========== 更新出仓记录异常 ==========", e);
            e.printStackTrace();
            return AjaxResult.error("更新出仓记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除出仓记录（逻辑删除）
     */
    @Override
    @Transactional
    public AjaxResult deleteWarehouseOut(Integer id) {
        if (id == null) {
            return AjaxResult.error("出仓记录ID不能为空");
        }

        // 查询出仓记录是否存在
        WarehouseOut warehouseOut = warehouseOutMapper.selectById(id);
        if (warehouseOut == null) {
            return AjaxResult.error("出仓记录不存在");
        }

        // 获取当前用户ID
        Integer userId = SecurityUtil.getCurrentUserId();

        // 直接使用 SQL 更新，不依赖 @TableLogic
        UpdateWrapper<WarehouseOut> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id)
                    .eq("is_delete", 0); // 只更新未删除的记录

        updateWrapper.set("is_delete", 1)
                    .set("updated_by", userId)
                    .set("update_time", new Date());

        int result = warehouseOutMapper.update(null, updateWrapper);

        if (result > 0) {
            // 恢复相关进仓记录的剩余数量（增加剩余数量）
            if (warehouseOut.getWarehouseInId() != null && warehouseOut.getCattleCount() != null) {
                updateWarehouseInRemainingCount(warehouseOut.getWarehouseInId(), warehouseOut.getCattleCount(), false);
            }
            return AjaxResult.success("删除出仓记录成功");
        } else {
            return AjaxResult.error("删除出仓记录失败");
        }
    }

    /**
     * 获取出仓详情
     */
    @Override
    public AjaxResult getWarehouseOutDetail(Integer id) {
        if (id == null) {
            return AjaxResult.error("出仓记录ID不能为空");
        }

        WarehouseOut warehouseOut = warehouseOutMapper.selectById(id);
        if (warehouseOut == null || (warehouseOut.getIsDelete() != null && warehouseOut.getIsDelete() == 1)) {
            return AjaxResult.error("出仓记录不存在");
        }

        // 转换为VO并填充关联信息
        WarehouseOutVo vo = new WarehouseOutVo();
        BeanUtils.copyProperties(warehouseOut, vo);

        // 关联查询中转仓名称
        if (warehouseOut.getWarehouseId() != null) {
            Warehouse warehouse = warehouseMapper.selectById(warehouseOut.getWarehouseId());
            if (warehouse != null) {
                vo.setWarehouseName(warehouse.getWarehouseName());
            }
        }

        // 关联查询进仓记录（支持多个ID，用逗号分隔）
        if (warehouseOut.getWarehouseInId() != null && !warehouseOut.getWarehouseInId().trim().isEmpty()) {
            String[] warehouseInIds = warehouseOut.getWarehouseInId().split(",");
            List<String> warehouseInNumbers = new ArrayList<>();
            for (String warehouseInIdStr : warehouseInIds) {
                try {
                    Integer warehouseInId = Integer.parseInt(warehouseInIdStr.trim());
                    WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseInId);
                    if (warehouseIn != null) {
                        warehouseInNumbers.add(warehouseIn.getInNumber());
                    }
                } catch (NumberFormatException e) {
                    logger.warn("进仓记录ID格式错误: {}", warehouseInIdStr);
                }
            }
            if (!warehouseInNumbers.isEmpty()) {
                vo.setWarehouseInNumber(String.join(",", warehouseInNumbers));
            }
        }

        // 关联查询运送清单信息
        if (warehouseOut.getDeliveryId() != null) {
            Delivery delivery = deliveryMapper.selectById(warehouseOut.getDeliveryId());
            if (delivery != null) {
                vo.setDeliveryNumber(delivery.getDeliveryNumber());
                vo.setLicensePlate(delivery.getLicensePlate());
                vo.setDriverName(delivery.getDriverName());
                vo.setDriverMobile(delivery.getDriverMobile());
            }
        }

        // 设置状态描述
        vo.setStatusDesc(getStatusDesc(warehouseOut.getStatus()));

        return AjaxResult.success("查询成功", vo);
    }

    /**
     * 生成出仓单号：OUT + 年月日 + 4位流水号（如：OUT202501200001）
     */
    private String generateOutNumber() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String datePrefix = "OUT" + dateStr;

        // 查询当天最大流水号
        Integer maxSequence = warehouseOutMapper.getMaxSequenceByDate(datePrefix);
        if (maxSequence == null) {
            maxSequence = 0;
        }

        // 生成新的流水号
        int nextSequence = maxSequence + 1;
        return String.format("%s%04d", datePrefix, nextSequence);
    }

    /**
     * 更新单个进仓记录的剩余数量
     * @param warehouseInId 进仓记录ID
     * @param outCount 出仓数量
     * @param isSubtract true-减去出仓数量（减少剩余数量），false-增加出仓数量（恢复剩余数量）
     */
    private void updateSingleWarehouseInRemainingCount(Integer warehouseInId, Integer outCount, boolean isSubtract) {
        if (warehouseInId == null || outCount == null || outCount <= 0) {
            return;
        }

        try {
            WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseInId);
            if (warehouseIn != null && warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 0) {
                int currentRemaining = warehouseIn.getRemainingCount() != null ? warehouseIn.getRemainingCount() : warehouseIn.getCattleCount();
                
                int newRemaining;
                if (isSubtract) {
                    // 减去出仓数量
                    newRemaining = Math.max(0, currentRemaining - outCount);
                } else {
                    // 恢复出仓数量
                    newRemaining = Math.min(warehouseIn.getCattleCount(), currentRemaining + outCount);
                }

                UpdateWrapper<WarehouseIn> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", warehouseInId)
                            .eq("is_delete", 0)
                            .set("remaining_count", newRemaining)
                            .set("update_time", new Date());
                warehouseInMapper.update(null, updateWrapper);
                
                logger.info("更新进仓记录 {} 的剩余数量: {} -> {} (出仓数量: {}, 操作: {})", 
                    warehouseInId, currentRemaining, newRemaining, outCount, isSubtract ? "减去" : "恢复");
            }
        } catch (Exception e) {
            logger.error("更新进仓记录剩余数量失败，进仓记录ID: {}", warehouseInId, e);
        }
    }

    /**
     * 更新进仓记录的剩余数量（平均分配方式，用于兼容旧数据）
     * @param warehouseInIdStr 进仓记录ID（可能是单个ID或逗号分隔的多个ID）
     * @param outCount 出仓数量
     * @param isSubtract true-减去出仓数量（减少剩余数量），false-增加出仓数量（恢复剩余数量）
     */
    private void updateWarehouseInRemainingCount(String warehouseInIdStr, Integer outCount, boolean isSubtract) {
        if (warehouseInIdStr == null || warehouseInIdStr.trim().isEmpty() || outCount == null || outCount <= 0) {
            return;
        }

        try {
            String[] warehouseInIds = warehouseInIdStr.split(",");
            int countPerIn = outCount / warehouseInIds.length; // 平均分配出仓数量
            int remainder = outCount % warehouseInIds.length; // 余数分配给第一个

            for (int i = 0; i < warehouseInIds.length; i++) {
                try {
                    Integer warehouseInId = Integer.parseInt(warehouseInIds[i].trim());
                    WarehouseIn warehouseIn = warehouseInMapper.selectById(warehouseInId);
                    if (warehouseIn != null && warehouseIn.getIsDelete() != null && warehouseIn.getIsDelete() == 0) {
                        int currentRemaining = warehouseIn.getRemainingCount() != null ? warehouseIn.getRemainingCount() : warehouseIn.getCattleCount();
                        int outCountForThis = countPerIn + (i == 0 ? remainder : 0); // 第一个分配余数
                        
                        int newRemaining;
                        if (isSubtract) {
                            // 减去出仓数量
                            newRemaining = Math.max(0, currentRemaining - outCountForThis);
                        } else {
                            // 恢复出仓数量
                            newRemaining = Math.min(warehouseIn.getCattleCount(), currentRemaining + outCountForThis);
                        }

                        UpdateWrapper<WarehouseIn> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", warehouseInId)
                                    .eq("is_delete", 0)
                                    .set("remaining_count", newRemaining)
                                    .set("update_time", new Date());
                        warehouseInMapper.update(null, updateWrapper);
                        
                        logger.info("更新进仓记录 {} 的剩余数量: {} -> {} (出仓数量: {}, 操作: {})", 
                            warehouseInId, currentRemaining, newRemaining, outCountForThis, isSubtract ? "减去" : "恢复");
                    }
                } catch (NumberFormatException e) {
                    logger.warn("进仓记录ID格式错误: {}", warehouseInIds[i], e);
                }
            }
        } catch (Exception e) {
            logger.error("更新进仓记录剩余数量失败", e);
        }
    }

    /**
     * 获取状态描述
     */
    private String getStatusDesc(Integer status) {
        if (status == null) {
            return "未知";
        }
        switch (status) {
            case 1:
                return "待出仓";
            case 2:
                return "已出仓";
            default:
                return "未知";
        }
    }
}

