package com.prolog.eis.service.stationOutbound.impl;

import com.prolog.eis.dto.eis4.StationOBAreaContainerDto;
import com.prolog.eis.dto.eis4.StationOBAreaDto;
import com.prolog.eis.dto.eis4.StationOBCarryTaskDto;
import com.prolog.eis.dto.eis4.StationOBDispatchDto;
import com.prolog.eis.service.stationOutbound.StationObNoTaskDispatchService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class StationObNoTaskDispatchServiceImpl implements StationObNoTaskDispatchService {
    @Override
    public List<StationOBCarryTaskDto> dispatch(StationOBDispatchDto stationOBDispatch) {
        List<StationOBCarryTaskDto> obCarryTaskList = new ArrayList<>();

        //获取
        List<StationOBAreaDto> areaList = stationOBDispatch.getAreaList().stream().filter(r -> r.isSendNoTaskContainer()).sorted(Comparator.comparingInt(StationOBAreaDto::getPriority)).collect(Collectors.toList());

        for (StationOBAreaDto area : areaList) {
            for (int i = area.getNoTaskContainerNoList().size() - 1; i > -1; i--) {
                StationOBAreaContainerDto container = area.getNoTaskContainerNoList().get(i);
                String bestTargetAreaNo = this.findBestNoTaskTargetArea(stationOBDispatch, container, area);

                 if (bestTargetAreaNo != null) {
                    stationOBDispatch.removeContainer(container.getContainerNo());

                    StationOBAreaDto bestAreaTarget = stationOBDispatch.findArea(bestTargetAreaNo);
                    if (bestAreaTarget != null) {
                        bestAreaTarget.increaseUseLocatorCount();
                    }

                    StationOBCarryTaskDto obCarryTask = new StationOBCarryTaskDto();
                    obCarryTask.setContainerNo(container.getContainerNo());
                    obCarryTask.setSourceAreaNo(area.getAreaNo());
                    obCarryTask.setTargetAreaNo(bestTargetAreaNo);

                    obCarryTaskList.add(obCarryTask);
                }
            }
        }

        return obCarryTaskList;
    }

    private String findBestNoTaskTargetArea(StationOBDispatchDto stationOBDispatch, StationOBAreaContainerDto container, StationOBAreaDto area) {
        if (!container.isFinishTask() || stationOBDispatch.getNoTaskAreaAction() == null)
            return null;

        List<String> areaNoList = stationOBDispatch.getNoTaskAreaAction().findNoTaskSendArea(container);

        for (String areaNo : areaNoList) {
            StationOBAreaDto areaTarget = stationOBDispatch.findArea(areaNo);
            if (areaTarget == null)
                return areaNo;

            if (areaTarget.getFreeLocatorCount() > 0)
                return areaTarget.getAreaNo();
        }

        return null;
    }
}
