package com.openhis.administration.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.openhis.administration.domain.TraceNoManage;
import com.openhis.administration.mapper.TraceNoManageMapper;
import com.openhis.administration.service.ITraceNoManageService;
import com.openhis.common.enums.TraceNoStatus;

/**
 * 【追溯码管理】Service业务层处理
 *
 * @author system
 * @date 2025-07-07
 */
@Service
public class TraceNoManageServiceImpl extends ServiceImpl<TraceNoManageMapper, TraceNoManage>
    implements ITraceNoManageService {

    /**
     * 获取在库的追溯码列表
     *
     * @param itemId 项目id
     * @param lotNumber 批号
     * @return 追溯码列表
     */
    @Override
    public List<String> getInventoryTraceNoList(Long itemId, String lotNumber) {
        // 根据批号查询一个项目在库存中的追溯码
        List<TraceNoManage> traceNoManageList = baseMapper.selectList(new LambdaQueryWrapper<TraceNoManage>()
            .eq(TraceNoManage::getItemId, itemId).eq(TraceNoManage::getLotNumber, lotNumber));
        // 按追溯码分组
        Map<String, List<TraceNoManage>> groupedByTraceNo =
            traceNoManageList.stream().collect(Collectors.groupingBy(TraceNoManage::getTraceNo));
        // 在库的追溯码列表
        List<String> remainingTraceNos = new ArrayList<>();

        // 遍历每个追溯码的记录
        for (Map.Entry<String, List<TraceNoManage>> entry : groupedByTraceNo.entrySet()) {
            String traceNo = entry.getKey();
            List<TraceNoManage> records = entry.getValue();

            // 统计进入和出去的数量
            int inCount = 0;
            int outCount = 0;
            for (TraceNoManage record : records) {
                if (TraceNoStatus.IN.getValue().equals(record.getStatusEnum())) {
                    inCount++;
                } else if (TraceNoStatus.OUT.getValue().equals(record.getStatusEnum())) {
                    outCount++;
                }
            }
            // 如果进入数量大于出去数量，说明还有剩余在库中
            if (inCount > outCount) {
                remainingTraceNos.add(traceNo);
            }
        }
        return remainingTraceNos;
    }
}