package com.prolog.cs.biz.outbound.utils;


import com.prolog.cs.biz.outbound.model.entity.OmsDoBillDDO;
import com.prolog.cs.biz.outbound.model.OmsDoBillHDO;
import com.prolog.framework.core.util.ClassUtils;
import com.prolog.framework.core.util.TableUtils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 算法工具类
 * Created by chenjun on 2021-03-25.
 */
public class AlgorithmUtils {

    /**
     * 波次分组方法
     * @param billList 出库单
     * @param itemList 出库单商品明细
     * @param groupBy 分组参数(表字段)
     * @return
     * @throws Exception
     */
    public static Map<List<String>, Map<String,Object>> waveGroup(List<OmsDoBillHDO> billList, List<OmsDoBillDDO> itemList, String... groupBy){
        Map<List<String>, Map<String,Object>> groups  = new HashMap<>();
        for (final OmsDoBillHDO bill : billList) {
            List<String> key = new ArrayList<>();
            for (String g : groupBy) {
                Field field = TableUtils.getFiled(g, OmsDoBillHDO.class);
                Object objv = ClassUtils.getFieldValue(field.getName(),bill);
                key.add(objv.toString());
            }
            Map<String,Object> wmsOut = groups.get(key);
            List<OmsDoBillHDO> lineBeanList = null;
            List<OmsDoBillDDO> itemBeanList = null;
            if (wmsOut == null) {
                wmsOut = new HashMap<>();
                lineBeanList = new ArrayList<>();
                itemBeanList = new ArrayList<>();
            } else {
                lineBeanList = (List<OmsDoBillHDO>)wmsOut.get("lineBeanList");
                itemBeanList = (List<OmsDoBillDDO>)wmsOut.get("itemBeanList");
            }
            lineBeanList.add(bill);
            wmsOut.put("lineBeanList", lineBeanList);
            for (Iterator<OmsDoBillDDO> it = itemList.iterator(); it.hasNext(); ) {
                OmsDoBillDDO item = it.next();
                if (item.getBillid().equals(bill.getBillid())) {
                    itemBeanList.add(item);
                    wmsOut.put("itemBeanList", itemBeanList);
                    //it.remove();//注释掉陷阱：遍历后长度为0
                }
            }
            groups.put(key, wmsOut);
        }
        return groups;
    }

}