package com.prolog.eis.dto.bindgrid;

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 BindGridDispatchDto {
    @ApiModelProperty("格口集合")
    private List<BGDGridDto> gridList = new ArrayList<>();

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

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

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

        for (int orderId : this.getOrderIdList()) {
            if (bindOrderIdHs.contains(orderId)) {
                throw new Exception("已绑订单和未绑订单重复：" + orderId);
            }
        }
    }

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

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

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

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

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