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

import com.prolog.eis.dto.bindgridex.BGDExGridDto;
import com.prolog.eis.dto.bindgridex.BGDExGridGroupDto;
import com.prolog.eis.dto.bindgridex.BGDExDispatchDto;
import com.prolog.eis.dto.bindgridex.BGDExOrderDto;
import com.prolog.eis.service.bindgridex.BindGridExAlgorithmService;
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 BindGridExAlgorithmServiceImpl implements BindGridExAlgorithmService {
    @Override
    public List<BGDExGridDto> bindGrid(BGDExDispatchDto dispatchDto) {
        List<BGDExOrderDto> orderList = new ArrayList<>();
        orderList.addAll(dispatchDto.getOrderList());

        List<BGDExGridDto> newBindGridList = new ArrayList<>();
        while (true) {
            BGDExOrderDto order = this.findBestOrder(orderList);
            if(order == null){
                break;
            }
            orderList.remove(order);

            //绑定最优分组下的格口
            BGDExGridDto bestGrid = this.bindBestGrid(dispatchDto.getGridGroupList(), order);
            if (bestGrid == null) {
                break;
            }

            newBindGridList.add(bestGrid);
        }

        return newBindGridList;
    }

    private BGDExOrderDto findBestOrder(List<BGDExOrderDto> orderList) {
        if (orderList.size() == 0) {
            return null;
        }

        BGDExOrderDto bestOrder = orderList.get(0);
        for (int i = 1; i < orderList.size(); i++) {
            BGDExOrderDto order = orderList.get(i);
            //优先选择波次更早的订单
            if (order.getWaveNo().compareTo(bestOrder.getWaveNo()) < 0) {
                bestOrder = order;
                continue;
            }

            if (order.getDetailCount() > bestOrder.getDetailCount()) {
                bestOrder = order;
                continue;
            }
        }
        return bestOrder;
    }

    private BGDExGridDto bindBestGrid(List<BGDExGridGroupDto> groupList, BGDExOrderDto order) {
        BGDExGridGroupDto bestGroup = null;
        for (BGDExGridGroupDto 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) {
            BGDExGridDto bestGrid = bestGroup.getFreeGridList().get(0);
            if (bestGrid != null) {
                bestGroup.getFreeGridList().remove(0);
                bestGrid.setBindOrderId(order.getOrderId());
                return bestGrid;
            }
        }

        return null;
    }
}
