package com.prolog.eis.service.out;

import com.prolog.eis.core.dto.route.AreaInOutCountDto;
import com.prolog.eis.dto.strategy.ContainerInfoDto;
import com.prolog.eis.router.vo.ContainerLocationVo;
import com.prolog.eis.service.feign.RouteFeignService;
import com.prolog.framework.core.exception.PrologException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author dengj
 * @version 1.0
 * @date 2023/3/6 10:21
 */
@Service
@RequiredArgsConstructor
public class BasicStoreStrategyService {

    private final RouteFeignService routeFeignService;

    public void getAreaTask(List<ContainerInfoDto> containerInfoDtoList) throws Exception {
        List<String> collect = containerInfoDtoList.stream().map(ContainerInfoDto::getAreaNo).filter(x -> Objects.nonNull(x)).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collect)) {
            throw new PrologException("容器集合所在区域不能为空");
        }
        List<AreaInOutCountDto> list = routeFeignService.queryAreaInOutCount(collect);
        for (ContainerInfoDto containerInfoDto : containerInfoDtoList) {

            AreaInOutCountDto inOutCountDto = list.stream().filter(x -> x.getAreaNo().equals(containerInfoDto.getAreaNo())).findFirst().orElse(null);
            if (Objects.isNull(inOutCountDto)) {
                containerInfoDto.setTaskNum(0);
            } else {
                containerInfoDto.setTaskNum(inOutCountDto.getInCount() + inOutCountDto.getOutCount());
            }
        }
    }


    public void getContainerLocation(List<ContainerInfoDto> containerInfoDtoList, String warehouseArea) throws Exception {
        List<String> containerNoList = containerInfoDtoList.stream().map(ContainerInfoDto::getContainerNo).collect(Collectors.toList());
        List<ContainerLocationVo> data = routeFeignService.findLocationByContainerList(containerNoList);
        Iterator<ContainerInfoDto> iterator = containerInfoDtoList.iterator();
        while (iterator.hasNext()) {
            ContainerInfoDto next = iterator.next();
            List<ContainerLocationVo> collect =
                    data.stream().filter(containerLocationVo -> containerLocationVo.getContainerNo().equals(next.getContainerNo())).collect(Collectors.toList());
            if (!collect.isEmpty()) {
                ContainerLocationVo containerLocationVo = collect.get(0);
                next.setAreaNo(containerLocationVo.getCurrentArea());
                next.setDepth(containerLocationVo.getDeptNum());
            } else {
                iterator.remove();
            }

        }
    }
}
