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

import com.prolog.eis.dto.bindgrid.BGDGridDto;
import com.prolog.eis.dto.bindgrid.BGDGridGroupDto;
import com.prolog.eis.dto.bindgrid.BindGridDispatchDto;
import com.prolog.eis.service.bindgrid.BindGridAlgorithmService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Version: 1.0
 * @Author: wuhan
 * @Created: 2024/8/1 15:37
 */
@Service
public class BindGridAlgorithmServiceImpl implements BindGridAlgorithmService {
    @Override
    public List<BGDGridDto> bindGrid(BindGridDispatchDto dispatchDto) {
        List<Integer> orderIdList = new ArrayList<>();
        orderIdList.addAll(dispatchDto.getOrderIdList());

        List<BGDGridDto> newBindGridList = new ArrayList<>();
        while (true) {
            if (orderIdList.size() == 0) {
                break;
            }
            int orderId = orderIdList.get(0);
            orderIdList.remove(0);
            BGDGridDto bestGrid = this.bindBestGrid(dispatchDto.getGridGroupList(), orderId);
            if (bestGrid == null) {
                break;
            }

            newBindGridList.add(bestGrid);
        }

        return newBindGridList;
    }

    private BGDGridDto bindBestGrid(List<BGDGridGroupDto> groupList, int orderId) {
        BGDGridGroupDto bestGroup = null;
        for (BGDGridGroupDto group : groupList) {
            if (group.getFreeGridList().size() == 0) {
                continue;
            }
            if (bestGroup == null) {
                bestGroup = group;
                continue;
            }

            if (group.getFreeGridList().size() > bestGroup.getFreeGridList().size()) {
                bestGroup = group;
                continue;
            }
        }

        if (bestGroup != null) {
            BGDGridDto bestGrid = bestGroup.getFreeGridList().get(0);
            if (bestGrid != null) {
                bestGroup.getFreeGridList().remove(0);
                bestGrid.setBindOrderId(orderId);
                return bestGrid;
            }
        }

        return null;
    }
}
