package com.yem.wm.es.storagetrans.op;

import com.yem.or.utils.OrderApiUtils;
import com.yem.wm.es.Util.CreditBackFillUtils;
import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.es.storagetrans.validator.StorageTransAuditValid;
import com.yem.wm.utils.CalendarUtils;
import com.yem.wm.utils.GiftAmount;
import com.yem.wm.utils.YEM;
import kd.bos.armor.core.util.StringUtil;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
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.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

import static com.yem.wm.es.storagetrans.form.StorageTransEdit.isLastShip;

/**
 * @author xwudd
 * @date 15:14
 * @Description
 **/
public class StorageTransAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_customer");
        fieldKeys.add("yem_salecontractno");
        fieldKeys.add("yem_quotation_cd");
        fieldKeys.add("yem_reccondition_cd");
        fieldKeys.add("yem_insuranceamt_cd");
        fieldKeys.add("yem_creditamt_cd");
        fieldKeys.add("yem_term_cd");
        fieldKeys.add("yem_sinosurerate_cd");
        fieldKeys.add("yem_insuranceamt_cd");
        fieldKeys.add("yem_creditamtbase");
        fieldKeys.add("yem_insuranceamtbas_cd");
        fieldKeys.add("yem_creditdate1_cd");
        fieldKeys.add("yem_paymentamt1_cd");
        fieldKeys.add("yem_creditdate2_cd");
        fieldKeys.add("yem_paymentamt2_cd");
        fieldKeys.add("yem_giftdecimal");
        fieldKeys.add("yem_es_salesorder_l");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_contractnumbers");
        fieldKeys.add("yem_shipmentnumbers");
        fieldKeys.add("yem_giftproactype");
        fieldKeys.add("yem_tsagerqty");
        fieldKeys.add("yem_giftamt");
        fieldKeys.add("yem_giftamtbase");
        fieldKeys.add("yem_isgiftgive");
        fieldKeys.add("yem_productmodel");
        fieldKeys.add("yem_products");
        fieldKeys.add("yem_contractnumbers_m");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_creditamt_cd");
        fieldKeys.add("yem_usacreditamt_cd");
        fieldKeys.add("yem_ladingdate");
        fieldKeys.add("yem_countpayback");
        fieldKeys.add("yem_amountowed");
        fieldKeys.add("yem_paydate1");
        fieldKeys.add("yem_actualsinkamt_cd");
        fieldKeys.add("yem_paymentamt1_cdbase");
        fieldKeys.add("yem_paydate2");
        fieldKeys.add("yem_paymentamt2_cdbase");
        fieldKeys.add("yem_actualsinkamtba_cd");
        fieldKeys.add("yem_creditremark");
        fieldKeys.add("yem_noticeno");
        fieldKeys.add("yem_tddate");
        fieldKeys.add("yem_corebillid");
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        e.addValidator(new StorageTransAuditValid());
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {

        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            updateReceiptDate(dataEntitie);
            giftAmount(dataEntitie);
            giftSpecialAmount(dataEntitie);
        }
        logistics(dataEntities);
    }


    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] entities = e.getDataEntities();
        for (DynamicObject dataEntitie : entities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            DynamicObject customer = dataEntitie.getDynamicObject("yem_customer");
            DynamicObjectCollection creditDetails = dataEntitie.getDynamicObjectCollection("yem_creditdetail");
            if (YEM.isNotEmpty(customer) && creditDetails.size() > 0) {
                DynamicObject method = TotalUtil.getSettlementMethod(dataEntitie);
                DynamicObject company = dataEntitie.getDynamicObject("yem_company.yem_erporg");
                String swiftCode = TotalUtil.getSwiftCode(dataEntitie);
                DynamicObject csrCreditLine = TotalUtil.getCsrCreditLine(customer, method, company, swiftCode);
                for (DynamicObject creditDetail : creditDetails) {
                    DynamicObject salecontractno = creditDetail.getDynamicObject("yem_salecontractno");
                    if (salecontractno == null) continue;
                    salecontractno = BusinessDataServiceHelper.loadSingle(salecontractno.getPkValue(), salecontractno.getDynamicObjectType().getName());
                    boolean issinosurecon = salecontractno.getBoolean("yem_issinosurecon");
                    if (!issinosurecon) {
                        continue;
                    }
                    if (YEM.isNotEmpty(csrCreditLine)) {
                        DynamicObjectCollection infos = csrCreditLine.getDynamicObjectCollection("yem_im_info");
                        DynamicObject addNew = infos.addNew();
                        addNew.set("yem_storagetransno", dataEntitie);//储运托单号
                        addNew.set("yem_salecontractno", creditDetail.get("yem_salecontractno"));//外销合同号
                        addNew.set("yem_contractcurr", dataEntitie.get("yem_currency"));//结算币别
                        addNew.set("yem_rapstyle", creditDetail.get("yem_quotation_cd"));//结算方式
                        addNew.set("yem_reccondition", creditDetail.get("yem_reccondition_cd"));//收款条件
                        addNew.set("yem_creditamt", creditDetail.get("yem_creditamt_cd"));//信保金额（合同）
                        addNew.set("yem_creditamtuse", creditDetail.get("yem_usacreditamt_cd"));//信保金额（使用）
                        addNew.set("yem_creditdeadline", creditDetail.get("yem_term_cd"));//信用期限
                        addNew.set("yem_creditrate", creditDetail.get("yem_sinosurerate_cd"));//信保费率
                        addNew.set("yem_premium", creditDetail.get("yem_insuranceamt_cd"));//保险费
                        addNew.set("yem_creditamtbase", creditDetail.get("yem_creditamtbase"));//信保金额本位币
                        addNew.set("yem_premiumbase", creditDetail.get("yem_insuranceamtbas_cd"));//保险费金额本位币
                        addNew.set("yem_ladingdate", creditDetail.get("yem_ladingdate"));//提单日期
                        addNew.set("yem_creditdate1_cd", creditDetail.get("yem_creditdate1_cd"));//信保天数1
                        addNew.set("yem_paydate1", creditDetail.get("yem_paydate1"));//应收款日期1
                        // zzs add 2024/1/25
                        addNew.set("yem_countpayback", creditDetail.get("yem_countpayback"));//应回款倒计时
                        addNew.set("yem_paymentamt1_cd", creditDetail.get("yem_paymentamt1_cd"));//收款金额1
                        addNew.set("yem_paymentamt1_cdbase", creditDetail.get("yem_paymentamt1_cdbase"));//收款金额1
                        addNew.set("yem_creditdate2_cd", creditDetail.get("yem_creditdate2_cd"));//信保天数2
                        addNew.set("yem_paydate2", creditDetail.get("yem_paydate2"));//应收款日期2
                        addNew.set("yem_paymentamt2_cd", creditDetail.get("yem_paymentamt2_cd"));//收款金额2
                        addNew.set("yem_paymentamt2_cdbase", creditDetail.get("yem_paymentamt2_cdbase"));//收款金额2
                        addNew.set("yem_actualsinkamt", creditDetail.get("yem_actualsinkamt_cd"));//实际收汇金额
                        addNew.set("yem_actualsinkamtbase", creditDetail.get("yem_actualsinkamtba_cd"));//实际收汇金额本位币
                        // zzs add 2024/1/25
                        addNew.set("yem_amountowed", creditDetail.get("yem_amountowed"));//欠款金额
                        addNew.set("yem_creditremark", creditDetail.getString("yem_creditremark"));//信保备注
                        addNew.set("yem_storagetransid", dataEntitie.getPkValue());//储运托单Id
                        addNew.set("yem_storagetranentryid", creditDetail.getPkValue());//储运托单分录行Id

                        addNew.set("yem_storagetransamt", creditDetail.get("yem_storagetransamt"));//订舱合同金额

                        addNew.set("yem_year_e", creditDetail.get("yem_year_e"));//年份
                        addNew.set("yem_creditstatus_e", creditDetail.get("yem_creditstatus_e"));//投保状态
                    } else {
                        throw new KDBizException(String.format("找不到客户：%s的客户信保额度申请单", customer.getString("name")));
                    }

                }
                BigDecimal decimal = CreditBackFillUtils.calcRemainingAmount(csrCreditLine);
                csrCreditLine.set("yem_balance", decimal);
//                SaveServiceHelper.update(new DynamicObject[]{csrCreditLine});
                OperationResult Operate = OperationServiceHelper.executeOperate("save", csrCreditLine.getDynamicObjectType().getName(), new DynamicObject[]{csrCreditLine}, OperateOption.create());
                if (Operate.isSuccess()) {

                }
            }
        }
    }

    /**
     * 同步至下单平台
     *
     * @param dataEntities
     */
    private void logistics(DynamicObject[] dataEntities) {

        for (DynamicObject dataEntitie : dataEntities) {
            if (!isLastShip(dataEntitie)) {
                continue;
            }
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            Long id = dataEntitie.getLong("yem_corebillid");
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id,billno,yem_sourcebillid"
                    , new QFilter[]{new QFilter("id", QCP.equals, id)});
            if (dynamicObject != null) {
                long aLong = dynamicObject.getLong("yem_sourcebillid");
                DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle("yem_im_clientdemand", "id,billno,yem_orderplatid"
                        , new QFilter[]{new QFilter("id", QCP.equals, aLong)});
                if (loadSingle != null) {
                    String yemOrderplatid = loadSingle.getString("yem_orderplatid");
                    map.put("id", yemOrderplatid);
                    String yemNoticeno = dataEntitie.getString("yem_noticeno");
                    Date yemTddate = dataEntitie.getDate("yem_tddate");
                    map.put("status", "7");
                    map.put("logisticsNo", yemNoticeno);
                    map.put("ladingDate", yemTddate);
                    list.add(map);
                }
            }
            OrderApiUtils.partsorderlist(list);
        }
    }

    /**
     * 更新应回款倒计时，欠款金额
     *
     * @param dataEntity
     */
    public void updateReceiptDate(DynamicObject dataEntity) {
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        for (DynamicObject dynamicObject : collection) {
            Date targetDate = dynamicObject.getDate("yem_paydate1");
            if (targetDate != null) {
                dynamicObject.set("yem_countpayback", CalendarUtils.calcPayBackCount(targetDate));
            }
            // 投保回款金额美元（实际收汇金额）
            BigDecimal actualsinkamt_cd = dynamicObject.getBigDecimal("yem_actualsinkamt_cd");
            // 应收款金额1
            BigDecimal paymentamt1Cd = dynamicObject.getBigDecimal("yem_paymentamt1_cd");
            BigDecimal amountowed = actualsinkamt_cd.subtract(paymentamt1Cd);
            dynamicObject.set("yem_amountowed", amountowed.abs());
        }
//        OperationResult Operate = OperationServiceHelper.executeOperate("save",
//                dataEntity.getDynamicObjectType().getName(),
//                new DynamicObject[]{dataEntity}, OperateOption.create());
        SaveServiceHelper.update(new DynamicObject[]{dataEntity});
    }

    /**
     * @description 审核金额反写到客户资金池 普通规则
     * @author power
     * @time 2023/10/8
     */
    public void giftAmount(DynamicObject dataEntitie) {
        String number = dataEntitie.getString("billno");
//        Long customer = dataEntitie.getLong("yem_customer.id");
        DynamicObject saleorderCustomer = dataEntitie.getDynamicObject("yem_customer");
        Long customer = null;//
        if (saleorderCustomer != null) {
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(saleorderCustomer.getPkValue(), saleorderCustomer.getDynamicObjectType().getName());
            if (dynamicObject != null) {
                DynamicObject groupcusfields = dynamicObject.getDynamicObject("yem_groupcustomers");
                if (groupcusfields != null) {
                    customer = groupcusfields.getLong("id");
                }
            }
        }
        Long org = dataEntitie.getLong("org.id");

        BigDecimal exrate = dataEntitie.getBigDecimal("yem_giftdecimal");
        DynamicObjectCollection giveamounts = dataEntitie.getDynamicObjectCollection("yem_es_salesorder_l");


        for (DynamicObject giveamount : giveamounts) {

            Long products = giveamount.getLong("yem_bd_products.id");
            DynamicObject giftamountss = BusinessDataServiceHelper.loadSingle("yem_im_giftamount",
                    new QFilter[]{new QFilter("yem_groupcusfields", QCP.equals, customer),
                            new QFilter("org", QCP.equals, org),
                            new QFilter("yem_bd_products", QCP.equals, products)});


            Long id = giveamount.getLong("id");
            String contractnumbers = giveamount.getString("yem_contractnumbers");
            String shipmentnumbers = giveamount.getString("yem_shipmentnumbers");
            Long giftproactype = giveamount.getLong("yem_giftproactype.id");
            int tsagerqty = giveamount.getInt("yem_tsagerqty");
            BigDecimal giftamt = giveamount.getBigDecimal("yem_giftamt");
            BigDecimal giftamtbase = giveamount.getBigDecimal("yem_giftamtbase");
            if (giftamountss != null) {
                DynamicObjectCollection entryentitys = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
                int row = 0;
                for (DynamicObject entryentity : entryentitys) {
                    String yem_originno = entryentity.getString("yem_originno");
                    if (contractnumbers.equals(yem_originno)) {
                        DynamicObjectCollection enablegiftinfor = entryentity.getDynamicObjectCollection("yem_enablegiftinfor");
                        DynamicObject newEntryEntity = enablegiftinfor.addNew();

                        //外销合同号
                        newEntryEntity.set("yem_etctnum", contractnumbers);
                        //出运明细单号
                        newEntryEntity.set("yem_stdsnum", shipmentnumbers);
                        //储运托单订单号
                        newEntryEntity.set("yem_sernorrnum", number);
                        //机型
                        newEntryEntity.set("yem_giftproactype", giftproactype);
                        //台式
                        newEntryEntity.set("yem_tsagerqty", tsagerqty);
                        //可用礼品金额
                        newEntryEntity.set("yem_sneygiftenable", giftamt);
                        //汇率
                        newEntryEntity.set("yem_exchangerate", exrate);
                        //可用礼品本位币金额
                        newEntryEntity.set("yem_crsygiftenable", giftamtbase);
                        //储运分录内码
                        newEntryEntity.set("yem_im_giftapplyides", id);


                    }
                    entryentitys.set(row, entryentity);
                    row++;
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{giftamountss});
            GiftAmount.Calculate(customer, org, products);
        }
    }


    /**
     * @description 审核金额反写到客户资金池 特殊规则
     * @author power
     * @time 2023/10/10
     */
    public void giftSpecialAmount(DynamicObject dataEntitie) {
//        Long customer = dataEntitie.getLong("yem_customer.id");
        DynamicObject saleorderCustomer = dataEntitie.getDynamicObject("yem_customer");
        Long customer = null;//
        if (saleorderCustomer != null) {
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(saleorderCustomer.getPkValue(), saleorderCustomer.getDynamicObjectType().getName());
            if (dynamicObject != null) {
                DynamicObject groupcusfields = dynamicObject.getDynamicObject("yem_groupcustomers");
                if (groupcusfields != null) {
                    customer = groupcusfields.getLong("id");
                }
            }
        }
        Long org = dataEntitie.getLong("org.id");
        DynamicObjectCollection materialinfos = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal exrate = dataEntitie.getBigDecimal("yem_giftdecimal");
        Long id = dataEntitie.getLong("id");

        DynamicObject[] storagetrans = BusinessDataServiceHelper.load("yem_es_storagetrans",
                "yem_es_materialinfo.yem_productmodel,yem_es_materialinfo.yem_qty,billno," +
                        "yem_es_materialinfo.yem_contractnumbers_m",
                new QFilter[]{
                        new QFilter("billstatus", QCP.equals, "C"),
                        new QFilter("yem_customer", QCP.equals, customer),
                        new QFilter("id", QCP.not_equals, id),
                        new QFilter("org", QCP.equals, org),});

        Object[] pk = new Object[storagetrans.length];
        int rows = 0;
        for (DynamicObject dt : storagetrans) {
            pk[rows] = dt.getPkValue();
            rows++;
        }
        if (materialinfos != null) {
            for (int i = 0; i < materialinfos.size(); i++) {
                DynamicObject materialinfo = materialinfos.get(i);

                String isgiftgive = materialinfo.getString("yem_isgiftgive");
                if (materialinfo.getDynamicObject("yem_productmodel") != null) {
                    Long productmodels = materialinfo.getLong("yem_productmodel.yem_products.id");
                    Long products = materialinfo.getLong("yem_products.id");


                    DynamicObject giftamountss = BusinessDataServiceHelper.loadSingle("yem_im_giftamount",
                            new QFilter[]{new QFilter("yem_groupcusfields", QCP.equals, customer),
                                    new QFilter("org", QCP.equals, org),
                                    new QFilter("yem_bd_products", QCP.equals, products)});


                    if (giftamountss != null) {
                        if ("A".equals(isgiftgive)) {
                            if (StringUtil.isNotEmpty(materialinfo.getString("yem_contractnumbers_m"))) {
                                String conBillno = materialinfo.getString("yem_contractnumbers_m");
                                DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "yem_isnewagent",
                                        new QFilter[]{new QFilter("billno", QCP.equals, conBillno),});
                                if (data != null) {
                                    String isnewagent = data.getString("yem_isnewagent");

                                    DynamicObject giftruless = BusinessDataServiceHelper.loadSingle("yem_bd_giftrules",
                                            new QFilter[]{
                                                    new QFilter("status", QCP.equals, "C"),
                                                    new QFilter("yem_classify", QCP.equals, products),
                                                    new QFilter("yem_ynnewdealer", QCP.equals, isnewagent)
                                            });

                                    //是经销商
                                    if ("A".equals(isnewagent)) {
                                        if (giftruless != null) {
                                            for (DynamicObject giftrules : giftruless.getDynamicObjectCollection("yem_bd_giftrules_b")) {
                                                BigDecimal sumqty = BigDecimal.ZERO;
                                                BigDecimal masqty = BigDecimal.ZERO;
                                                BigDecimal yem_qtys = BigDecimal.ZERO;
                                                for (DynamicObject giftrule : giftrules.getDynamicObjectCollection("yem_bd_giftrules_c")) {
                                                    Long producttypea = giftrule.getLong("yem_producttypea.id");
                                                    if (producttypea.equals(productmodels)) {
                                                        yem_qtys = materialinfo.getBigDecimal("yem_qty");
                                                    }

                                                    for (int j = i + 1; j < materialinfos.size(); j++) {
                                                        DynamicObject materialinfoj = materialinfos.get(j);
                                                        String isgiftgivej = materialinfoj.getString("yem_isgiftgive");
                                                        if ("A".equals(isgiftgivej)) {
                                                            Long productsj = materialinfoj.getLong("yem_products.id");
                                                            String conBillnoj = materialinfoj.getString("yem_contractnumbers_m");
                                                            if (materialinfoj.getDynamicObject("yem_productmodel") != null) {
                                                                Long productmodelsj = materialinfoj.getLong("yem_productmodel.yem_products.id");
                                                                String name = materialinfoj.getString("yem_productmodel.yem_products.name");
                                                                String names = materialinfo.getString("yem_productmodel.yem_products.name");
                                                                if (conBillno.equals(conBillnoj)) {
                                                                    if (products.equals(productsj)) {
                                                                        if (productmodelsj.equals(producttypea)) {
                                                                            BigDecimal yem_qty = materialinfoj.getBigDecimal("yem_qty");
                                                                            masqty = masqty.add(yem_qty);
                                                                        }
                                                                    }
                                                                }
                                                                if (!conBillno.equals(conBillnoj)) {
                                                                    DynamicObject datafo = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "yem_isnewagent",
                                                                            new QFilter[]{new QFilter("billno", QCP.equals, conBillnoj),});
                                                                    if (datafo != null) {
                                                                        String isnewagentfo = data.getString("yem_isnewagent");
                                                                        if ("A".equals(isnewagentfo)) {
                                                                            if (products.equals(productsj)) {
                                                                                if (productmodelsj.equals(producttypea)) {
                                                                                    BigDecimal yem_qty = materialinfoj.getBigDecimal("yem_qty");
                                                                                    masqty = masqty.add(yem_qty);
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }


                                                    if (storagetrans != null && storagetrans.length > 0) {
                                                        DynamicObject[] load = BusinessDataServiceHelper.load(pk, storagetrans[0].getDynamicObjectType());
                                                        for (DynamicObject loads : load) {
                                                            DynamicObjectCollection yem_es_materialinfo = loads.getDynamicObjectCollection("yem_es_materialinfo");
                                                            for (DynamicObject yem_es_materialinfos : yem_es_materialinfo) {
                                                                if (yem_es_materialinfos.getDynamicObject("yem_productmodel") != null) {
                                                                    Long maproduct = yem_es_materialinfos.getDynamicObject("yem_productmodel").getLong("yem_products.id");
                                                                    if (producttypea.equals(maproduct)) {
                                                                        String conBillnofo = yem_es_materialinfos.getString("yem_contractnumbers_m");
                                                                        DynamicObject datafo = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "yem_isnewagent",
                                                                                new QFilter[]{new QFilter("billno", QCP.equals, conBillnofo),});
                                                                        if (datafo != null) {
                                                                            String isnewagentfo = data.getString("yem_isnewagent");
                                                                            if ("A".equals(isnewagentfo)) {

                                                                                BigDecimal yem_qty = yem_es_materialinfos.getBigDecimal("yem_qty");
                                                                                sumqty = sumqty.add(yem_qty);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                BigDecimal yem_qtyb = giftrules.getBigDecimal("yem_qtyb");
//                                        sumqty =masqty.add(sumqty);
                                                BigDecimal qtys = yem_qtys.add(masqty.add(sumqty));
                                                if (qtys.compareTo(yem_qtyb) == 1 && masqty.compareTo(yem_qtyb) < 1) {
                                                    BigDecimal giveamo = giftrules.getBigDecimal("yem_giveamob");
                                                    BigDecimal giveamobase = giveamo.multiply(exrate);
                                                    giveamo = giveamo.setScale(2, BigDecimal.ROUND_HALF_UP);
                                                    giveamobase = giveamobase.setScale(2, BigDecimal.ROUND_HALF_UP);
                                                    if (giftamountss != null) {
                                                        DynamicObjectCollection entryentitys = giftamountss.getDynamicObjectCollection("yem_im_giftamount_o");
                                                        int row = 0;
                                                        for (DynamicObject entryentity : entryentitys) {
                                                            if (giveamo.compareTo(entryentity.getBigDecimal("yem_originamt")) == 0 && "D".equals(entryentity.getString("yem_origintype"))) {
                                                                entryentity.set("yem_entrygiftenable", giveamo);
                                                                entryentity.set("yem_sneycrgiftenable", giveamobase);
                                                                entryentity.set("seq", entryentity.getInt("seq"));
                                                            }
                                                            entryentity.set("seq", row);
//                                                            entryentitys.set(row,entryentity);
                                                            row++;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
//                                SaveServiceHelper.save(new DynamicObject[] {giftamountss});
//                                GiftAmount.Calculate(customer,org,products);
                            }
                        }
                        SaveServiceHelper.save(new DynamicObject[]{giftamountss});
                        GiftAmount.Calculate(customer, org, products);
                    }
                }
            }
        }
        for (DynamicObject ma : materialinfos) {

            Long products = ma.getLong("yem_products.id");
            GiftAmount.Calculate(customer, org, products);
        }
    }


}
