package com.yem.wm.es.Util;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Classname BoxTypeDataGen
 * @Description 单据保存时根据明细信息  大柜和小柜数量不为空的明细行  的箱型箱量，去重合并拼接生成
 * @Date 2023/12/7 13:03
 * @Created by 张子帅
 */

public class BoxTypeDataGen
{
    public static void genBoxTypeData(DynamicObject entity)
    {
        LinkedHashMap<String, BigDecimal> map = new LinkedHashMap<>();


        DynamicObjectCollection collection = entity.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject object : collection) {
            // 大柜名称
            String bigcabinet = object.getString("yem_bigcabinet.name");
            // 小柜名称
            String mincabinet = object.getString("yem_mincabinet.name");

            // 大柜数量
            BigDecimal bigcabinetnumbers = object.getBigDecimal("yem_bigcabinetnumbers");
            // 小柜数量
            BigDecimal mincabinetnumbers = object.getBigDecimal("yem_mincabinetnumbers");

            if (bigcabinetnumbers.compareTo(BigDecimal.ZERO) > 0) {
                if (map.containsKey(bigcabinet)) {
                    map.replace(bigcabinet, map.get(bigcabinet).add(bigcabinetnumbers));
                } else {
                    map.put(bigcabinet, bigcabinetnumbers);
                }
            }

            if (mincabinetnumbers.compareTo(BigDecimal.ZERO) > 0) {
                if (map.containsKey(mincabinet)) {
                    map.replace(mincabinet, map.get(mincabinet).add(mincabinetnumbers));
                }
                map.put(mincabinet, mincabinetnumbers);
            }
        }
        if (!map.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, BigDecimal> entry : map.entrySet()) {
                sb.append(entry.getKey()).append("*").append(entry.getValue().setScale(0, RoundingMode.DOWN)).append(";");
            }
            sb.delete(sb.length() - 1, sb.length());
            // 箱型箱量
            entity.set("yem_boxvolume1", sb.toString());
            SaveServiceHelper.update(new DynamicObject[]{entity});
        }
    }
}
