package com.prolog.eis.dto.bindgridex;


import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Version: 1.0
 * @Author: wuhan
 * @Created: 2024/8/1 15:47
 */
@Getter
@Setter
public class BGDExDispatchDto {
//    @ApiModelProperty("波次绑定最大订单数")
//    private int waveBindMaxOrderCount = 0;

    @ApiModelProperty("格口集合")
    private List<BGDExGridDto> gridList = new ArrayList<>();

    @ApiModelProperty("未绑定格口波次订单集合")
    private List<BGDExOrderDto> orderList = new ArrayList<>();

//    @ApiModelProperty("已绑定订单的波次号集合")
//    private HashSet<String> bindWaveNoHs = new HashSet<>();

    //*****以下为非查询数据*****
    @ApiModelProperty("格口分组集合")
    private List<BGDExGridGroupDto> gridGroupList = new ArrayList<>();

    private void checkOrder() throws Exception {
        Set<Integer> bindOrderIdHs = new HashSet<>();
        for (BGDExGridDto grid : this.gridList) {
            if (grid.getBindOrderId() != null) {
                bindOrderIdHs.add(grid.getBindOrderId());
            }
        }

        for (BGDExOrderDto order : this.orderList) {
            if (order.getOrderId() == 0) {
                throw new Exception("订单ID为0");
            }
            if (bindOrderIdHs.contains(order.getOrderId())) {
                throw new Exception("已绑订单和未绑订单重复：" + order.getOrderId());
            }
        }
    }

    public void init() throws Exception {
        this.checkOrder();

        for (BGDExGridDto grid : this.getGridList()) {
            if (grid.getGroupNo() == null) {
                grid.setGroupNo("defaultGroup");
            }
        }

        Map<String, List<BGDExGridDto>> gridListMap = gridList.stream().collect(Collectors.groupingBy(BGDExGridDto::getGroupNo));
        for (Map.Entry<String, List<BGDExGridDto>> entry : gridListMap.entrySet()) {
            BGDExGridGroupDto group = new BGDExGridGroupDto();
            group.setGridGroupNo(entry.getKey());
            group.setGridList(entry.getValue());

            this.getGridGroupList().add(group);
        }

        for (BGDExGridGroupDto group : this.getGridGroupList()) {
            for (BGDExGridDto grid : group.getGridList()) {
                if (grid.getBindOrderId() == null) {
                    group.getFreeGridList().add(grid);
                }
            }
        }
    }
}
