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

import com.yem.tws.common1.BigDecimalUtils;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.form.IFormView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import org.apache.commons.lang3.ArrayUtils;

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

/**
 * @author 张立攀
 * @version 1.0
 * @description
 * @date 2023-08-09 18:28
 */
public class ClientUtils {
    /**
     * 明细信息 获取标准价按钮
     */
    public static void getPriceNew(DynamicObject datas, IDataModel models, IFormView view) {
        String yem_billtype = datas.getString("yem_billtype.number");
        DynamicObject dataEntity = models.getDataEntity(true);
        String Entityname = dataEntity.getDataEntityType().getName();
        BigDecimal yem_exrate = dataEntity.getBigDecimal("yem_exrate");
        DynamicObjectCollection detailedinfor = getTypeColl(models);
        //提示
        StringBuffer info = new StringBuffer();
        //配件物料查询出的 价格
        List<DynamicObject> pjDatas = new ArrayList<DynamicObject>();
        List<DynamicObject> selectDatas = new ArrayList<DynamicObject>();
        int rowInfo = 0;
        boolean flag = false;
        for (DynamicObject temp : detailedinfor) {
            if (Entityname.equals("yem_es_xsalesorder")) {
                String yem_linetype = temp.getString("yem_linetype");
                if (!yem_linetype.equals("add")) {
                    rowInfo++;
                    continue;
                }
            }
            //多功能配置分录行获取
            DynamicObjectCollection multiconfig = null;
            DynamicObject currentEntry = detailedinfor.get(rowInfo);
            if (currentEntry != null) {
                multiconfig = currentEntry.getDynamicObjectCollection("yem_multiconfig");
            }
            //所有加装、可替换等数据集合
            Map<Long, BigDecimal> dataMap = new HashMap<Long, BigDecimal>();
            List<QFilter> list = new ArrayList<QFilter>();
            DynamicObject spmodel = temp.getDynamicObject("yem_productmodel");
            DynamicObject materials = temp.getDynamicObject("yem_materiel");
            DynamicObject yemBdProducts = dataEntity.getDynamicObject("yem_bd_products");
            String businesssort = temp.getString("yem_businesssort");
            if (spmodel == null && "Z".equals(businesssort)) {
                info.append("明细信息第").append(rowInfo + 1).append("行【基础机型】不能为空!\r\n");
                selectDatas.add(null);
                rowInfo++;
                continue;
            }
            if ("P".equals(businesssort) && materials == null) {
                info.append("明细信息第").append(rowInfo + 1).append("行【物料编码】不能为空!\r\n");
                selectDatas.add(null);
                rowInfo++;
                continue;
            }
            if ("P".equals(businesssort) && yemBdProducts == null) {
                info.append("产品分类不能为空!\r\n");
                selectDatas.add(null);
                rowInfo++;
                continue;
            }
            long products = 0L;
            if (spmodel != null) {
                products = spmodel.getLong("yem_products.id");
            }
            String yemBdProductsid  = "";
            if (yemBdProducts!=null){
                yemBdProductsid = yemBdProducts.getString("number");
            }
            if ("P".equals(businesssort)){
                if ("CC".equals(yemBdProducts.getString("number"))){//叉车
                    yemBdProductsid= "CCPJ";
                }else if ("ZZJ".equals(yemBdProducts.getString("number"))){//装载机
                    yemBdProductsid= "ZZJPJ";
                } else if ("TLJ".equals(yemBdProducts.getString("number"))) {//拖拉机
                    yemBdProductsid= "TLJPJ";
                }
            }
            //客户需求单整机 -整机分录行
//            if (("yem_im_clientdeman_zj".equals(yem_billtype) || "yem_im_inclientdeman_zj".equals(yem_billtype) || ("yem_es_salesorder_ZJ".equals(yem_billtype)) || "yem_es_salesorder_nmzj".equals(yem_billtype)) && "Z".equals(businesssort)) {
            if (("yem_im_clientdeman_zj".equals(yem_billtype) || "yem_im_inclientdeman_zj".equals(yem_billtype) || ("yem_es_salesorder_ZJ".equals(yem_billtype)) || "yem_es_salesorder_nmzj".equals(yem_billtype) || "yem_es_xsalesorder_zj".equals(yem_billtype) | "yem_es_xsalesorder_nmzj".equals(yem_billtype)) && "Z".equals(businesssort)) {
                list.add(new QFilter("yem_bd_products.id", QCP.equals, products));
                list.add(new QFilter("billstatus", QCP.equals, "C"));
                list.add(new QFilter("yem_billtype.number", QCP.equals, "yem_pricelibrary_ZJ"));
                list.add(new QFilter("yem_cancelstatus",QCP.equals,"0"));
//                list.add(new QFilter("yem_productclass.number",QCP.equals,yemBdProductsid));
                //读取价格库数据
                DynamicObject yem_pricelibrary = null;
                if (multiconfig != null && !multiconfig.isEmpty()) {
                    yem_pricelibrary = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", list.toArray(new QFilter[0]));
                } else {
                    yem_pricelibrary = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", list.toArray(new QFilter[0]));
                }
                if (yem_pricelibrary != null) {
                    //多功能配置分录行无数据 则跳过查询价格库
                    if (multiconfig != null && !multiconfig.isEmpty()) {
                        DynamicObjectCollection optional = yem_pricelibrary.getDynamicObjectCollection("yem_optional");
                        DynamicObjectCollection replaceable = yem_pricelibrary.getDynamicObjectCollection("yem_replaceable");
                        DynamicObjectCollection retrofitting = yem_pricelibrary.getDynamicObjectCollection("yem_retrofitting");
                        if (optional != null && !optional.isEmpty()) {
                            for (DynamicObject temp1 : optional) {
                                // 状态可用
                                if ("A".equals(temp1.getString("yem_disabledstate"))) {
                                    dataMap.put(temp1.getLong("yem_entryid_o"), temp1.getBigDecimal("yem_salesmarkup_o"));
                                }
                            }
                        }
                        if (replaceable != null && !replaceable.isEmpty()) {
                            for (DynamicObject temp1 : replaceable) {
                                // 状态可用
                                if ("A".equals(temp1.getString("yem_disabledstate1"))) {
                                    dataMap.put(temp1.getLong("yem_entryid_re"), temp1.getBigDecimal("yem_salesmarkup_re"));
                                }
                            }
                        }
                        if (retrofitting != null && !retrofitting.isEmpty()) {
                            for (DynamicObject temp1 : retrofitting) {
                                // 状态可用
                                if ("A".equals(temp1.getString("yem_disabledstate2"))) {
                                    dataMap.put(temp1.getLong("yem_entryid_rt"), temp1.getBigDecimal("yem_salesmarkup_rt"));
                                }
                            }
                        }
                        setPriceNow(multiconfig, dataMap, rowInfo, models);
                    }
                    DynamicObjectCollection yem_basicmodel = yem_pricelibrary.getDynamicObjectCollection("yem_basicmodel");
                    if (yem_basicmodel != null && !yem_basicmodel.isEmpty()) {
                        for (DynamicObject dynamicObject : yem_basicmodel) {
                            Long model = dynamicObject.getLong("yem_model.id");
                            assert spmodel != null;
                            Long spmodelId = spmodel.getLong("id");
                            if (model.equals(spmodelId)) {
                                selectDatas.add(dynamicObject);
                                fobPriceAdd(detailedinfor, yem_exrate, rowInfo, dynamicObject, models);
                            }
                        }
                        if (selectDatas.isEmpty()) {
                            info.append("明细信息 第").append(rowInfo + 1).append("行未获取到标准价，请及时询价！\r\n");
                        }
                    } else {
                        info.append("明细信息 第").append(rowInfo + 1).append("行未获取到标准价，请及时询价！\r\n");
                    }


                } else {
                    info.append("明细信息 第").append(rowInfo + 1).append("行未获取到标准价，请及时询价！\r\n");
                }

            }
            //客户需求单整机 -配件分录行
            else if (("yem_im_clientdeman_zj".equals(yem_billtype) || "yem_im_inclientdeman_zj".equals(yem_billtype) || ("yem_es_salesorder_ZJ".equals(yem_billtype)) || "yem_es_salesorder_nmzj".equals(yem_billtype) || "yem_es_xsalesorder_zj".equals(yem_billtype) || "yem_es_xsalesorder_nmzj".equals(yem_billtype)) && "P".equals(businesssort)) {
//              else if (("yem_im_clientdeman_zj".equals(yem_billtype) || "yem_im_inclientdeman_zj".equals(yem_billtype) || ("yem_es_salesorder_ZJ".equals(yem_billtype)) || "yem_es_salesorder_nmzj".equals(yem_billtype)) && "P".equals(businesssort)) {
                pjFindPrice(yem_exrate, info, pjDatas, rowInfo, list, materials, models, yemBdProductsid);
            }
            //客户需求单配件

//            else if (("yem_im_clientdema_pj".equals(yem_billtype) || "yem_im_inclientdema_pj".equals(yem_billtype) || "yem_es_salesorder_PJ".equals(yem_billtype) || "yem_es_salesorder_nmpj".equals(yem_billtype)) && "P".equals(businesssort)) {
            else if (("yem_im_clientdema_pj".equals(yem_billtype) || "yem_im_inclientdema_pj".equals(yem_billtype) || "yem_es_salesorder_PJ".equals(yem_billtype) || "yem_es_salesorder_nmpj".equals(yem_billtype) || "yem_es_xsalesorder_pj".equals(yem_billtype) || "yem_es_xsalesorder_nmpj".equals(yem_billtype)) && "P".equals(businesssort)) {
                pjFindPrice(yem_exrate, info, pjDatas, rowInfo, list, materials, models, yemBdProductsid);
            }
            rowInfo++;
        }
        //弹窗提示
        if (info.length() > 0) {
            view.showMessage(info.toString());
        }

    }

    /**
     * 获取标准价中  计算fob价(整机分录行)
     */
    public static void fobPriceAdd(DynamicObjectCollection dy, BigDecimal yem_exrate, int rowInfo, DynamicObject dynamicObject, IDataModel models) {
        //fob单价计算
        DynamicObject dataEntity = models.getDataEntity(true);
        String yembilltype = dataEntity.getString("yem_billtype.number");
        BigDecimal pricefob = BigDecimal.ZERO;
        if ("yem_im_inclientdeman_zj".equals(yembilltype) || "yem_es_salesorder_nmzj".equals(yembilltype) || "yem_es_xsalesorder_nmzj".equals(yembilltype)) {
            pricefob = dynamicObject.getBigDecimal("yem_foreigntradeprice");
        }
        if ("yem_im_clientdeman_zj".equals(yembilltype) || "yem_es_salesorder_ZJ".equals(yembilltype) || "yem_es_xsalesorder_zj".equals(yembilltype)) {
            pricefob = dynamicObject.getBigDecimal("yem_pricefob");
        }

        //计算多功能配置页签  标准销售价价计算总额
        DynamicObject currEntry = dy.get(rowInfo);
        if (currEntry != null) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            DynamicObjectCollection dc = currEntry.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal marketraiseprice = di.getBigDecimal("yem_marketraisepribase");
                BigDecimal unitsetnumber = di.getBigDecimal("yem_unitsetnumber");
                fobPrice = fobPrice.add(marketraiseprice.multiply(unitsetnumber));
            }
            BigDecimal fobPriceAmount = fobPrice.add(pricefob);
            models.setValue("yem_fobprice", fobPriceAmount, rowInfo);
            if ("yem_es_salesorder".equals(yembilltype) || "yem_es_xsalesorder".equals(yembilltype)) {
                models.setValue("yem_exwrmbprice", fobPriceAmount, rowInfo);
            }

//            if(yem_exrate.compareTo(BigDecimal.ZERO) != 0){
//                models.setValue("yem_price",(fobPrice.add(pricefob)).divide(yem_exrate, RoundingMode.HALF_UP), rowInfo);
//            }

        }
        BigDecimal foreigntradeprice = dynamicObject.getBigDecimal("yem_foreigntradeprice");
        models.setValue("yem_standardprice", pricefob, rowInfo);
        models.setValue("yem_foreigntraprice", foreigntradeprice, rowInfo);
    }

    /**
     * 外销合同 多功能配置删除行   计算fob价
     */

    public static void deleteRowFobPriceAdd(IDataModel models) {
        DynamicObject dataEntity = models.getDataEntity(true);
        //fob单价计算

        BigDecimal yem_exrate = dataEntity.getBigDecimal("yem_exrate");
        //计算多功能配置页签  标准销售价价计算总额
        int rowInfo = models.getEntryCurrentRowIndex("yem_es_materialinfo");
        DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        DynamicObject currEntry = null;
        if (materialinfo != null && materialinfo.size() > rowInfo) {
            currEntry = materialinfo.get(rowInfo);
        }

        if (currEntry != null) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            BigDecimal pricefob = currEntry.getBigDecimal("yem_standardprice");
            DynamicObjectCollection dc = currEntry.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal marketraiseprice = di.getBigDecimal("yem_marketraisepribase");
                BigDecimal unitsetnumber = di.getBigDecimal("yem_unitsetnumber");
                fobPrice = fobPrice.add(marketraiseprice.multiply(unitsetnumber));
            }
            BigDecimal fobPriceAmount = fobPrice.add(pricefob);
            models.setValue("yem_fobprice", fobPriceAmount, rowInfo);
            String yembilltype = models.getDataEntityType().getName();
            if ("yem_es_salesorder".equals(yembilltype)) {
                models.setValue("yem_exwrmbprice", fobPriceAmount, rowInfo);
            }
            if (yem_exrate.compareTo(BigDecimal.ZERO) != 0) {
                models.setValue("yem_price", (fobPrice.add(pricefob)).divide(yem_exrate, RoundingMode.HALF_UP), rowInfo);
            }

        }
    }

    /**
     * 客户需求单 多功能配置删除行   计算fob价
     */

    public static void deleteRowFobPriceAddkh(IDataModel models) {
        DynamicObject dataEntity = models.getDataEntity(true);
        //fob单价计算

        BigDecimal yem_exrate = dataEntity.getBigDecimal("yem_exrate");
        //计算多功能配置页签  标准销售价价计算总额
        int rowInfo = models.getEntryCurrentRowIndex("yem_im_detailedinfor");
        DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_im_detailedinfor");
        DynamicObject currEntry = null;
        if (materialinfo != null && materialinfo.size() > rowInfo) {
            currEntry = materialinfo.get(rowInfo);
        }

        if (currEntry != null) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            BigDecimal pricefob = currEntry.getBigDecimal("yem_standardprice");
            DynamicObjectCollection dc = currEntry.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal marketraiseprice = di.getBigDecimal("yem_marketraisepribase");
                BigDecimal unitsetnumber = di.getBigDecimal("yem_unitsetnumber");
                fobPrice = fobPrice.add(marketraiseprice.multiply(unitsetnumber));
            }
            BigDecimal fobPriceAmount = fobPrice.add(pricefob);
            models.setValue("yem_fobprice", fobPriceAmount, rowInfo);
            String yembilltype = models.getDataEntityType().getName();
            if ("yem_es_salesorder".equals(yembilltype)) {
                models.setValue("yem_exwrmbprice", fobPriceAmount, rowInfo);
            }
            if (yem_exrate.compareTo(BigDecimal.ZERO) != 0) {
                models.setValue("yem_price", (fobPrice.add(pricefob)).divide(yem_exrate, RoundingMode.HALF_UP), rowInfo);
            }

        }
    }

    /**
     * 获取标准价中  给当前行标准销售加价赋值
     */
    public static void setPriceNow(DynamicObjectCollection multiconfig, Map<Long, BigDecimal> dataMap, int rowInfo, IDataModel models) {
        int multiconfigIndex = 0;
        if (multiconfig != null && multiconfig.size() > 0) {
            for (DynamicObject dc : multiconfig) {
                long configentryid = dc.getLong("yem_configentryid");
                BigDecimal configentry = dataMap.get(configentryid) == null ? BigDecimal.ZERO : dataMap.get(configentryid).setScale(2);
                models.setValue("yem_marketraisepribase", configentry, multiconfigIndex, rowInfo);
                multiconfigIndex++;
            }
        }
    }

    /**
     * 获取标准价中  配件价格获取
     */
    public static void pjFindPrice(BigDecimal yem_exrate, StringBuffer info, List<DynamicObject> pjDatas, int rowInfo, List<QFilter> list, DynamicObject materials, IDataModel models, String yemBdProducts) {
        if (materials != null && yemBdProducts != null) {
            long materialId = materials.getLong("id");
            list.add(new QFilter("billstatus", QCP.equals, "C"));
            list.add(new QFilter("yem_billtype.number", QCP.equals, "yem_pricelibrary_PJ"));
            list.add(new QFilter("yem_accessory.yem_material.id", QCP.equals, materialId));
            list.add(new QFilter("yem_productclass.number",QCP.equals,yemBdProducts));
            //DynamicObject yem_material = BusinessDataServiceHelper.loadSingle("yem_pricelibrary","yem_accessory.yem_material,yem_accessory.yem_standsalesprice", list.toArray(new QFilter[0]));
            DynamicObject[] yem_material = BusinessDataServiceHelper.load("yem_pricelibrary", "billno,yem_accessory.yem_material,yem_accessory.yem_standsalesprice,auditdate", list.toArray(new QFilter[0]));
            DynamicObject nowMaterial = null;
            if (yem_material != null && yem_material.length == 1) {
                nowMaterial = yem_material[0];
            } else {
                Map<Date, Object> map = new TreeMap<Date, Object>(
                        new Comparator<Date>() {
                            @Override
                            public int compare(Date obj1, Date obj2) {
                                // 降序排序
                                return obj2.compareTo(obj1);
                            }
                        });
                for (DynamicObject dt : yem_material) {
                    Date yemBizdate = dt.getDate("auditdate");
                    if (yemBizdate != null) {
                        map.put(yemBizdate, dt);
                    }
                }
                Set<Date> keySet = map.keySet();
                Iterator<Date> iter = keySet.iterator();

                while (iter.hasNext()) {
                    Date key = iter.next();
                    nowMaterial = (DynamicObject) map.get(key);

                    break;
                }
            }

            if (nowMaterial != null) {
                DynamicObjectCollection yem_accessory = nowMaterial.getDynamicObjectCollection("yem_accessory");
                if (yem_accessory != null && yem_accessory.size() > 0) {
                    for (DynamicObject dm : yem_accessory) {
                        long yem_materials = dm.getLong("yem_material.id");//价格库物料内码
                        if (materialId == yem_materials) {
                            pjDatas.add(dm);
                            if (dm != null) {
                                models.setValue("yem_fobprice", dm.getBigDecimal("yem_standsalesprice"), rowInfo);
                                String yembilltype = models.getDataEntityType().getName();
                                if ("yem_es_salesorder".equals(yembilltype) || "yem_es_xsalesorder".equals(yembilltype)) {
                                    models.setValue("yem_exwrmbprice", dm.getBigDecimal("yem_standsalesprice"), rowInfo);
                                }
                                if (yem_exrate.compareTo(BigDecimal.ZERO) != 0) {
                                    models.setValue("yem_safobprice", roundUpNew(dm.getBigDecimal("yem_standsalesprice").divide(yem_exrate, RoundingMode.HALF_UP)), rowInfo);
                                }
                            }
                        }
                    }
                } else {
                    info.append("明细信息 第" + (rowInfo + 1) + "行未获取到标准价，请及时询价！\r\n");
                }
                //价格库有数据 但未查询到匹配值
                if (pjDatas.size() == 0) {
                    info.append("明细信息 第" + (rowInfo + 1) + "行未获取到标准价，请及时询价！\r\n");
                }
            } else {
                info.append("明细信息 第" + (rowInfo + 1) + "行未获取到标准价，请及时询价！\r\n");
            }
        }
    }

    /**
     * 商品明细分录FOB单价（EXW单价）=SUM（标准销售加价*单台数量）+父单据体的标配FOB（青岛）价
     */


    public static void fobPriceAdd(IDataModel model, DynamicObjectCollection dy) {
        int rowNow = 0;
        for (DynamicObject temp : dy) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            DynamicObjectCollection dc = temp.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal unitsetamountbase = di.getBigDecimal("yem_unitsetamountbase");
                fobPrice = fobPrice.add(unitsetamountbase);
            }
            String businesssort = temp.getString("yem_businesssort");
            if ("Z".equals(businesssort)) {
                BigDecimal standardprice = temp.getBigDecimal("yem_standardprice");
                model.setValue("yem_fobprice", fobPrice.add(standardprice), rowNow);
            }
            rowNow++;
        }
    }

    /**
     * 计算FOB金额
     */

    public static void countFobAmt(IDataModel model, int rowNow) {
        BigDecimal needqty = (BigDecimal) model.getValue("yem_qty", rowNow);
        BigDecimal fobprice = (BigDecimal) model.getValue("yem_fobprice", rowNow);
        model.setValue("yem_fobamount", needqty.multiply(fobprice), rowNow);

    }


    /**
     * 计算 销售FOB标配青岛价
     */
    public static void countFobAmtSale(IDataModel model, int rowNow) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        BigDecimal standardprice = (BigDecimal) model.getValue("yem_standardprice", rowNow);
        if (exrate.compareTo(BigDecimal.ZERO) != 0) {
            model.setValue("yem_sastandardprice", roundUp(standardprice.divide(exrate, BigDecimal.ROUND_HALF_UP)), rowNow);
        }
    }

    /**
     * 计算 销售FOB标配青岛单价（人民币）
     */
    public static void countFobAmtSaleRMB(IDataModel model, int rowNow) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        BigDecimal sastandardprice = (BigDecimal) model.getValue("yem_sastandardprice", rowNow);
        model.setValue("yem_sastandardpricesa", sastandardprice.multiply(exrate), rowNow);
    }

    /**
     * 计算销售fob单价 结算(可优化)
     */
    public static void addSaPrice(IDataModel model, DynamicObjectCollection dy) {
        int rowNow = 0;
        for (DynamicObject temp : dy) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            String businesssort = temp.getString("yem_businesssort");
            DynamicObjectCollection dc = temp.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal unitsetamount = di.getBigDecimal("yem_unitsetamount");
                fobPrice = fobPrice.add(unitsetamount);
            }
            BigDecimal sastandardprice = temp.getBigDecimal("yem_sastandardprice");
//            if("P".equals(businesssort)){
//                model.setValue("yem_safobprice",roundUpNew(fobPrice.add(sastandardprice)), rowNow);
//            }else {
            //            }
            if ("Z".equals(businesssort)) {
                model.setValue("yem_safobprice", fobPrice.add(sastandardprice), rowNow);
            }


            rowNow++;
        }

    }

    /**
     * 计算销售fob单价人民币
     */
    public static void addSaPriceRMB(IDataModel model, int rowNow) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate", rowNow);
        BigDecimal safobprice = (BigDecimal) model.getValue("yem_safobprice", rowNow);
        model.setValue("yem_safobpricebase", exrate.multiply(safobprice), rowNow);
    }

    /**
     * 计算销售FOB金额
     */
    public static void addSaPriceSale(IDataModel model, int rowNow) {
        BigDecimal needqty = (BigDecimal) model.getValue("yem_qty", rowNow);
        BigDecimal safobprice1 = (BigDecimal) model.getValue("yem_safobprice", rowNow);
        model.setValue("yem_safobamount", safobprice1.multiply(needqty), rowNow);
    }

    /**
     * 计算销售FOB金额（人民币）
     */
    public static void addSaPriceSaleRMB(IDataModel model, int rowNow) {
        BigDecimal safobamount = (BigDecimal) model.getValue("yem_safobamount", rowNow);
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate", rowNow);
        model.setValue("yem_safobamountbase", safobamount.multiply(exrate), rowNow);
    }


    /**
     * 实际整车单价
     *
     * 实际整车单价 = 实际整车金额 / 数量
     */
    public static void countRealCatPrice(IDataModel model, int rowNow) {
        boolean ifgift = (boolean) model.getValue("yem_ifgift", rowNow);
        if (!ifgift) {
//            BigDecimal sapriceclausebase = (BigDecimal) model.getValue("yem_sapricepriceclause", rowNow);
//            BigDecimal pricefieldacc = (BigDecimal) model.getValue("yem_pricefieldaccba", rowNow);
            BigDecimal truecaramt = (BigDecimal) model.getValue("yem_truecaramt", rowNow); // 实际整车金额
            BigDecimal qty = (BigDecimal) model.getValue("yem_qty", rowNow);
            model.setValue("yem_truecarprice", BigDecimalUtils.div(truecaramt, qty, 2), rowNow);
        } else {
            model.setValue("yem_truecarprice", null, rowNow);
        }
    }

    /**
     * 实际整车金额
     *
     * 实际整车金额 = 销售金额价格条款 - 资源配件金额
     */

    public static void countRealCatAmount(IDataModel model, int rowNow) {
        boolean ifgift = (boolean) model.getValue("yem_ifgift", rowNow);
        if (!ifgift) {
            BigDecimal saamtpriceclause = (BigDecimal) model.getValue("yem_saamtpriceclause", rowNow); // 销售金额（价格条款）
            BigDecimal pricefieldaccamt = (BigDecimal) model.getValue("yem_pricefieldaccamt", rowNow); // 资源配件金额

//            BigDecimal truecarprice = (BigDecimal) model.getValue("yem_truecarprice", rowNow);
//            BigDecimal needqty = (BigDecimal) model.getValue("yem_qty", rowNow);
            model.setValue("yem_truecaramt", saamtpriceclause.subtract(pricefieldaccamt), rowNow);
        } else {
            model.setValue("yem_truecaramt", null, rowNow);
        }
        countRealCatPrice(model, rowNow);
    }

    /***
     * 实际整车单价人民币
     */
    public static void countRealCatPriceRMB(IDataModel model, int rowNow) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate", rowNow);
        BigDecimal truecarprice = (BigDecimal) model.getValue("yem_truecarprice", rowNow);
        model.setValue("yem_truecarpriceba", truecarprice.multiply(exrate), rowNow);
    }


    /***
     * 实际整车金额人民币
     */
    public static void countRealCatAmountRMB(IDataModel model, int rowNow) {
        BigDecimal qty = (BigDecimal) model.getValue("yem_qty", rowNow);
        BigDecimal truecarpriceba = (BigDecimal) model.getValue("yem_truecarpriceba", rowNow);
        model.setValue("yem_truecaramtba", truecarpriceba.multiply(qty), rowNow);
    }

    /**
     * 计算 资源配件单价
     */
    public static void addPjSourcePrice(IDataModel model, int rowNow) {
        boolean ifgift = (boolean) model.getValue("yem_ifgift", rowNow);
        if (!ifgift) {
            BigDecimal qty = (BigDecimal) model.getValue("yem_qty", rowNow);
            BigDecimal pricefieldaccamt = (BigDecimal) model.getValue("yem_pricefieldaccamt", rowNow);
            if (qty.compareTo(BigDecimal.ZERO) != 0) {
                model.setValue("yem_pricefieldaccba", pricefieldaccamt.divide(qty, BigDecimal.ROUND_HALF_UP), rowNow);
            }
        } else {
            model.setValue("yem_pricefieldaccba", null, rowNow);
        }
    }

    /**
     * 计算 资源配件金额
     */
    public static void addPjSourceAccount(IDataModel model, DynamicObjectCollection collection) {
        int rowCurr = 0;
        String name = model.getDataEntityType().getName();
        if ("yem_es_salesorder".equals(name)) {
            for (DynamicObject dynamicObject : collection) {
                String businesssort = dynamicObject.getString("yem_businesssort");
                long pkValue = (long) dynamicObject.getPkValue();

                if ("Z".equals(businesssort)) {
                    BigDecimal sumAmt = BigDecimal.ZERO;
                    for (DynamicObject object : collection) {
                        String current = object.getString("yem_businesssort");
                        boolean ifgift = object.getBoolean("yem_ifgift");
                        if ("P".equals(current) && ifgift) {
                            long incompid = object.getLong("yem_incompid");
                            if (YEM.isNotEmpty(incompid) && incompid == pkValue) {
                                BigDecimal safobamount = object.getBigDecimal("yem_safobamount");
                                sumAmt = sumAmt.add(safobamount);
                            }
                        }
                    }
                    model.setValue("yem_pricefieldaccamt", sumAmt, rowCurr);
                }

                rowCurr++;
            }
        }

        if ("yem_im_clientdemand".equals(name)) {
            for (DynamicObject temp : collection) {
                String businesssort = temp.getString("yem_businesssort");
                DynamicObject resourcenog = temp.getDynamicObject("yem_resourcenog");
                BigDecimal sum = BigDecimal.ZERO;
                if ("Z".equals(businesssort)) {
                    if (resourcenog != null) {
                        long resourcenogId = resourcenog.getLong("id");
                        for (DynamicObject twoS : collection) {
                            boolean ifgift = twoS.getBoolean("yem_ifgift");
                            String yem_businesssort = twoS.getString("yem_businesssort");
                            DynamicObject yem_resourcenog = twoS.getDynamicObject("yem_resourcenog");
                            if (yem_resourcenog != null) {
                                long id = yem_resourcenog.getLong("id");
                                if ("P".equals(yem_businesssort) && id == resourcenogId && ifgift) {
                                    sum = sum.add(twoS.getBigDecimal("yem_safobamount"));
                                }
                            }

                        }
                        model.setValue("yem_pricefieldaccamt", sum, rowCurr);
                    }
                }
                rowCurr++;
            }
        }
    }

    /**
     * @description 外贸整机汇率改变
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * @time 2023/8/10 19:17
     */

    public static void changeRate(IDataModel model, String entryKey) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        int entryRowCount = model.getEntryRowCount(entryKey);
        if (exrate.compareTo(BigDecimal.ZERO) != 0) {
            if ("yem_im_detailedinfor".equals(entryKey) || "yem_es_materialinfo".equals(entryKey)) {
                DynamicObject dataEntity = model.getDataEntity(true);
                DynamicObjectCollection detailedinfor = dataEntity.getDynamicObjectCollection(entryKey);
                for (int i = 0; i < entryRowCount; i++) {
                    if (exrate.compareTo(BigDecimal.ZERO) != 0) {
//                        BigDecimal price = (BigDecimal) model.getValue("yem_price", i);
//                        model.setValue("yem_sapricepriceclause", price.divide(exrate, RoundingMode.HALF_UP), i);
                        String businesssort = (String) model.getValue("yem_businesssort", i);
                        if ("Z".equals(businesssort)) {
                            BigDecimal standardprice = (BigDecimal) model.getValue("yem_standardprice", i);
                            if (exrate.compareTo(BigDecimal.ZERO) != 0) {
                                model.setValue("yem_sastandardprice", roundUp(standardprice.divide(exrate, BigDecimal.ROUND_HALF_UP)), i);
                            }
                            BigDecimal sastandardprice = (BigDecimal) model.getValue("yem_sastandardprice", i);
                            model.setValue("yem_sastandardpricesa", sastandardprice.multiply(exrate), i);

                            //重新计算多功能配置中 标准销售加价（结算币计算）
                            DynamicObject entry = detailedinfor.get(i);
                            DynamicObjectCollection multiconfig = entry.getDynamicObjectCollection("yem_multiconfig");
                            if (multiconfig != null && multiconfig.size() > 0) {
                                int row = 0;
                                for (DynamicObject temp : multiconfig) {
                                    BigDecimal marketraisepribase = temp.getBigDecimal("yem_marketraisepribase");
                                    if (exrate.compareTo(BigDecimal.ZERO) != 0) {
                                        model.setValue("yem_marketraiseprice", roundUp(marketraisepribase.divide(exrate, BigDecimal.ROUND_HALF_UP)), row, i);
                                    }
                                    row++;
                                }
                            }
                        }
                        if ("P".equals(businesssort)) {
                            BigDecimal fobprice = (BigDecimal) model.getValue("yem_fobprice", i);
                            if (exrate.compareTo(BigDecimal.ZERO) != 0) {
                                model.setValue("yem_safobprice", roundUpNew(fobprice.divide(exrate, BigDecimal.ROUND_HALF_UP)), i);
                            }
                        }

                        BigDecimal safobprice = (BigDecimal) model.getValue("yem_safobprice", i);
                        model.setValue("yem_safobpricebase", exrate.multiply(safobprice), i);
                        BigDecimal safobamount = (BigDecimal) model.getValue("yem_safobamount", i);
                        model.setValue("yem_safobamountbase", safobamount.multiply(exrate), i);
                        BigDecimal sapricepriceclause = (BigDecimal) model.getValue("yem_sapricepriceclause", i);
//                        model.setValue("yem_sapriceclausebase", exrate.multiply(sapricepriceclause), i);


                    }
                }
            }
//            else {
//                for (int i = 0; i < entryRowCount; i++) {
//                    if(exrate.compareTo(BigDecimal.ZERO) != 0) {
//                        BigDecimal price = (BigDecimal) model.getValue("yem_price", i);
//                        model.setValue("yem_sapricepriceclause", price.divide(exrate, RoundingMode.HALF_UP), i);
//                        BigDecimal standardprice = (BigDecimal) model.getValue("yem_standardprice", i);
//                        model.setValue("yem_sastandardprice", standardprice.divide(exrate, BigDecimal.ROUND_HALF_UP), i);
//                        BigDecimal sastandardprice = (BigDecimal) model.getValue("yem_sastandardprice", i);
//                        model.setValue("yem_sastandardpricesa", sastandardprice.multiply(exrate), i);
//                        BigDecimal safobprice = (BigDecimal) model.getValue("yem_safobprice", i);
//                        model.setValue("yem_safobpricebase", exrate.multiply(safobprice), i);
//                        BigDecimal safobamount = (BigDecimal) model.getValue("yem_safobamount", i);
//                        model.setValue("yem_safobamountbase", safobamount.multiply(exrate), i);
//                        BigDecimal sapricepriceclause = (BigDecimal) model.getValue("yem_sapricepriceclause", i);
//                        model.setValue("yem_sapriceclausebase", exrate.multiply(sapricepriceclause), i);
//                    }
//                }
//            }

        }

    }


    /**
     * @description 配件 计算销售fob单价
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/8/10 19:54
     */

    public static void countPjSaFobPrice(IDataModel model, int row) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        BigDecimal fobPrice = (BigDecimal) model.getValue("yem_fobprice", row);
        model.setValue("yem_safobprice", fobPrice.divide(exrate, RoundingMode.HALF_UP), row);
    }


    /**
     * @description 外贸整机汇率改变
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * @time 2023/8/10 19:17
     */

    public static void changeRatePJ(IDataModel model, String entryKey) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        int entryRowCount = model.getEntryRowCount(entryKey);
        for (int i = 0; i < entryRowCount; i++) {
            BigDecimal saPricePriceClause = (BigDecimal) model.getValue("yem_sapricepriceclause", i);
//            model.setValue("yem_sapriceclausebase",saPricePriceClause.multiply(exrate),i);//赋值 销售单价（价格条款人民币）

            BigDecimal saBobAmount = (BigDecimal) model.getValue("yem_safobamount", i);
            model.setValue("yem_safobamountbase", saBobAmount.multiply(exrate), i);//赋值销售fob金额人民币

            BigDecimal saFobPrice = (BigDecimal) model.getValue("yem_safobprice", i);
            model.setValue("yem_safobpricebase", saFobPrice.multiply(exrate), i);

            String name = model.getDataEntityType().getName();
            BigDecimal fobPrice;
            if ("yem_es_salesorder".equals(name) || "yem_es_xsalesorder".equals(name)) {
                fobPrice = (BigDecimal) model.getValue("yem_exwrmbprice", i);
            } else {
                fobPrice = (BigDecimal) model.getValue("yem_fobprice", i);
            }
            if (exrate.compareTo(BigDecimal.ZERO) != 0) {
                model.setValue("yem_safobprice", roundUpNew(fobPrice.divide(exrate, RoundingMode.HALF_UP)), i);
            } else {
                model.setValue("yem_safobprice", BigDecimal.ZERO, i);
            }

        }
    }
//    /**
//     * @Description 配件池计算折扣金额
//     */
//    public static void countAccCapitalPool(IFormView view,IDataModel model,String entryKey){
//        String fundUseType = (String)model.getValue("yem_fundusetype");
//        BigDecimal frontRate = (BigDecimal) model.getValue("yem_frontrate");
//        int materialInfoRows = model.getEntryRowCount(entryKey);
//        if("B".equals(fundUseType) && frontRate.compareTo(BigDecimal.ZERO) > 0){
//            for (int i = 0; i < materialInfoRows; i++) {
//                BigDecimal frontDisAmt = (BigDecimal)model.getValue("yem_frontdisamt", i);
//                model.beginInit();
//                if(frontDisAmt.compareTo(BigDecimal.ZERO) > 0){
//                    BigDecimal disAmt = BigDecimal.ONE.subtract(frontRate.divide(new BigDecimal(100), 4, RoundingMode.HALF_UP)).multiply(frontDisAmt);
//                    model.setValue("yem_disamt",disAmt,i);
//                }else{
//                    model.setValue("yem_disamt",BigDecimal.ZERO,i);
//                    model.setValue("yem_frontrateentry",BigDecimal.ZERO,i);
//                }
//                model.endInit();
//                view.updateView("yem_disamt",i);
//                view.updateView("yem_frontrateentry",i);
//            }
//        }else{
//            for (int i = 0; i < materialInfoRows; i++) {
//                model.beginInit();
//                model.setValue("yem_disamt",BigDecimal.ZERO,i);
//                model.endInit();
//                view.updateView("yem_disamt",i);
//                view.updateView("yem_frontrateentry",i);
//            }
//        }
//    }

    /**
     * BigDeciaml向上取整  保留整数位
     */
    public static BigDecimal roundUp(BigDecimal bigDecimal) {
        if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
            String strValue = bigDecimal.toString();
            String[] values = strValue.split("\\.");
            if (values.length > 1) {
                int intValue = Integer.valueOf(values[0]);
                double doValue = Double.valueOf("0." + values[1]);
                if (doValue > 0) {
                    intValue = intValue + 1;
                }
                return new BigDecimal(intValue);
            }
        }
        if (bigDecimal.compareTo(BigDecimal.ZERO) == -1) {
            String strValue = bigDecimal.toString();
            String[] values = strValue.split("\\.");
            if (values.length > 1) {
                int intValue = Integer.valueOf(values[0]);
                double doValue = Double.valueOf("0." + values[1]);
                if (doValue > 0) {
                    intValue = intValue;
                }
                return new BigDecimal(intValue);
            }
        }

        return bigDecimal;
    }

    /**
     * BigDeciaml向上取整  如果是10及其以上位数，进位保留整数，如10.2、10.7等都是11.
     * 如果是10以下位数，，小数点后进位保留一位，8.91 是9.0, 8.64 是 8.7。支持手工维护
     */
    public static BigDecimal roundUpNew(BigDecimal bigDecimal) {
//        if (bigDecimal.compareTo(new BigDecimal(10)) == 1) {
//            String strValue = bigDecimal.toString();
//            String[] values = strValue.split("\\.");
//            if (values.length > 1) {
//                int intValue = Integer.valueOf(values[0]);
//                double doValue = Double.valueOf("0." + values[1]);
//                if (doValue > 0) {
//                    intValue = intValue + 1;
//                }
//                return new BigDecimal(intValue);
//            }
//        } else {
//            if (bigDecimal.compareTo(BigDecimal.ZERO) == 1) {
//                String strValue = bigDecimal.toString();
//                String[] values = strValue.split("\\.");
//                if (values.length > 1) {
//                    int intValue = Integer.valueOf(values[0]);
//                    String minValue = values[1];
//                    String min = Character.toString(minValue.charAt(0));
//                    String min2 = Character.toString(minValue.charAt(1));
//                    int temp = Integer.valueOf(min);
//                    int temp2 = Integer.valueOf(min2);
//                    if (temp2 != 0) {
//                        if (temp == 9) {
//                            return new BigDecimal(intValue + 1);
//                        } else {
//                            double doValue = Double.valueOf("0." + (temp + 1));
//                            return new BigDecimal(intValue + doValue);
//                        }
//
//                    } else {
//                        double doValue = Double.valueOf("0." + (temp));
//                        return new BigDecimal(intValue + doValue);
//                    }
//
//                }
//            }
//
//
//        }

        return bigDecimal.setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 标准销售加价（结算币别） 标准销售加价（人民币）/汇率，向上进位取整，保留整数
     */
    public static void countStandardSales(IDataModel model) {
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        DynamicObjectCollection collection = getTypeColl(model);
        if (collection != null && collection.size() > 0) {
            int partIndex = 0;
            for (DynamicObject temp : collection) {
                if (temp != null) {
                    DynamicObjectCollection dynamicObjectCollection = temp.getDynamicObjectCollection("yem_multiconfig");
                    if (dynamicObjectCollection != null && dynamicObjectCollection.size() > 0) {
                        int sonIndex = 0;
                        for (DynamicObject dy : dynamicObjectCollection) {
                            if (dy != null) {
                                BigDecimal marketraisepribase = dy.getBigDecimal("yem_marketraisepribase");
                                if (BigDecimal.ZERO.compareTo(exrate) != 0) {
                                    model.setValue("yem_marketraiseprice", roundUp(marketraisepribase.divide(exrate, BigDecimal.ROUND_HALF_UP)), sonIndex, partIndex);
                                }
                            }
                            sonIndex++;
                        }

                    }
                }
                partIndex++;

            }
        }

//
//         BigDecimal marketraisepribase = (BigDecimal) model.getValue("yem_marketraisepribase",row);
//        if(BigDecimal.ZERO.compareTo(exrate) != 0){
//            model.setValue("yem_marketraiseprice",marketraisepribase == null?null:roundUp(marketraisepribase.divide(exrate,BigDecimal.ROUND_HALF_UP)),row,ParentRow);
//        }

    }

    /**
     * 外销合同、客户需求单 获取明细信息单据体
     */
    public static DynamicObjectCollection getTypeColl(IDataModel model) {
        DynamicObject datas = model.getDataEntity(true);
        String billType = datas.getString("yem_billtype.number");
        DynamicObjectCollection collection;
        if (salesorderytpe().containsKey(billType)) {
//        if ("yem_es_salesorder_ZJ".equals(billType) || "yem_es_salesorder_nmzj".equals(billType) || "yem_es_salesorder_PJ".equals(billType) || "yem_es_salesorder_nmpj".equals(billType)) {
            //外销合同整机
            collection = datas.getDynamicObjectCollection("yem_es_materialinfo");
        } else {
            collection = datas.getDynamicObjectCollection("yem_im_detailedinfor");
        }
        return collection;
    }

    public static Map<String, String> salesorderytpe() {
        Map map = new HashMap<>();
        map.put("yem_es_salesorder_ZJ", "外贸整机合同");
        map.put("yem_es_salesorder_nmzj", "内贸整机合同");
        map.put("yem_es_salesorder_PJ", "外贸配件合同");
        map.put("yem_es_salesorder_nmpj", "内贸配件合同");
        map.put("yem_es_xsalesorder_zj", "外贸整机合同变更单");
        map.put("yem_es_xsalesorder_pj", "外贸配件合同变更单");
        map.put("yem_es_xsalesorder_nmzj", "内贸整机合同变更单");
        map.put("yem_es_xsalesorder_nmpj", "内贸配件合同变更单");
        return map;
    }

    /**
     * 锁定字段
     */
    public static void lock(IFormView view, IDataModel model, int rowIndex) {
        String businessSort = (String) model.getValue("yem_businesssort", rowIndex);
        if ("P".equals(businessSort)) {
            model.deleteEntryData("yem_multiconfig");
            model.setValue("yem_productmodel", null, rowIndex);
            view.setEnable(false, rowIndex, "yem_productmodel");
            view.setEnable(false, rowIndex, "yem_sastandardprice");
            view.setEnable(false, rowIndex, "yem_sastandardpricesa");
            view.setEnable(true, rowIndex, "yem_safobprice");
        } else {
            view.setEnable(true, rowIndex, "yem_productmodel");
            view.setEnable(false, rowIndex, "yem_safobprice");
        }
    }

    /**
     * 资源号锁定性
     */
    public static void resourceNogLock(IFormView view, IDataModel model, int rowIndex) {
        String businessSort = (String) model.getValue("yem_businesssort", rowIndex);
        boolean ifgift = (boolean) model.getValue("yem_ifgift", rowIndex);
        if ("P".equals(businessSort)) {
            if (ifgift) {
                view.setEnable(true, rowIndex, "yem_resourcenog");
            } else {
                view.setEnable(false, rowIndex, "yem_resourcenog");
            }
        }
    }

    public static void forResourceNogLock(IFormView view, IDataModel model, String entryKey) {
        int entryRowCount = model.getEntryRowCount(entryKey);
        for (int i = 0; i < entryRowCount; i++) {
            resourceNogLock(view, model, i);
        }
    }


    /**
     * 获取标准价后 清除 配件- 是赠品的 销售单价（价格条款）
     */
    public static void clearSalePrice(IDataModel model) {
        DynamicObjectCollection col = getTypeColl(model);
        if (col != null && col.size() > 0) {
            int row = 0;
            for (DynamicObject temp : col) {
                if (temp != null) {
                    String businesssort = temp.getString("yem_businesssort");
                    boolean ifgift = temp.getBoolean("yem_ifgift");
                    if ("P".equals(businesssort) && ifgift) {
                        model.setValue("yem_sapricepriceclause", null, row);
                    }
                }
                row++;
            }
        }
    }

    /**
     * 选资源号时、判断资源号中是否存在物料  如果没有则用资源号编码去物料库查、没有则提示
     */
    public static void resouceToMaterial(IDataModel model, IFormView view, int row) {
        DynamicObject resourceid = (DynamicObject) model.getValue("yem_resourcenog", row);
        String businesssort = (String) model.getValue("yem_businesssort", row);
        if (resourceid != null && "Z".equals(businesssort)) {
            String resouceNumber = resourceid.getString("number");
            List<QFilter> qFilterList = new ArrayList<QFilter>();
            if (!Objects.equals(resouceNumber, "")) {
                qFilterList.add(new QFilter("number", QCP.equals, resouceNumber));
            }
            DynamicObject tempCol = BusinessDataServiceHelper.loadSingle("bd_material", "11", qFilterList.toArray(new QFilter[0]));
            if (tempCol != null) {
                model.setValue("yem_materiel", tempCol.getLong("id"), row);
            } else {
                view.showMessage("请维护编码【" + resouceNumber + "】的物料！");
            }
        }
    }

    /**
     * 明细信息 新增行 给单位赋值
     */
    public static void setValueByAddRow(String entryName, RowDataEntity re, IDataModel model, ValueSave valueSave) {
        DynamicObject unitNow;
        if (ClientUtils.isZJPage(model)) {
            unitNow = valueSave.getDatas("unitZj");
            if (unitNow == null) {
                DynamicObject unit = BusinessDataServiceHelper.loadSingle("bd_measureunits", "name",
                        new QFilter[]{new QFilter("name", QCP.equals, "台")});
                valueSave.setDatas("unitZj", unit);
            }
        } else if (ClientUtils.isPjPage(model)) {
            unitNow = valueSave.getDatas("unitPj");
            if (unitNow == null) {
                DynamicObject unit = BusinessDataServiceHelper.loadSingle("bd_measureunits", "name",
                        new QFilter[]{new QFilter("name", QCP.equals, "个")});
                valueSave.setDatas("unitPj", unit);
            }
        }

        if ("yem_im_detailedinfor".equals(entryName)) {
            if (ClientUtils.isZJPage(model)) {
                DynamicObject unit = valueSave.getDatas("unitZj");
                if (unit != null) {
                    model.setValue("yem_unit", unit.getPkValue(), re.getRowIndex());
                    model.setValue("yem_baseunit", unit.getPkValue(), re.getRowIndex());
                }
                model.setValue("yem_businesssort", "Z", re.getRowIndex());

            } else if (ClientUtils.isPjPage(model)) {
                DynamicObject unit = valueSave.getDatas("unitPj");
                if (unit != null) {
                    model.setValue("yem_unit", unit.getPkValue(), re.getRowIndex());
                    model.setValue("yem_baseunit", unit.getPkValue(), re.getRowIndex());
                }
                model.setValue("yem_businesssort", "P", re.getRowIndex());

            }

        }
    }


    /**
     * 判断是否当前页面是  外贸、内贸客户需求单整机
     */
    public static boolean isZJPage(IDataModel model) {
        DynamicObject temp = (DynamicObject) model.getValue("yem_billtype");
        if (temp != null) {
            String billNumber = temp.getString("number");
            if ("yem_im_clientdeman_zj".equals(billNumber) || "yem_im_inclientdeman_zj".equals(billNumber)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断是否当前页面是  外贸、内贸客户需求单配件
     */
    public static boolean isPjPage(IDataModel model) {
        DynamicObject temp = (DynamicObject) model.getValue("yem_billtype");
        if (temp != null) {
            String billNumber = temp.getString("number");
            if ("yem_im_clientdema_pj".equals(billNumber) || "yem_im_inclientdema_pj".equals(billNumber)) {
                return true;
            }
        }
        return false;
    }


//    /**
//     * @description 计算使用额度
//     * @author xwudd
//     * @param[1] view
//     * @param[2] model
//     * @param[3] entryKey
//     * return
//     * @time 2023/9/21 15:24
//     */
//
//    public static void countFundPoolAmt(IFormView view,IDataModel model,String entryKey){
//        BigDecimal disAmtTotal = BigDecimal.ZERO;
//        int entryRowCount = model.getEntryRowCount(entryKey);
//        for (int i = 0; i < entryRowCount; i++) {
//            BigDecimal disAmt = (BigDecimal)model.getValue("yem_disamt",i);//折扣金额
//            disAmtTotal = disAmtTotal.add(disAmt);
//        }
//        model.beginInit();
//        model.setValue("yem_fundpoolamt",disAmtTotal);
//        model.endInit();
//        view.updateView("yem_fundpoolamt");
//    }


    public static void empty(IDataModel model, int row, String entryKey, IFormView view) {
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObjectCollection dynamicObjectCollection = dataEntity.getDynamicObjectCollection(entryKey);
        Boolean ifGift = (Boolean) model.getValue("yem_ifgift", row);
        if (ifGift) {
            model.setValue("yem_onecarsum", null, row);//单车总费用
            model.setValue("yem_onecarsumbase", null, row);//单车总费用(人民币)
            model.setValue("yem_sapricepriceclause", null, row);//销售单价（价格条款）
            model.setValue("yem_saamtpriceclause", null, row);//销售金额（价格条款）
            model.setValue("yem_sapriceclausebase", null, row);//销售单价（价格条款人民币）
            model.setValue("yem_samtpriceclauseba", null, row);//销售金额（价格条款人民币）
            model.setValue("yem_truecarprice", null, row);//实际整车单价
            model.setValue("yem_truecaramt", null, row);//实际整车金额
            model.setValue("yem_truecarpriceba", null, row);//实际整车单价（人民币）
            model.setValue("yem_truecaramtba", null, row);//实际整车金额（人民币）
            model.setValue("yem_pricefieldaccba", null, row);//资源配件单价
            model.setValue("yem_pricefieldaccamt", null, row);//资源配件金额
            model.setValue("yem_disamt", null, row);//折扣金额
            model.setValue("yem_frontrateentry", null, row);//折扣率%
            model.setValue("yem_frontdisprice", null, row);//折扣前销售单价
            model.setValue("yem_frontdisamt", null, row);//折扣前销售金额
            model.setValue("yem_afterfrontdisprice", null, row);//折扣前销售单价
            model.setValue("yem_afterfrontdisamt", null, row);//折扣前销售金额
        } else {
            addPjSourceAccount(model, dynamicObjectCollection);//资源配件单价
//            countSaPricePriceClause(model, row);
            countFrontDisPrice(model, row);
            countFrontDisAmt(model, row);
            addSaAmountTk(model, row);
            countDisAmt(model, entryKey, row, view);
            countAfterFrontAmt(model, row);
            countAfterFrontPrice(model, row);
            model.setValue("yem_frontrateentry", model.getValue("yem_frontrate"), row);
        }
    }

    /**
     * @description 配件 销售单价（价格条款）
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/8/10 19:55
     *
     * 销售单价（价格条款）= 销售FOB金额 /数量
     */

    public static void countSaPricePriceClause(IDataModel model, int row) {
        BigDecimal afterFrontDisPrice = (BigDecimal) model.getValue("yem_afterfrontdisprice", row); // 折扣后销售单价
        boolean ifgift = (boolean) model.getValue("yem_ifgift", row);
        BigDecimal qty = (BigDecimal) model.getValue("yem_qty", row);//数量
        if (!ifgift) {
            BigDecimal priceFieldAccBa = (BigDecimal) model.getValue("yem_pricefieldaccba", row);//资源配置单价
            BigDecimal oneCarSum = (BigDecimal) model.getValue("yem_onecarsum", row);//单车总费用
            BigDecimal saamtpriceclause = (BigDecimal) model.getValue("yem_saamtpriceclause", row);// 销售金额（价格条款）
            model.setValue("yem_sapricepriceclause", BigDecimalUtils.div(saamtpriceclause, qty, 6), row);

//            if (afterFrontDisPrice.compareTo(BigDecimal.ZERO) > 0) {
//                // 销售单价（价格条款）= （销售金额（价格条款） / 数量）
//                model.setValue("yem_sapricepriceclause", BigDecimalUtils.div(saamtpriceclause, qty, 2), row);
//            } else {
//                BigDecimal saFobAmount = (BigDecimal) model.getValue("yem_safobprice", row);
//                // 从销售FOB金额改成销售FOB单价 2024-4-26
//                // 销售单价（价格条款）= 销售FOB单价 + 资源配置单价 + 单车总费用
//                model.setValue("yem_sapricepriceclause", saFobAmount.add(priceFieldAccBa).add(oneCarSum), row);
//            }
        } else {
            model.setValue("yem_sapricepriceclause", null, row);
        }



    }


    /**
     * 销售金额（价格条款）结算币别
     *
     * 1、如果分录没有总费用、没有折扣金额，就是按照   数量*销售EXW单价
     * 2、如果分录有总费用或者折扣金额，则销售金额（价格条款） = （折扣后销售金额 +总费用 ）+ 资源配件单价 *数量
     * 销售单价（价格条款）= 销售金额（价格条款） /数量
     *
     */
    public static void addSaAmountTk(IDataModel model, int rowNow) {
        boolean ifgift = (boolean) model.getValue("yem_ifgift", rowNow);
        String[] roundArr = {
                "yem_es_salesorder_ZJ",
                "yem_es_salesorder_nmzj",
                "yem_im_clientdeman_zj",
                "yem_im_inclientdeman_zj",
                "yem_shippingdetails_nmzj",
                "yem_shippingdetails_zj",

                "yem_es_xsalesorder_ZJ",
                "yem_es_xsalesorder_nmzj",
                "yem_xshippingdetails_nmzj",
                "yem_xshippingdetails_zj",
        };
        if (!ifgift) {
            BigDecimal totalamount = (BigDecimal) model.getValue("yem_totalamount", rowNow);// 总费用汇总
            // 销售金额（价格条款） = 销售FOB金额 + 总费用 + 资源配件金额 - 折扣金额
            BigDecimal safobamount = (BigDecimal) model.getValue("yem_safobamount", rowNow); // 销售FOB金额
            BigDecimal qty = (BigDecimal) model.getValue("yem_qty", rowNow); // 数量
            BigDecimal pricefieldaccba = (BigDecimal) model.getValue("yem_pricefieldaccba", rowNow);// 资源配件单价
            BigDecimal disamt = (BigDecimal) model.getValue("yem_disamt", rowNow); // 折扣金额
            BigDecimal pricefieldaccamt = (BigDecimal) model.getValue("yem_pricefieldaccamt", rowNow);// 资源配件金额
            BigDecimal calculate = safobamount.add(totalamount).add(pricefieldaccamt).subtract(disamt);
            DynamicObject billtype = (DynamicObject) model.getValue("yem_billtype");
            if (billtype == null) return;
            String type = billtype.getString("number");
            if (ArrayUtils.contains(roundArr, type)) {
                model.setValue("yem_saamtpriceclause", calculate.setScale(0, RoundingMode.UP), rowNow);
            } else {
                model.setValue("yem_saamtpriceclause", calculate, rowNow);
            }
        } else {
            model.setValue("yem_saamtpriceclause", null, rowNow);
        }
        countSaPricePriceClause(model, rowNow);
        countRealCatAmount(model, rowNow);
//        calculateInsurancePremiums(rowNow, model);
    }

    /**
     * 计算保险费
     * 保险费=（FOB单价+海运费）*保险加成率*运保费率/100
     * @param rowIdx
     * @param model
     */
    public static void calculateInsurancePremiums(int rowIdx, IDataModel model) {
        if (rowIdx != -1) {
            doCalculateInsurancePremiums(rowIdx, model);
        } else {
            int rowCount = model.getEntryRowCount("yem_es_materialinfo");
            for (int index = 0; index < rowCount; index++) {
                doCalculateInsurancePremiums(index, model);
            }
        }
    }

    private static void doCalculateInsurancePremiums(int rowIdx, IDataModel model) {

        BigDecimal safobprice = (BigDecimal) model.getValue("yem_safobprice", rowIdx);//销售FOB单价
        BigDecimal seafreight = (BigDecimal) model.getValue("yem_e_seafreight", rowIdx);//海运费
        BigDecimal insuranceaddrate = (BigDecimal) model.getValue("yem_insuranceaddrate");//保险加成率
        BigDecimal insurancefeerate = (BigDecimal) model.getValue("yem_insurancefeerate");//运保费率
        BigDecimal calc = safobprice.add(seafreight).multiply(insuranceaddrate).multiply(insurancefeerate).divide(new BigDecimal("100"), 10, RoundingMode.HALF_UP);
        model.setValue("yem_e_marinsupreamt", calc, rowIdx);
    }

    /**
     * 信保费=（当前行销售FOB单价+海运费+保险费+银行利息费）*收款计划中的是否信保为是的收汇百分比%*信保费率
     */
    public static void calculateCreditAmount(int rowIdx, IDataModel model) {
        if (rowIdx != -1) {
            doCalculateCreditAmount(rowIdx, model);
        } else {
            int rowCount = model.getEntryRowCount("yem_es_materialinfo");
            for (int index = 0; index < rowCount; index++) {
                doCalculateCreditAmount(index, model);
            }
        }
    }

    private static void doCalculateCreditAmount(int rowIdx, IDataModel model) {
        BigDecimal safobprice = (BigDecimal) model.getValue("yem_safobprice", rowIdx);//销售FOB单价
        BigDecimal seafreight = (BigDecimal) model.getValue("yem_e_seafreight", rowIdx);//海运费
        BigDecimal marinsupreamt = (BigDecimal) model.getValue("yem_e_marinsupreamt", rowIdx);//保险费
        BigDecimal interestamt = (BigDecimal) model.getValue("yem_e_interestamt", rowIdx);//银行利息费
        BigDecimal calculate = BigDecimal.ZERO;
        int rowCount = model.getEntryRowCount("yem_es_salescontrac_s");
        for (int i = 0; i < rowCount; i++) {
            String issinosure = (String) model.getValue("yem_issinosure", i);
            if ("A".equals(issinosure)) {
                BigDecimal raprate = (BigDecimal) model.getValue("yem_raprate", i);//收汇百分比%
                raprate = BigDecimalUtils.div(raprate, new BigDecimal("100"), 10);
                BigDecimal sinosurerate = (BigDecimal) model.getValue("yem_sinosurerate", i);//信保费率
                sinosurerate = BigDecimalUtils.div(sinosurerate, new BigDecimal("100"), 10);
                BigDecimal multiply = safobprice.add(seafreight).add(marinsupreamt).add(interestamt).multiply(raprate).multiply(sinosurerate);
                calculate = calculate.add(multiply);
            }
        }
        model.setValue("yem_e_creditamt", calculate, rowIdx);

    }

    /**
     * // 银行利息费=（当前行销售FOB单价+海运费+保险费）*收款计划中的是否信保为是的收汇百分比%/100*利息率/100，利息率手填
     *
     * 银行利息费=（当前行销售FOB单价+海运费+保险费）*收款计划中的是否信保为是的收汇百分比%/100*利息率/100/360*利息天数
     * @param rowIdx
     * @param model
     */
    public static void calculateBankInterestCharges(int rowIdx, IDataModel model) {
        if (rowIdx != -1) {
            doCalculateBankInterestCharges(rowIdx, model);
        } else {
            int rowCount = model.getEntryRowCount("yem_es_materialinfo");
            for (int index = 0; index < rowCount; index++) {
                doCalculateBankInterestCharges(index, model);
            }
        }
    }

    private static void doCalculateBankInterestCharges(int rowIdx, IDataModel model) {
        BigDecimal safobprice = (BigDecimal) model.getValue("yem_safobprice", rowIdx);//销售FOB单价
        BigDecimal seafreight = (BigDecimal) model.getValue("yem_e_seafreight", rowIdx);//海运费
        BigDecimal marinsupreamt = (BigDecimal) model.getValue("yem_e_marinsupreamt", rowIdx);//保险费
        BigDecimal interestrate = (BigDecimal) model.getValue("yem_e_interestrate", rowIdx);//利息率%
        interestrate = BigDecimalUtils.div(interestrate, new BigDecimal("100"), 10);
        BigDecimal calculate = BigDecimal.ZERO;
        int rowCount = model.getEntryRowCount("yem_es_salescontrac_s");
        for (int i = 0; i < rowCount; i++) {
            String issinosure = (String) model.getValue("yem_issinosure", i);
            if ("A".equals(issinosure)) {
                BigDecimal raprate = (BigDecimal) model.getValue("yem_raprate", i);//收汇百分比%
                BigDecimal interestdays = (BigDecimal) model.getValue("yem_interestdays", i);//利息天数
                raprate = BigDecimalUtils.div(raprate, new BigDecimal("100"), 10);
                BigDecimal multiply = BigDecimalUtils.div(safobprice.add(seafreight).add(marinsupreamt).multiply(raprate).multiply(interestrate), new BigDecimal("360"), 10).multiply(interestdays);
                calculate = calculate.add(multiply);
            }
        }
        model.setValue("yem_e_interestamt", calculate.setScale(0, RoundingMode.UP), rowIdx);
    }

    /**
     * @description 计算折扣前销售单价
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/8/10 20:13
     */

    public static void countFrontDisPrice(IDataModel model, int row) {
        boolean ifgift = (boolean) model.getValue("yem_ifgift", row);
        if (!ifgift) {
            BigDecimal saFobPrice = (BigDecimal) model.getValue("yem_safobprice", row);
            BigDecimal oneCarSum = (BigDecimal) model.getValue("yem_onecarsum", row);
            BigDecimal priceFieldAccBa = (BigDecimal) model.getValue("yem_pricefieldaccba", row);
            model.setValue("yem_frontdisprice", saFobPrice.add(oneCarSum).add(priceFieldAccBa), row);
        } else {
            model.setValue("yem_frontdisprice", null, row);
        }
    }


    /**
     * @description 计算折扣前销售金额
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/8/10 20:13
     */
    public static void countFrontDisAmt(IDataModel model, int row) {
        boolean ifgift = (boolean) model.getValue("yem_ifgift", row);
        if (!ifgift) {
            BigDecimal frontDisPrice = (BigDecimal) model.getValue("yem_frontdisprice", row);
            BigDecimal qty = (BigDecimal) model.getValue("yem_qty", row);
            model.setValue("yem_frontdisamt", frontDisPrice.multiply(qty), row);
        } else {
            model.setValue("yem_frontdisamt", null, row);
        }
    }

    /**
     * @description 按比例清空折扣率 按金额 清空使用额度
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * return
     * @time 2023/11/28 10:42
     */

    public static void delValue(IDataModel model, String entryKey) {
        String accAmtUseType = (String) model.getValue("yem_accamtusetype");
        int entryRowCount = model.getEntryRowCount(entryKey);
        if (YEM.isNotEmpty(accAmtUseType)) {
            switch (accAmtUseType) {
                case "A":
                    model.setValue("yem_fundpoolamt", null);
                    model.setValue("yem_frontrate", null);
                    for (int i = 0; i < entryRowCount; i++) {
                        model.setValue("yem_disamt", null, i);
                        model.setValue("yem_frontrateentry", null, i);
                    }
                    break;
                case "B":
                    model.setValue("yem_fundpoolamt", null);
                    for (int i = 0; i < entryRowCount; i++) {
                        model.setValue("yem_disamt", null, i);
                        model.setValue("yem_frontrateentry", null, i);
                    }
                    break;
            }
        } else {
            model.setValue("yem_fundpoolamt", null);
            model.setValue("yem_frontrate", null);
            for (int i = 0; i < entryRowCount; i++) {
                model.setValue("yem_disamt", null, i);
                model.setValue("yem_frontrateentry", null, i);
            }
        }
    }

    /**
     * @description 计算折扣金额
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * @param[3] row
     * return
     * @time 2023/11/24 17:09
     */

    public static void countDisAmt(IDataModel model, String entryKey, int row, IFormView view) {
        String accAmtUseType = (String) model.getValue("yem_accamtusetype");
        int entryRow = model.getEntryRowCount(entryKey);
        if (YEM.isNotEmpty(accAmtUseType)) {
            switch (accAmtUseType) {
                case "A":
                    countAmtDisAmt(model, entryKey, view);
                    break;
                case "B":
                    countRateDisAmt(model, row);
                    break;
            }
        }

    }


    /**
     * @description 按金额计算折扣金额
     * @author xwudd
     * @param[1] model
     * return
     * @time 2023/10/19 15:56
     */

    public static void countAmtDisAmt(IDataModel model, String entryKey, IFormView view) {
        BigDecimal fundPoolAmt = (BigDecimal) model.getValue("yem_fundpoolamt");
        BigDecimal amount = (BigDecimal) model.getValue("yem_amount");
        if (amount.compareTo(BigDecimal.ZERO) > 0) {
            int entryRowCount = model.getEntryRowCount(entryKey);
            int seq = 0;
            for (int i = 0; i < entryRowCount; i++) {
                Boolean ifGift = (Boolean) model.getValue("yem_ifgift", i);
                if (!ifGift) {
                    if (i > seq) {
                        seq = i;
                    }
                }
            }
            BigDecimal fundPoolAmtSum = BigDecimal.ZERO;
            for (int i = 0; i < entryRowCount; i++) {
                Boolean ifGift = (Boolean) model.getValue("yem_ifgift", i);
                if (!ifGift) {
                    BigDecimal saFobAmount = (BigDecimal) model.getValue("yem_safobamount", i);
                    BigDecimal diaAmt = saFobAmount.divide(amount, RoundingMode.HALF_UP).multiply(fundPoolAmt).setScale(2, RoundingMode.HALF_UP);
                    if (i == seq) {
                        model.beginInit();
                        model.setValue("yem_disamt", fundPoolAmt.subtract(fundPoolAmtSum), i);
                        model.endInit();
                        view.updateView("yem_disamt", i);
                    } else {
                        fundPoolAmtSum = fundPoolAmtSum.add(diaAmt);
                        model.beginInit();
                        model.setValue("yem_disamt", diaAmt, i);
                        model.endInit();
                        view.updateView("yem_disamt", i);
                    }
//                    System.out.printf("++++++++--  i = %s -- seq = %s -- yem_disamt = %s%n", i, seq, model.getValue("yem_disamt", i));
                } else {
                    model.beginInit();
                    model.setValue("yem_disamt", null, i);
                    model.endInit();
                    view.updateView("yem_disamt", i);
                }
            }
        }

    }

    /**
     * @description 按比例计算折扣金额
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/10/19 15:56
     */

    private static void countRateDisAmt(IDataModel model, int row) {
        if (row >= 0) {
            Boolean ifGift = (Boolean) model.getValue("yem_ifgift", row);
            if (!ifGift) {
                BigDecimal frontRateEntry = (BigDecimal) model.getValue("yem_frontrateentry", row);
                BigDecimal saFobAmount = (BigDecimal) model.getValue("yem_safobamount", row);
                model.setValue("yem_disamt", saFobAmount.multiply(BigDecimal.ONE.subtract(frontRateEntry.divide(new BigDecimal(100)))).setScale(2, RoundingMode.UP), row);
            } else {
                model.setValue("yem_disamt", null, row);
            }
        }
    }

    /**
     * @description 计算折扣后销售金额
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/11/24 17:17
     */

    public static void countAfterFrontAmt(IDataModel model, int row) {
        Boolean ifGift = (Boolean) model.getValue("yem_ifgift", row);
        if (!ifGift) {
            BigDecimal saFobAmount = (BigDecimal) model.getValue("yem_safobamount", row);
            BigDecimal disAmt = (BigDecimal) model.getValue("yem_disamt", row);
            model.setValue("yem_afterfrontdisamt", saFobAmount.subtract(disAmt), row);
        } else {
            model.setValue("yem_afterfrontdisamt", null, row);
        }
    }

    /**
     * @description 计算折扣后销售单价
     * @author xwudd
     * @param[1] model
     * @param[2] row
     * return
     * @time 2023/11/24 17:17
     */

    public static void countAfterFrontPrice(IDataModel model, int row) {
        Boolean ifGift = (Boolean) model.getValue("yem_ifgift", row);
        if (!ifGift) {
            BigDecimal afterFrontDisAmt = (BigDecimal) model.getValue("yem_afterfrontdisamt", row);
            BigDecimal qty = (BigDecimal) model.getValue("yem_qty", row);
            if (qty.compareTo(BigDecimal.ZERO) > 0) {
                model.setValue("yem_afterfrontdisprice", afterFrontDisAmt.divide(qty, RoundingMode.HALF_UP), row);
            } else {
                model.setValue("yem_afterfrontdisprice", null, row);
            }
        } else {
            model.setValue("yem_afterfrontdisprice", null, row);
        }
    }

    /**
     * @description 按比例 汇总折扣金额到使用额度
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * return
     * @time 2023/11/27 16:49
     */

    public static void countPoolAmt(IFormView view, IDataModel model, String entryKey) {
        BigDecimal amt = BigDecimal.ZERO;
        String accAmtUseType = (String) model.getValue("yem_accamtusetype");
        if ("B".equals(accAmtUseType)) {
            int entryRowCount = model.getEntryRowCount(entryKey);
            for (int i = 0; i < entryRowCount; i++) {
                Boolean ifGift = (Boolean) model.getValue("yem_ifgift", i);
                if (!ifGift) {
                    amt = amt.add((BigDecimal) model.getValue("yem_disamt", i));
                }
            }
            model.beginInit();
            model.setValue("yem_fundpoolamt", amt);
            model.endInit();
            view.updateView("yem_fundpoolamt");
        }

    }

    /**
     * @description 分录字段汇总表头字段
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * @param[3] fieldKey
     * return
     * @time 2023/10/20 16:48
     */

    public static void totalSaFobAmount(IDataModel model, String entryKey, String... fieldKey) {
        BigDecimal total = BigDecimal.ZERO;
        int entryRows = model.getEntryRowCount(entryKey);
        for (int i = 0; i < entryRows; i++) {
            Boolean gift = (Boolean) model.getValue(fieldKey[0], i);
            if (!gift) {
                total = total.add(((BigDecimal) model.getValue(fieldKey[1], i)).setScale(2, RoundingMode.HALF_UP));
            }
        }
        model.setValue(fieldKey[2], total);
    }


    public static void exwRMBPriceChange(IDataModel model, int rowIndex, IFormView view) {
        String yembilltype = model.getDataEntityType().getName();
        if ("yem_es_salesorder".equals(yembilltype)) {
            DynamicObject dataEntity = model.getDataEntity();
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            boolean doCalc = true;
            if (collection.get(rowIndex).getBigDecimal("yem_exwrmbprice").compareTo(BigDecimal.ZERO) > 0) {
                model.setValue("yem_fobprice", collection.get(rowIndex).getBigDecimal("yem_exwrmbprice"), rowIndex);
            } else {
                doCalc = false;
            }
            if (doCalc) {
                addPjSourceAccount(model, collection);//资源配件单价
//                countSaPricePriceClause(model, rowIndex);
                countFrontDisPrice(model, rowIndex);
                countFrontDisAmt(model, rowIndex);
                addSaAmountTk(model, rowIndex);
                countDisAmt(model, "yem_es_materialinfo", rowIndex, view);
                countAfterFrontAmt(model, rowIndex);
                countAfterFrontPrice(model, rowIndex);
            }
        }
    }

    public static void clearRelevantPrice(IDataModel model, IFormView view, int row, String entryKey) {
        Boolean ifGift = (Boolean) model.getValue("yem_ifgift", row);
        String businesssort = (String) model.getValue("yem_businesssort");
        if ("P".equals(businesssort) && !ifGift) {
            int rowCount = model.getEntryCurrentRowIndex(entryKey);
            DynamicObject currentResourcenog = (DynamicObject) model.getValue("yem_resourcenog", row);
            if (currentResourcenog == null) return;
            long id = currentResourcenog.getLong("id");
            model.setValue("yem_resourcenog", null, row);
            for (int i = 0; i < rowCount; i++) {
                DynamicObject entryResourceno = (DynamicObject) model.getValue("yem_resourcenog", i);
                if (entryResourceno == null) continue;
                long entryId = entryResourceno.getLong("id");
                if (entryId == id) {
                    model.setValue("yem_pricefieldaccamt", null, i);// 资源配件金额
                    model.setValue("yem_pricefieldaccba", null, i);// 资源配件单价
                    countRealCatAmount(model, i);
                }
            }
        }
    }
}






