package com.yem.wm.im.debcrednotenew.utils;

import com.yem.or.utils.OrderUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.basedata.BaseDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhouc
 * @date 2024/3/28 10:28
 * @className DebCredUtils
 * @description 贷记单公共类
 */
public class DebCredUtils {


    /**
     * 生成配件资金池
     *
     * @param temp 贷记单对象
     * @return 配件资金池单据对象
     */
    public static DynamicObject Addspcapitalpool(DynamicObject temp) {
        String yem_billtype = temp.getString("yem_billtype.number");
        DynamicObject loadColl = BusinessDataServiceHelper.newDynamicObject("yem_spcapitalpool");
        loadColl.set("yem_billtype", seelctDyn("bos_billtype", "number", "yem_spcapitalpool_BT"));
        loadColl.set("yem_bizdate", new Date());
        loadColl.set("org", temp.getDynamicObject("org"));
        loadColl.set("billstatus", "A");
        loadColl.set("yem_bd_products", temp.getDynamicObject("yem_bd_products"));
        loadColl.set("yem_operator", temp.getDynamicObject("yem_operator"));
        loadColl.set("yem_department", temp.getDynamicObject("yem_operator"));
        loadColl.set("yem_department", temp.getDynamicObject("org"));
        loadColl.set("yem_customer", temp.getDynamicObject("yem_groupcusfields"));
        loadColl.set("yem_groupcusfields", temp.getDynamicObject("yem_groupcusfields"));
        DynamicObject yem_currencybase = OrderUtils.seelctDyn("bd_currency", "number", "CNY");
        loadColl.set("yem_currency", yem_currencybase);
        loadColl.set("yem_currencybase", temp.getDynamicObject("yem_currencybase"));
        DynamicObject yem_exratetable = temp.getDynamicObject("yem_exratetable");
        loadColl.set("yem_exratetable", yem_exratetable);
        loadColl.set("yem_exratedate", temp.getDate("yem_exratedate"));
        loadColl.set("yem_quotation", temp.getString("yem_quotation"));
        BigDecimal exchangeRate = YEM.getExchangeRate(yem_exratetable.getLong("id"), yem_currencybase.getLong("id"), yem_currencybase.getLong("id"), new Date());
        loadColl.set("yem_exrate", exchangeRate);
        loadColl.set("creator", YEM.getCurrentUserId());
        loadColl.set("createtime", new Date());
        loadColl.set("validstatus", "A");
        loadColl.set("changestatus", "A");
        loadColl.set("yem_version", "1");
        loadColl.set("yem_sourcebillid", temp.getLong("id"));
        //配件资金来源
        DynamicObjectCollection spcapitalpool_a = loadColl.getDynamicObjectCollection("yem_spcapitalpool_o");
        //贷记单来源  yem_creditnotesource
        DynamicObjectCollection yem_creditnotesource = temp.getDynamicObjectCollection("yem_creditnotesource");
        if (yem_creditnotesource.size() > 0) {
            DynamicObject object = spcapitalpool_a.addNew();
            object.set("yem_origintype", temp.getDynamicObject("yem_credittype"));//来源类型
            object.set("yem_originno", temp.getString("billno"));//来源单号
            object.set("yem_datetimefield", new Date());//业务日期
            object.set("yem_sourcecustomer", temp.getDynamicObject("yem_customer"));//来源实际客户
            if (yem_billtype.equals("yem_debcrednote_a")) {
                object.set("yem_origincurr", temp.getDynamicObject("yem_adjusttocurr"));//目标币别
            } else {
                object.set("yem_origincurr", temp.getDynamicObject("yem_currency"));//结算币别
            }
            object.set("yem_originexrate", temp.getBigDecimal("yem_exrate"));//来源单据汇率
            object.set("yem_originamt", temp.getBigDecimal("yem_amount"));//预计金额
            object.set("yem_amountbase", temp.getBigDecimal("yem_amountbase"));//预计本位币金额
            object.set("yem_originremark", temp.getString("yem_esremark"));//备注
            object.set("yem_sourcebillkey_s", temp.getDynamicObjectType().getName());//来源单据标识
            object.set("yem_sourcebillid_o", temp.getLong("id"));//来源单据标识
            object.set("yem_origdebcredtype", temp.getString("yem_debcredtype"));//来源借/贷类型
        }
        //配件资金池去向
        DynamicObjectCollection yem_partsfund = loadColl.getDynamicObjectCollection("yem_partsfund");
        //贷记单去向 yem_creditnotedes
        DynamicObjectCollection yem_creditnotedes = temp.getDynamicObjectCollection("yem_creditnotedes");
        if (yem_creditnotedes.size() > 0) {
            DynamicObject object = yem_partsfund.addNew();
            object.set("yem_towardtype1", temp.getDynamicObject("yem_credittype"));//去向类型
            object.set("yem_towardno1", temp.getString("billno"));//去向单号
            object.set("yem_direcustomer", temp.getDynamicObject("yem_customer"));//来源实际客户
            object.set("yem_towardbizdate1", new Date());//业务日期
            if (yem_billtype.equals("yem_debcrednote_a")) {
                object.set("yem_towardcurrency", temp.getDynamicObject("yem_adjustfromcurr"));//原币
            } else {
                object.set("yem_towardcurrency", temp.getDynamicObject("yem_currency"));//去向结算币别
            }
            object.set("yem_towardexrate1", temp.getBigDecimal("yem_exrate"));//去向单据汇率
            object.set("yem_towardamt1", temp.getBigDecimal("yem_amount_sub"));//预计金额
            object.set("yem_towardamtbase1", temp.getBigDecimal("yem_amountbase_sub"));//预计本位币金额
            object.set("yem_towardremark1", temp.getString("yem_esremark"));//备注
            object.set("yem_creditid1", temp.getDynamicObjectType().getName());//来源单据标识
            object.set("yem_sourceid", temp.getLong("id"));//来源单据标识
            object.set("yem_towdebcredtype", temp.getString("yem_debcredtype"));//去向
            Map<Long, BigDecimal> map = new HashMap<>();
            List yem_towardwritebillno = new ArrayList<>();
            for (int i = 0; i < yem_creditnotedes.size(); i++) {
                DynamicObject creditnotedes = yem_creditnotedes.get(i);
                DynamicObject yem_debcrednoteno = creditnotedes.getDynamicObject("yem_debcrednoteno");
                if (yem_debcrednoteno != null) {
                    String billno = yem_debcrednoteno.getString("billno");
                    yem_towardwritebillno.add(billno);
                    long debcrednotenoid = yem_debcrednoteno.getLong("id");
                    BigDecimal yem_amount_d = creditnotedes.getBigDecimal("yem_amount_d");
                    if (map.containsKey(debcrednotenoid)) {
                        BigDecimal bigDecimal = map.get(debcrednotenoid);
                        map.put(debcrednotenoid, bigDecimal.add(yem_amount_d));
                    } else {
                        map.put(debcrednotenoid, yem_amount_d);
                    }
                }
            }
            if (yem_towardwritebillno.size() > 0) {
                object.set("yem_towardwriteamt", temp.getBigDecimal("yem_sumoriginalamtloc"));//预计核销金额
                object.set("yem_towardwritebillno", dedupAndJoin(yem_towardwritebillno, ";"));//核销借记单单号
            }
            if (map.size() > 0) {
                updateJJD(map, "YJ");
            }
        }
        loadColl = UpdateSpcapitalpoolAmount(loadColl);
        return loadColl;
    }

    /**
     * 更新配件资金池
     *
     * @param temp          贷记单对象
     * @param spcapitalpool 配件资金池对象
     * @return 配件资金池对象
     */
    public static DynamicObject Updatespcapitalpool(DynamicObject temp, DynamicObject spcapitalpool) {
        String billtype = temp.getString("yem_billtype.number");
        //配件资金来源
        DynamicObjectCollection spcapitalpool_a = spcapitalpool.getDynamicObjectCollection("yem_spcapitalpool_o");
        //贷记单来源  yem_creditnotesource
        DynamicObjectCollection yem_creditnotesource = temp.getDynamicObjectCollection("yem_creditnotesource");
        if (yem_creditnotesource.size() > 0) {
            DynamicObject object = spcapitalpool_a.addNew();
            object.set("yem_origintype", temp.getDynamicObject("yem_credittype"));//来源类型
            object.set("yem_originno", temp.getString("billno"));//来源单号
            object.set("yem_sourcecustomer", temp.getDynamicObject("yem_customer"));//来源实际客户
            object.set("yem_datetimefield", new Date());//业务日期
            object.set("yem_origincurr", temp.getDynamicObject("yem_currency"));//结算币别
            object.set("yem_originexrate", temp.getBigDecimal("yem_exrate"));//来源单据汇率
            object.set("yem_originamt", temp.getBigDecimal("yem_amount"));//预计金额
            object.set("yem_amountbase", temp.getBigDecimal("yem_amountbase"));//预计本位币金额
            object.set("yem_originremark", temp.getString("yem_esremark"));//备注
            object.set("yem_sourcebillkey_s", temp.getDynamicObjectType().getName());//来源单据标识
            object.set("yem_sourcebillid_o", temp.getLong("id"));//来源单据标识
            object.set("yem_origdebcredtype", temp.getString("yem_debcredtype"));//来源借/贷类型
        }
        //配件资金池去向
        DynamicObjectCollection yem_partsfund = spcapitalpool.getDynamicObjectCollection("yem_partsfund");
        //贷记单去向 yem_creditnotedes
        DynamicObjectCollection yem_creditnotedes = temp.getDynamicObjectCollection("yem_creditnotedes");
        if (yem_creditnotedes.size() > 0) {
            DynamicObject object = yem_partsfund.addNew();
            object.set("yem_towardtype1", temp.getDynamicObject("yem_credittype"));//去向类型
            object.set("yem_towardno1", temp.getString("billno"));//去向单号
            object.set("yem_direcustomer", temp.getDynamicObject("yem_customer"));//来源实际客户
            object.set("yem_towardbizdate1", new Date());//业务日期
            object.set("yem_towardcurrency", temp.getDynamicObject("yem_currency"));//去向结算币别
            object.set("yem_towardexrate1", temp.getBigDecimal("yem_exrate"));//去向单据汇率
            object.set("yem_towardamt1", temp.getBigDecimal("yem_amount_sub"));//预计金额
            object.set("yem_towardamtbase1", temp.getBigDecimal("yem_amountbase_sub"));//预计本位币金额
            object.set("yem_towardremark1", temp.getString("yem_esremark"));//备注
            object.set("yem_creditid1", temp.getDynamicObjectType().getName());//来源单据标识
            object.set("yem_sourceid", temp.getLong("id"));//去向单据标识
            object.set("yem_towdebcredtype", temp.getString("yem_debcredtype"));//去向
            Map<Long, BigDecimal> map = new HashMap<>();
            List yem_towardwritebillno = new ArrayList<>();
            for (int i = 0; i < yem_creditnotedes.size(); i++) {
                DynamicObject creditnotedes = yem_creditnotedes.get(i);
                DynamicObject yem_debcrednoteno = creditnotedes.getDynamicObject("yem_debcrednoteno");
                if (yem_debcrednoteno != null) {
                    String billno = yem_debcrednoteno.getString("billno");
                    yem_towardwritebillno.add(billno);
                    long debcrednotenoid = yem_debcrednoteno.getLong("id");
                    BigDecimal yem_amount_d = creditnotedes.getBigDecimal("yem_amount_d");
                    if (map.containsKey(debcrednotenoid)) {
                        BigDecimal bigDecimal = map.get(debcrednotenoid);
                        map.put(debcrednotenoid, bigDecimal.add(yem_amount_d));
                    } else {
                        map.put(debcrednotenoid, yem_amount_d);
                    }
                }
            }
            if (yem_towardwritebillno.size() > 0) {
                if (billtype.equals("yem_debcrednote_a")) {
                    object.set("yem_towardwriteamt", temp.getBigDecimal("yem_sumoriginalamtloc"));//预计核销金额
                } else {
                    object.set("yem_towardwriteamt", temp.getBigDecimal("yem_amount_sub"));//预计核销金额
                }
                object.set("yem_towardwritebillno", dedupAndJoin(yem_towardwritebillno, ";"));//核销借记单单号
            }
            if (map.size() > 0) {
                updateJJD(map, "YJ");
            }

        }
        spcapitalpool = UpdateSpcapitalpoolAmount(spcapitalpool);
        return spcapitalpool;
    }

    /**
     * list 去重拼接字符串
     *
     * @param list
     * @param delimiter
     * @return
     */
    public static String dedupAndJoin(List<String> list, String delimiter) {
        Set<String> deduplicated = new LinkedHashSet<>(list);
        StringBuilder sb = new StringBuilder();
        for (String element : deduplicated) {
            sb.append(element).append(delimiter);
        }
        // 移除最后的分隔符
        int length = sb.length();
        if (length > 0 && length > delimiter.length()) {
            sb.setLength(length - delimiter.length());
        }
        return sb.toString();
    }

    public static String dedupLongAndJoin(List<Long> list, String delimiter) {
        StringBuilder sb = new StringBuilder();
        for (Long element : list) {
            sb.append(element).append(delimiter);
        }
        // 移除最后的分隔符
        int length = sb.length();
        if (length > 0 && length > delimiter.length()) {
            sb.setLength(length - delimiter.length());
        }
        return sb.toString();
    }

    /**
     * 更新借记单核销金额
     *
     * @param map
     */
    public static void updateJJD(Map<Long, BigDecimal> map, String type) {
        for (long key : map.keySet()) {
            QFilter qFilter = new QFilter("id", QCP.equals, key);
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_debcrednote", "id", qFilter.toArray());
            if (billType != null) {
                DynamicObject loadColl = BusinessDataServiceHelper.loadSingle(billType.getPkValue(), billType.getDynamicObjectType().getName());
                if (type.equals("YJ")) {
                    BigDecimal yem_towardwriteamt = loadColl.getBigDecimal("yem_towardwriteamt");
                    loadColl.set("yem_towardwriteamt", yem_towardwriteamt.add(map.get(key)));
                }
                if (type.equals("SJ")) {
                    BigDecimal yem_towardsjamt = loadColl.getBigDecimal("yem_towardsjamt");
                    loadColl.set("yem_towardsjamt", yem_towardsjamt.add(map.get(key)));
                }
                SaveServiceHelper.update(new DynamicObject[]{loadColl});
            }
        }
    }

    /**
     * 更新配件资金池(转换贷记单)
     *
     * @param temp          贷记单对象
     * @param spcapitalpool 配件资金池对象
     * @return 配件资金池对象
     */
    public static DynamicObject Updatespcapitalpool_Adjust(DynamicObject temp, DynamicObject spcapitalpool) {
        String yem_adjustdirection = temp.getString("yem_adjustdirection");//调整方向
        //配件资金来源
        DynamicObjectCollection spcapitalpool_a = spcapitalpool.getDynamicObjectCollection("yem_spcapitalpool_o");
        //贷记单来源  yem_creditnotesource
        DynamicObjectCollection yem_creditnotesource = temp.getDynamicObjectCollection("yem_creditnotesource");
        if (yem_creditnotesource.size() > 0) {
            DynamicObject object = spcapitalpool_a.addNew();
            object.set("yem_origintype", temp.getDynamicObject("yem_credittype"));//来源类型
            object.set("yem_originno", temp.getString("billno"));//来源单号
            object.set("yem_sourcecustomer", temp.getDynamicObject("yem_customer"));//来源实际客户
            object.set("yem_datetimefield", new Date());//业务日期

            object.set("yem_origincurr", temp.getDynamicObject("yem_adjusttocurr"));//目标币别
            if (yem_adjustdirection.equals("CNY_USD")) {
                object.set("yem_originexrate", temp.getBigDecimal("yem_adjustexrate"));//来源单据汇率
            } else {
                object.set("yem_originexrate", new BigDecimal(1));//来源单据汇率
            }
            object.set("yem_originamt", temp.getBigDecimal("yem_sumgoalamt"));//预计金额
            object.set("yem_amountbase", temp.getBigDecimal("yem_sumgoalamtloc"));//预计本位币金额
            object.set("yem_originremark", temp.getString("yem_esremark"));//备注
            object.set("yem_sourcebillkey_s", temp.getDynamicObjectType().getName());//来源单据标识
            object.set("yem_sourcebillid_o", temp.getLong("id"));//来源单据标识
            object.set("yem_origdebcredtype", temp.getString("yem_debcredtype"));//来源借/贷类型
        }
        //配件资金池去向
        DynamicObjectCollection yem_partsfund = spcapitalpool.getDynamicObjectCollection("yem_partsfund");
        //贷记单去向 yem_creditnotedes
        DynamicObjectCollection yem_creditnotedes = temp.getDynamicObjectCollection("yem_creditnotedes");
        if (yem_creditnotedes.size() > 0) {
            DynamicObject object = yem_partsfund.addNew();
            object.set("yem_towardtype1", temp.getDynamicObject("yem_credittype"));//去向类型
            object.set("yem_towardno1", temp.getString("billno"));//去向单号
            object.set("yem_direcustomer", temp.getDynamicObject("yem_customer"));//来源实际客户
            object.set("yem_towardbizdate1", new Date());//业务日期
            object.set("yem_towardcurrency", temp.getDynamicObject("yem_adjustfromcurr"));//原币
            if (yem_adjustdirection.equals("CNY_USD")) {
                object.set("yem_towardexrate1", new BigDecimal(1));//来源单据汇率
            } else {
                object.set("yem_towardexrate1", temp.getBigDecimal("yem_adjustexrate"));//来源单据汇率
            }
            object.set("yem_towardamt1", temp.getBigDecimal("yem_sumoriginalamtloc"));//预计金额
            object.set("yem_towardamtbase1", temp.getBigDecimal("yem_sumoriginalamt"));//预计本位币金额
            object.set("yem_towardremark1", temp.getString("yem_esremark"));//备注
            object.set("yem_creditid1", temp.getDynamicObjectType().getName());//来源单据标识
            object.set("yem_sourceid", temp.getLong("id"));//去向单据标识
            object.set("yem_towdebcredtype", temp.getString("yem_debcredtype"));//去向
        }
        spcapitalpool = UpdateSpcapitalpoolAmount(spcapitalpool);
        return spcapitalpool;
    }

    /**
     * 配件资金池金额计算
     *
     * @param spcapitalpool 配件资金池答案句对象
     * @return 配件资金池对象
     */
    public static DynamicObject UpdateSpcapitalpoolAmount(DynamicObject spcapitalpool) {
        //配件资金来源
        DynamicObjectCollection yem_spcapitalpool_o = spcapitalpool.getDynamicObjectCollection("yem_spcapitalpool_o");
        Map<String, Map<String, BigDecimal>> map = new HashMap<>();
        for (int i = 0; i < yem_spcapitalpool_o.size(); i++) {
            DynamicObject yem_spcapitalpool = yem_spcapitalpool_o.get(i);
            DynamicObject yem_origintype = yem_spcapitalpool.getDynamicObject("yem_origintype");
            DynamicObject yem_origincurr = yem_spcapitalpool.getDynamicObject("yem_origincurr");
            if (yem_origintype != null && yem_origincurr != null) {
                long origintypeid = yem_origintype.getLong("id");
                long yem_origincurrid = yem_origincurr.getLong("id");
                String yem_origdebcredtype = yem_spcapitalpool.getString("yem_origdebcredtype");
                String Key = origintypeid + "_" + yem_origincurrid + "_" + yem_origdebcredtype;
                BigDecimal yem_originamt = yem_spcapitalpool.getBigDecimal("yem_originamt");//预计金额
                BigDecimal yem_amountbase = yem_spcapitalpool.getBigDecimal("yem_amountbase");//预计本位币金额
                BigDecimal yem_totalamount = yem_spcapitalpool.getBigDecimal("yem_totalamount"); //实际金额
                BigDecimal yem_totalamountloc = yem_spcapitalpool.getBigDecimal("yem_totalamountloc");//实际金额本位币l
                if (map.containsKey(Key)) {
                    Map<String, BigDecimal> stringBigDecimalMap = map.get(Key);
                    BigDecimal yem_originamt1 = stringBigDecimalMap.get("yem_originamt");
                    stringBigDecimalMap.put("yem_originamt", yem_originamt1.add(yem_originamt));
                    BigDecimal yem_amountbase1 = stringBigDecimalMap.get("yem_amountbase");
                    stringBigDecimalMap.put("yem_amountbase", yem_amountbase1.add(yem_amountbase));
                    BigDecimal yem_totalamount1 = stringBigDecimalMap.get("yem_totalamount");
                    stringBigDecimalMap.put("yem_totalamount", yem_totalamount1.add(yem_totalamount));
                    BigDecimal yem_totalamountloc1 = stringBigDecimalMap.get("yem_totalamountloc");
                    stringBigDecimalMap.put("yem_totalamountloc", yem_totalamountloc1.add(yem_totalamountloc));
                    stringBigDecimalMap.put("yem_towardamt", new BigDecimal(0));
                    stringBigDecimalMap.put("yem_towardamtbase", new BigDecimal(0));
                    stringBigDecimalMap.put("yem_actamount", new BigDecimal(0));
                    stringBigDecimalMap.put("yem_actamountloc", new BigDecimal(0));
                    stringBigDecimalMap.put("yem_towardwriteamt", new BigDecimal(0));
                    stringBigDecimalMap.put("yem_towardsjamt", new BigDecimal(0));
                    map.put(Key, stringBigDecimalMap);
                } else {
                    Map<String, BigDecimal> amtMap = new HashMap<>();
                    amtMap.put("yem_originamt", yem_originamt);
                    amtMap.put("yem_amountbase", yem_amountbase);
                    amtMap.put("yem_totalamount", yem_totalamount);
                    amtMap.put("yem_totalamountloc", yem_totalamountloc);
                    amtMap.put("yem_towardamt", new BigDecimal(0));
                    amtMap.put("yem_towardamtbase", new BigDecimal(0));
                    amtMap.put("yem_actamount", new BigDecimal(0));
                    amtMap.put("yem_actamountloc", new BigDecimal(0));
                    amtMap.put("yem_towardwriteamt", new BigDecimal(0));
                    amtMap.put("yem_towardsjamt", new BigDecimal(0));
                    map.put(Key, amtMap);
                }
            }
        }
        //配件资金池去向
//        Map<String, Map<String, BigDecimal>> towardmap = new HashMap<>();
        DynamicObjectCollection yem_partsfund = spcapitalpool.getDynamicObjectCollection("yem_partsfund");
        for (int j = 0; j < yem_partsfund.size(); j++) {
            DynamicObject partsfund = yem_partsfund.get(j);
            DynamicObject yem_towardtype = partsfund.getDynamicObject("yem_towardtype1");
            DynamicObject yem_towardcurrency = partsfund.getDynamicObject("yem_towardcurrency");
            if (yem_towardtype != null && yem_towardcurrency != null) {
                long origintypeid = yem_towardtype.getLong("id");
                long yem_origincurrid = yem_towardcurrency.getLong("id");
                String yem_origdebcredtype = partsfund.getString("yem_towdebcredtype");
                String Key = origintypeid + "_" + yem_origincurrid + "_" + yem_origdebcredtype;
                BigDecimal yem_towardamt = partsfund.getBigDecimal("yem_towardamt1");//预计金额
                BigDecimal yem_towardamtbase = partsfund.getBigDecimal("yem_towardamtbase1");//预计本位币金额
                BigDecimal yem_actamount = partsfund.getBigDecimal("yem_actamount"); //实际金额
                BigDecimal yem_actamountloc = partsfund.getBigDecimal("yem_actamountloc");//实际金额本位币l
                BigDecimal yem_towardwriteamt = partsfund.getBigDecimal("yem_towardwriteamt");//预计核销金额
                BigDecimal yem_towardsjamt = partsfund.getBigDecimal("yem_towardsjamt");
                if (map.containsKey(Key)) {
                    Map<String, BigDecimal> stringBigDecimalMap = map.get(Key);
                    stringBigDecimalMap.put("yem_sumamo", stringBigDecimalMap.get("yem_sumamo"));//预计来源总金额
                    stringBigDecimalMap.put("yem_sumamobase", stringBigDecimalMap.get("yem_sumamobase"));//预计来源总金额本位币
                    stringBigDecimalMap.put("yem_sumtotalamount", stringBigDecimalMap.get("yem_sumtotalamount"));//实际来源总金额
                    stringBigDecimalMap.put("yem_sumtotalamountloc", stringBigDecimalMap.get("yem_sumtotalamountloc"));//实际来源总金额本位币
                    BigDecimal yem_originamt1 = stringBigDecimalMap.get("yem_towardamt");
                    stringBigDecimalMap.put("yem_towardamt", yem_originamt1.add(yem_towardamt));
                    BigDecimal yem_amountbase1 = stringBigDecimalMap.get("yem_towardamtbase");
                    stringBigDecimalMap.put("yem_towardamtbase", yem_amountbase1.add(yem_towardamtbase));
                    BigDecimal yem_totalamount1 = stringBigDecimalMap.get("yem_actamount");
                    stringBigDecimalMap.put("yem_actamount", yem_totalamount1.add(yem_actamount));
                    BigDecimal yem_totalamountloc1 = stringBigDecimalMap.get("yem_actamountloc");
                    stringBigDecimalMap.put("yem_actamountloc", yem_totalamountloc1.add(yem_actamountloc));
                    BigDecimal yem_towardwriteamt1 = stringBigDecimalMap.get("yem_towardwriteamt");
                    stringBigDecimalMap.put("yem_towardwriteamt", yem_towardwriteamt1.add(yem_towardwriteamt));
                    BigDecimal yem_towardsjamt1 = stringBigDecimalMap.get("yem_towardsjamt");
                    stringBigDecimalMap.put("yem_towardsjamt", yem_towardsjamt1.add(yem_towardsjamt));
                    map.put(Key, stringBigDecimalMap);
                } else {
                    Map<String, BigDecimal> amtMap = new HashMap<>();
                    amtMap.put("yem_originamt", new BigDecimal(0));//预计来源总金额
                    amtMap.put("yem_amountbase", new BigDecimal(0));//预计来源总金额本位币
                    amtMap.put("yem_totalamount", new BigDecimal(0));//实际来源总金额
                    amtMap.put("yem_totalamountloc", new BigDecimal(0));//实际来源总金额本位币
                    amtMap.put("yem_towardamt", yem_towardamt);
                    amtMap.put("yem_towardamtbase", yem_towardamtbase);
                    amtMap.put("yem_actamount", yem_actamount);
                    amtMap.put("yem_actamountloc", yem_actamountloc);
                    amtMap.put("yem_towardwriteamt", yem_towardwriteamt);
                    amtMap.put("yem_towardsjamt", yem_towardsjamt);
                    map.put(Key, amtMap);
                }
            }
        }
        //更新汇总信息
        DynamicObjectCollection yem_spcapitalpool_a = spcapitalpool.getDynamicObjectCollection("yem_spcapitalpool_a");
        yem_spcapitalpool_a.clear();
        for (String mapkey : map.keySet()) {
            Map<String, BigDecimal> stringBigDecimalMap = map.get(mapkey);
            String[] s = mapkey.split("_");
            if (s.length >= 1) {
                DynamicObject object = yem_spcapitalpool_a.addNew();
                object.set("yem_creditype", s[0]);
                object.set("yem_curr", s[1]);
                object.set("yem_debcredtype", s[2]);
                object.set("yem_sumamo", stringBigDecimalMap.get("yem_originamt"));//预计来源总金额
                object.set("yem_sumamobase", stringBigDecimalMap.get("yem_amountbase"));//预计来源总金额本位币
                object.set("yem_sumtotalamount", stringBigDecimalMap.get("yem_totalamount"));//实际来源总金额
                object.set("yem_sumtotalamountloc", stringBigDecimalMap.get("yem_totalamountloc"));//实际来源总金额本位币
                object.set("yem_sumtowardamt", stringBigDecimalMap.get("yem_towardamt"));//预计去向总金额
                object.set("yem_sumtowardamtloc", stringBigDecimalMap.get("yem_towardamtbase"));//预计去向总金额本位币
                object.set("yem_sumactamount", stringBigDecimalMap.get("yem_actamount"));//实际去向金额
                object.set("yem_sumactamountloc", stringBigDecimalMap.get("yem_actamountloc"));//实际去向金额本位币
                object.set("yem_estamount", stringBigDecimalMap.get("yem_originamt").subtract(stringBigDecimalMap.get("yem_towardamt")));//预计剩余金额
                object.set("yem_estamountloc", stringBigDecimalMap.get("yem_amountbase").subtract(stringBigDecimalMap.get("yem_towardamtbase")));//预计剩余金额本位币
                object.set("yem_actremaamount", stringBigDecimalMap.get("yem_totalamount").subtract(stringBigDecimalMap.get("yem_actamount")));//实际剩余金额
                object.set("yem_actremaamountloc", stringBigDecimalMap.get("yem_totalamountloc").subtract(stringBigDecimalMap.get("yem_actamountloc")));//实际剩余本位币l
//                object.set("yem_sumtowardwriteamt", stringBigDecimalMap.get("yem_towardwriteamt"));//预计核销汇总金额
//                object.set("yem_sumtowardsjamt", stringBigDecimalMap.get("yem_towardsjamt"));//实际核销汇总金额
            }
        }
        /**
         * 核销金额汇总
         */
        for (int i = 0; i < yem_spcapitalpool_a.size(); i++) {
            DynamicObject dynamicObject = yem_spcapitalpool_a.get(i);
            //借记类型（-）
            String yem_debcredtype = dynamicObject.getString("yem_debcredtype");
            if (yem_debcredtype.equals("DN")) {
//                DynamicObject yem_creditype = dynamicObject.getDynamicObject("yem_creditype");
//                DynamicObject yem_curr = dynamicObject.getDynamicObject("yem_curr");
//                if (yem_creditype != null && yem_curr != null) {
                long origintypeid = dynamicObject.getLong("yem_creditype");
                long yem_origincurrid = dynamicObject.getLong("yem_curr");
                String Key = origintypeid + "_" + yem_origincurrid + "_CN";
                if (map.containsKey(Key)) {
                    Map<String, BigDecimal> stringBigDecimalMap = map.get(Key);
                    dynamicObject.set("yem_sumtowardwriteamt", stringBigDecimalMap.get("yem_towardwriteamt"));//预计核销汇总金额
                    dynamicObject.set("yem_sumtowardsjamt", stringBigDecimalMap.get("yem_towardsjamt"));//实际核销汇总金额
                }
//                }
            }
        }
        return spcapitalpool;
    }

    /**
     * 更新贷记单配件资金池内码
     *
     * @param temp          贷记单对象
     * @param spcapitalpool 配件资金池对象
     */
    public static void updatespcapitalpool(DynamicObject temp, DynamicObject spcapitalpool) {
        String id = temp.getString("id");
        temp.set("yem_spcapitalpoolid", spcapitalpool.getLong("id"));//配件资金池id
        //贷记单来源  yem_creditnotesource
        DynamicObjectCollection yem_creditnotesource = temp.getDynamicObjectCollection("yem_creditnotesource");
        if (yem_creditnotesource.size() > 0) {
            //配件资金来源
            DynamicObjectCollection spcapitalpool_a = spcapitalpool.getDynamicObjectCollection("yem_spcapitalpool_o");
            for (int i = 0; i < spcapitalpool_a.size(); i++) {
                DynamicObject object = spcapitalpool_a.get(i);
                String yem_sourceid = object.getString("yem_sourcebillid_o");
                if (yem_sourceid.equals(id)) {
                    temp.set("yem_partsid", object.getLong("id"));
                    break;
                }
            }
        }
        //贷记单去向 yem_creditnotedes
        DynamicObjectCollection yem_creditnotedes = temp.getDynamicObjectCollection("yem_creditnotedes");
        if (yem_creditnotedes.size() > 0) {
            //配件资金池去向
            DynamicObjectCollection yem_partsfund = spcapitalpool.getDynamicObjectCollection("yem_partsfund");
            for (int i = 0; i < yem_partsfund.size(); i++) {
                DynamicObject object = yem_partsfund.get(i);
                String yem_sourceid = object.getString("yem_sourceid");
                if (yem_sourceid.equals(id)) {
                    temp.set("yem_accfunddetailid", object.getLong("id"));
                    break;
                }
            }
        }
        SaveServiceHelper.update(temp);
    }

    /**
     * 根据条件查询是否包含
     *
     * @param entryname 单据表示
     * @param filename  查询条件字段
     * @param value     查询条件值
     * @return 返沪动态对象
     */
    public static DynamicObject seelctDyn(String entryname, String filename, Object value) {
        QFilter qFilter = new QFilter(filename, QCP.equals, value);
        DynamicObject Object = BusinessDataServiceHelper.loadSingle(entryname, "id,number,name", qFilter.toArray());
        return Object;
    }

    /**
     * 下单审批生成去向贷记单
     *
     * @param dataEntitie 合同对象
     * @param temp        下单审批对象
     */
    public static DynamicObject AddQXGenerate(DynamicObject dataEntitie, DynamicObject temp) {
        Map<Long, Map<String, String>> map = new HashMap<>();
        DynamicObject debcrednote = BusinessDataServiceHelper.newDynamicObject("yem_debcrednote");
        debcrednote.set("validstatus", "A");
        debcrednote.set("changestatus", "A");
        debcrednote.set("yem_version", "1");
        debcrednote.set("billstatus", "A");
        debcrednote.set("yem_billtype", seelctDyn("bos_billtype", "number", "yem_debcrednote_d"));
        debcrednote.set("yem_customer", dataEntitie.getDynamicObject("yem_customer"));
        debcrednote.set("yem_bizdate", new Date());
        debcrednote.set("yem_operator", dataEntitie.getDynamicObject("yem_operator"));
        debcrednote.set("yem_debcredtype", "CN");
        DynamicObject object = seelctDyn("yem_bd_debcredtype", "number", "JDJLX-0002");
        debcrednote.set("yem_credittype", object);
        debcrednote.set("org", dataEntitie.getDynamicObject("org"));
        debcrednote.set("yem_sourcecreditno", getsourcecreditno(dataEntitie, object, "B"));
        debcrednote.set("yem_sourcebillno", dataEntitie.getString("billno"));
        debcrednote.set("yem_bd_products", dataEntitie.getDynamicObject("yem_bd_products"));
        debcrednote.set("yem_groupcusfields", dataEntitie.getDynamicObject("yem_customer").getDynamicObject("yem_groupcustomers"));
        DynamicObject yem_currency = dataEntitie.getDynamicObject("yem_givecurrency");
        DynamicObject yem_currencybase = OrderUtils.seelctDyn("bd_currency", "number", "CNY");
        DynamicObject yem_exratetable = OrderUtils.seelctDyn("bd_exratetable", "number", "001");
        debcrednote.set("yem_currency", yem_currency);
        debcrednote.set("yem_currencybase", yem_currencybase);
        debcrednote.set("yem_exratetable", yem_exratetable);
        debcrednote.set("yem_exratedate", new Date());
        debcrednote.set("yem_quotation", "0");
        debcrednote.set("yem_counstat", "A");
        debcrednote.set("yem_source", temp.getString("billno"));
        debcrednote.set("yem_partscredit", "A");
        BigDecimal yem_userate = BigDecimal.ZERO;
        if (yem_userate.compareTo(BigDecimal.ZERO) == 0) {
            if (yem_currency != null && yem_currencybase != null && yem_exratetable != null) {
//                yem_userate = BaseDataServiceHelper.getExchangeRate(yem_exratetable.getLong("id"), yem_currency.getLong("id"), yem_currencybase.getLong("id"), new Date());
                yem_userate = YEM.getExchangeRate(yem_exratetable, yem_currency, yem_currencybase, new Date());
                debcrednote.set("yem_exrate", yem_userate);
            }
        } else {
            debcrednote.set("yem_exrate", yem_userate);
        }
        debcrednote.set("creator", YEM.getCurrentUserId());
        debcrednote.set("createtime", new Date());
        debcrednote.set("yem_generate", "B");
        debcrednote.set("validstatus", "A");
        debcrednote.set("yem_version", "1");
        debcrednote.set("yem_sourcebillid", dataEntitie.getLong("id"));
        //贷记单来源
        DynamicObjectCollection yem_creditnotesource = debcrednote.getDynamicObjectCollection("yem_creditnotesource");

        DynamicObjectCollection XDmaterialinfo = temp.getDynamicObjectCollection("yem_es_materialinfo");
        DynamicObjectCollection WXmaterialinfo = dataEntitie.getDynamicObjectCollection("yem_es_salesorder_zp");
        BigDecimal yem_amount = BigDecimal.ZERO;
        BigDecimal yem_amountbase = BigDecimal.ZERO;
        for (int i = 0; i < XDmaterialinfo.size(); i++) {
            DynamicObject accfunddetail = XDmaterialinfo.get(i);
            DynamicObject yem_productmodel = accfunddetail.getDynamicObject("yem_productmodel");
            if (yem_productmodel != null) {
                DynamicObject yem_products = yem_productmodel.getDynamicObject("yem_products");
                for (int j = 0; j < WXmaterialinfo.size(); j++) {
                    DynamicObject materialinfo = WXmaterialinfo.get(j);
                    DynamicObject yem_giveproactype = materialinfo.getDynamicObject("yem_giveproactype");//产品机型
                    if (yem_products.getLong("id") == yem_giveproactype.getLong("id")) {
                        DynamicObject creditnotedes = yem_creditnotesource.addNew();
                        creditnotedes.set("yem_contractno_s", dataEntitie);//合同号
                        creditnotedes.set("yem_bd_products_s", yem_giveproactype);//产品机型
                        creditnotedes.set("yem_creditnotecont_s", "");//贷记单内容
                        BigDecimal yem_qty = accfunddetail.getBigDecimal("yem_qty");
                        BigDecimal yem_singleamt = materialinfo.getBigDecimal("yem_singleamt");
                        creditnotedes.set("yem_teqty", yem_qty);//台数
                        creditnotedes.set("yem_teprice", yem_singleamt);//单台单价
                        BigDecimal yem_amount_s = yem_qty.multiply(yem_singleamt);
                        BigDecimal yem_amountbase_s = yem_amount_s.multiply(yem_userate);
                        yem_amount = yem_amount.add(yem_amount_s);
                        yem_amountbase = yem_amountbase.add(yem_amountbase_s);
                        creditnotedes.set("yem_amount_s", yem_amount_s);//金额
                        creditnotedes.set("yem_amountbase_s", yem_amountbase_s);//金额本位币
                        creditnotedes.set("yem_remarke_s", accfunddetail.getString("yem_remarks"));//备注
                    }
                }
            }
        }
        debcrednote.set("yem_amount", yem_amount);
        debcrednote.set("yem_amountbase", yem_amountbase);
        return debcrednote;
    }


    /**
     * 收款单认领生成去向贷记单
     *
     * @param dataEntitie 合同对象
     */
    public static DynamicObject AddSKDGenerate(DynamicObject dataEntitie, String billno) {
        Map<Long, Map<String, String>> map = new HashMap<>();
        DynamicObject debcrednote = BusinessDataServiceHelper.newDynamicObject("yem_debcrednote");
        debcrednote.set("billstatus", "A");
        debcrednote.set("yem_billtype", seelctDyn("bos_billtype", "number", "yem_debcrednote_d"));
        debcrednote.set("yem_customer", dataEntitie.getDynamicObject("yem_customer"));
        debcrednote.set("yem_bizdate", new Date());
        debcrednote.set("yem_operator", dataEntitie.getDynamicObject("yem_operator"));
        debcrednote.set("yem_debcredtype", "CN");
        DynamicObject object = seelctDyn("yem_bd_debcredtype", "number", "JDJLX-0002");
        debcrednote.set("yem_credittype", object);
        debcrednote.set("yem_counstat", "A");
        debcrednote.set("org", dataEntitie.getDynamicObject("org"));
        debcrednote.set("yem_sourcecreditno", getsourcecreditno(dataEntitie, object, "B"));
        debcrednote.set("yem_sourcebillno", dataEntitie.getString("billno"));
        debcrednote.set("yem_bd_products", dataEntitie.getDynamicObject("yem_bd_products"));
        debcrednote.set("yem_groupcusfields", dataEntitie.getDynamicObject("yem_customer").getDynamicObject("yem_groupcustomers"));
        DynamicObject yem_currency = dataEntitie.getDynamicObject("yem_givecurrency");
        DynamicObject yem_currencybase = OrderUtils.seelctDyn("bd_currency", "number", "CNY");
        DynamicObject yem_exratetable = OrderUtils.seelctDyn("bd_exratetable", "number", "001");
        debcrednote.set("yem_currency", yem_currency);
        debcrednote.set("yem_currencybase", yem_currencybase);
        debcrednote.set("yem_exratetable", yem_exratetable);
        debcrednote.set("yem_exratedate", new Date());
        debcrednote.set("yem_quotation", "0");
        debcrednote.set("yem_source", billno);
        debcrednote.set("yem_partscredit", "C");
//        BigDecimal yem_userate = dataEntitie.getBigDecimal("yem_exrate");
//        if (yem_userate.compareTo(BigDecimal.ZERO) == 0) {
        if (yem_currency != null && yem_currencybase != null && yem_exratetable != null) {
            BigDecimal yem_userate = YEM.getExchangeRate(yem_exratetable, yem_currency, yem_currencybase, new Date());
//                yem_userate = BaseDataServiceHelper.getExchangeRate(yem_exratetable.getLong("id"), yem_currency.getLong("id"), yem_currencybase.getLong("id"), new Date());
            debcrednote.set("yem_exrate", yem_userate);
        }
//        } else {
//            debcrednote.set("yem_exrate", yem_userate);
//        }
        debcrednote.set("creator", YEM.getCurrentUserId());
        debcrednote.set("createtime", new Date());
        debcrednote.set("yem_generate", "B");
        debcrednote.set("validstatus", "A");
        debcrednote.set("changestatus", "A");
        debcrednote.set("yem_version", "1");
        debcrednote.set("yem_sourcebillid", dataEntitie.getLong("id"));
        //贷记单来源
        DynamicObjectCollection yem_creditnotesource = debcrednote.getDynamicObjectCollection("yem_creditnotesource");
        //合同赠送配件
        BigDecimal yem_amount = BigDecimal.ZERO;
        BigDecimal yem_amountbase = BigDecimal.ZERO;
        DynamicObjectCollection WXmaterialinfo = dataEntitie.getDynamicObjectCollection("yem_es_salesorder_zp");
        for (int j = 0; j < WXmaterialinfo.size(); j++) {
            DynamicObject materialinfo = WXmaterialinfo.get(j);
            DynamicObject yem_giveproactype = materialinfo.getDynamicObject("yem_giveproactype");//产品机型
            DynamicObject creditnotedes = yem_creditnotesource.addNew();
            creditnotedes.set("yem_contractno_s", dataEntitie);//合同号
            creditnotedes.set("yem_bd_products_s", yem_giveproactype);//产品机型
            creditnotedes.set("yem_creditnotecont_s", "");//贷记单内容
            creditnotedes.set("yem_teqty", materialinfo.getBigDecimal("yem_qtyint"));//台数
            creditnotedes.set("yem_teprice", materialinfo.getBigDecimal("yem_singleamt"));//单台单价
            BigDecimal yem_amount_s = materialinfo.getBigDecimal("yem_giveamt");
            BigDecimal yem_amountbase_s = materialinfo.getBigDecimal("yem_giveamtbase");
            yem_amount = yem_amount.add(yem_amount_s);
            yem_amountbase = yem_amountbase.add(yem_amountbase_s);
            creditnotedes.set("yem_amount_s", yem_amount_s);//金额
            creditnotedes.set("yem_amountbase_s", yem_amountbase_s);//金额本位币
            creditnotedes.set("yem_remarke_s", materialinfo.getString("yem_giveremark"));//备注
        }
        debcrednote.set("yem_amount", yem_amount);
        debcrednote.set("yem_amountbase", yem_amountbase);
        return debcrednote;
    }

    public static DynamicObject getsourcecreditno(DynamicObject dataEntitie, DynamicObject yem_debcredtype, String debcredtype) {
        DynamicObject object = null;
        //组织
        DynamicObject org = dataEntitie.getDynamicObject("org");
        //客户
        DynamicObject yem_groupcustomers = null;
        DynamicObject yem_customer = dataEntitie.getDynamicObject("yem_customer");
        if (yem_customer != null) {
            yem_groupcustomers = yem_customer.getDynamicObject("yem_groupcustomers");
        }
        //产品类型
        DynamicObject yem_bd_products = dataEntitie.getDynamicObject("yem_bd_products");
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
        qFilter.and(new QFilter("org.id", QCP.equals, org.getLong("id")));
        qFilter.and(new QFilter("yem_customer.id", QCP.equals, yem_groupcustomers.getLong("id")));
        qFilter.and(new QFilter("yem_bd_products.id", QCP.equals, yem_bd_products.getLong("id")));
        qFilter.and(new QFilter("yem_credittype.id", QCP.equals, yem_debcredtype.getLong("id")));
        qFilter.and(new QFilter("yem_debcredtype", QCP.equals, debcredtype));
        String selectfield = DynamicObjectUtil.getSelectfields("yem_debcrednote", false);
        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_debcrednote", "yem_creditnotedes", false);
        DynamicObjectCollection data = QueryServiceHelper.query("yem_debcrednote", "id," + selectfields, new QFilter[]{qFilter}, "billno DESC");
        if (data.size() > 0) {
            object = BusinessDataServiceHelper.loadSingle(data.get(0).getString("id"), "yem_debcrednote");
        }
        return object;
    }

    public static void deleteDJJhxje(String type, DynamicObjectCollection yem_creditnotedes) {
        Map<Long, BigDecimal> map = new HashMap<>();
        List yem_towardwritebillno = new ArrayList<>();
        for (int i = 0; i < yem_creditnotedes.size(); i++) {
            DynamicObject creditnotedes = yem_creditnotedes.get(i);
            DynamicObject yem_debcrednoteno = creditnotedes.getDynamicObject("yem_debcrednoteno");
            if (yem_debcrednoteno != null) {
                String billno = yem_debcrednoteno.getString("billno");
                yem_towardwritebillno.add(billno);
                long debcrednotenoid = yem_debcrednoteno.getLong("id");
                BigDecimal yem_amount_d = creditnotedes.getBigDecimal("yem_amount_d");
                if (map.containsKey(debcrednotenoid)) {
                    BigDecimal bigDecimal = map.get(debcrednotenoid);
                    map.put(debcrednotenoid, bigDecimal.add(yem_amount_d));
                } else {
                    map.put(debcrednotenoid, yem_amount_d);
                }
            }
        }
        for (long key : map.keySet()) {
            QFilter qFilter = new QFilter("id", QCP.equals, key);
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_debcrednote", "id", qFilter.toArray());
            if (billType != null) {
                DynamicObject loadColl = BusinessDataServiceHelper.loadSingle(billType.getPkValue(), billType.getDynamicObjectType().getName());
                if (type.equals("YJ")) {
                    BigDecimal yem_towardwriteamt = loadColl.getBigDecimal("yem_towardwriteamt");
                    loadColl.set("yem_towardwriteamt", yem_towardwriteamt.subtract(map.get(key)));
                }
                if (type.equals("SJ")) {
                    BigDecimal yem_towardwriteamt = loadColl.getBigDecimal("yem_towardsjamt");
                    loadColl.set("yem_towardsjamt", yem_towardwriteamt.subtract(map.get(key)));
                }
                SaveServiceHelper.update(new DynamicObject[]{loadColl});
            }
        }
    }
}
