package com.yem.wm.utils;/*
 *
 * @auther: xwudd
 * @Description
 * @Date: 2023/7/24
 */

import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.BeforeDeleteRowEventArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.property.AmountProp;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.field.AmountEdit;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @Description 共有功能公共方法
 **/
public class FunctionalCommon {

    /**
     * @description 单据类型编码和视图标识相同 赋值对应的单据类型
     * @author xwudd
     * @param[1] e
     * return
     * @time 2023/8/16 11:18
     */

    public static void setBillType(AbstractFormPlugin e){
        IFormView view = e.getView();
        IDataModel model = view.getModel();
        FormShowParameter fsp = view.getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        if(OperationStatus.ADDNEW == status){
            String formId = fsp.getFormId();
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id",
                    new QFilter[]{new QFilter("number", QCP.equals, formId)});
            model.setValue("yem_billtype",billType);
        }
    }










    /**
     * @description 选装、替换、加装功能公共方法
     * @author xwudd
     * @param[1] model
     * @param[2] view
     * @param[3] formId 动态表单标识
     * @param[4] operationNumber 服务标识
     * return
     * @time 2023/7/27 9:38
     */

    public static void optionalOperation(IDataModel model,IFormView view,String formId,String operationNumber){
        String name = model.getDataEntity().getDataEntityType().getName();
        int currentRowIndex = -1;
        if("yem_es_salesorder".equals(name)||"yem_es_xsalesorder".equals(name)){
            currentRowIndex = model.getEntryCurrentRowIndex("yem_es_materialinfo");
        }
        if("yem_im_clientdemand".equals(name) || "yem_im_inquirylist".equals(name)){
            currentRowIndex = model.getEntryCurrentRowIndex("yem_im_detailedinfor");
        }
        DynamicObject billType = (DynamicObject)model.getValue("yem_billtype");
        DynamicObject productModel = (DynamicObject)model.getValue("yem_productmodel",currentRowIndex);
        if(productModel != null){
            DynamicObject products = productModel.getDynamicObject("yem_products");
            if(products != null){
                Map<String, Object> map = new HashMap<>();
                List<Long> ids = new ArrayList();
                int multiConfigRows = model.getEntryRowCount("yem_multiconfig");
                for (int i = 0; i < multiConfigRows; i++) {
                    String configurType = (String)model.getValue("yem_configurtype",i);
                    Long configEntryId = (Long)model.getValue("yem_configentryid", i);
                    if("optionaloperation".equals(operationNumber)) {
                        if("A".equals(configurType)){
                            ids.add(configEntryId);
                        }
                    }
                    if("replaceoperation".equals(operationNumber)){
                        if("B".equals(configurType)){
                            ids.add(configEntryId);
                        }
                    }
                    if("retrofittingoperation".equals(operationNumber)){
                        if("C".equals(configurType)){
                            ids.add(configEntryId);
                        }
                    }
                }
                map.put("billTypeNumber",billType.getString("number"));
                map.put("products",products.getPkValue());
                map.put("operationNumber",operationNumber);
                map.put("type","B");
                map.put("ids",ids);
                map.put("productModel",productModel);
                viewForm(formId,map,view);
            }

        }else{
            view.showErrorNotification("请填写明细信息基础机型！");
        }
    }


    /**
     * @description 打开动态表单
     * @author xwudd
     * @param[1] formId 表单标识
     * @param[2] map 传参     无参传null
     * @param[3] view
     * return
     * @time 2023/8/29 11:19
     */

    public static void viewForm(String formId,Map<String,Object> map,IFormView view){
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId(formId);
        formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        if(YEM.isNotEmpty(map)){
            formShowParameter.setCustomParams(map);
        }
        view.showForm(formShowParameter);
    }

    /**
     * @description 获取金额字段绑定币别字段
     * @author xwudd
     * @param[1] view
     * @param[2] amountKey
     * @time 2023/7/31 11:50
     */

    public static Object getAmountFieldCurrencyKey(IFormView view,String amountKey){
        IDataModel model = view.getModel();
        AmountEdit marketPriceEdit = (AmountEdit)view.getControl(amountKey);
        AmountProp marketPriceProperty = (AmountProp)marketPriceEdit.getProperty();
        String marketPriceCurrName = marketPriceProperty.getControlPropName();
        if(YEM.isNotEmpty(marketPriceCurrName)){
            Object marketPriceCurr = model.getValue(marketPriceCurrName);
            return marketPriceCurr;
        }else{
            return null;
        }
    }


    /**
     * @description 明细信息的业务分类为配件时，
     * 1、基础机型锁定并清空
     * 2、多功能配置页签信息清空
     * @author xwudd
     * @param[1] rowIndex
     * @time 2023/8/3 10:26
     */

    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");
        }else{
            view.setEnable(true,rowIndex,"yem_productmodel");

        }
    }

    /**
     * @description 基础机型清空 清空多功能配置子分录
     * @author xwudd
     * @param[1] rowIndex
     * return
     * @time 2023/8/3 10:37
     */

    public static void multiConfig(IDataModel model,int rowIndex){
        model.deleteEntryData("yem_multiconfig");
    }


    /**
     * @description 贷记单审核反写配件资金池 汇总来源汇总信息和表头财务信息方法
     * @author xwudd
     * @param[1] bill 配件资金池实体
     * @time 2023/8/7 18:00
     */

    public static void countTotalSpCapitalPool(DynamicObject bill){
        DynamicObjectCollection spCapitalPool_os = bill.getDynamicObjectCollection("yem_spcapitalpool_o");
        Map<Long,Map<Long,Map<String, BigDecimal>>> map = new HashMap();
        for(DynamicObject spCapitalPool_o : spCapitalPool_os){
            DynamicObject originType = spCapitalPool_o.getDynamicObject("yem_origintype");
            DynamicObject originCurr = spCapitalPool_o.getDynamicObject("yem_origincurr");
            if(YEM.isNotEmpty(originType) && YEM.isNotEmpty(originCurr)){
                Long originTypeId = originType.getLong("id");
                Long originCurrId = originCurr.getLong("id");
                if(map.containsKey(originTypeId)){
                    Map<Long, Map<String, BigDecimal>> currMap = map.get(originTypeId);
                    if(currMap.containsKey(originCurrId)){
                        Map<String, BigDecimal> valueMap = currMap.get(originCurrId);
                        valueMap.put("originAmt",valueMap.get("originAmt").add(spCapitalPool_o.getBigDecimal("yem_originamt")));
                        valueMap.put("amountBase",valueMap.get("amountBase").add(spCapitalPool_o.getBigDecimal("yem_amountbase")));
                        valueMap.put("chargeOffAmt",valueMap.get("chargeOffAmt").add(spCapitalPool_o.getBigDecimal("yem_chargeoffamt")));
                        valueMap.put("chargeOffAmtBase",valueMap.get("chargeOffAmtBase").add(spCapitalPool_o.getBigDecimal("yem_chargeoffamtbase")));
                        valueMap.put("residueAvaAmt",valueMap.get("residueAvaAmt").add(spCapitalPool_o.getBigDecimal("yem_residueavaamt")));
                        valueMap.put("residueAvaAmtBase",valueMap.get("residueAvaAmtBase").add(spCapitalPool_o.getBigDecimal("yem_residueavaamtbase")));
                    }else{
                        Map<String, BigDecimal> valueMap = new HashMap<>();
                        valueMap.put("originAmt",spCapitalPool_o.getBigDecimal("yem_originamt"));
                        valueMap.put("amountBase",spCapitalPool_o.getBigDecimal("yem_amountbase"));
                        valueMap.put("chargeOffAmt",spCapitalPool_o.getBigDecimal("yem_chargeoffamt"));
                        valueMap.put("chargeOffAmtBase",spCapitalPool_o.getBigDecimal("yem_chargeoffamtbase"));
                        valueMap.put("residueAvaAmt",spCapitalPool_o.getBigDecimal("yem_residueavaamt"));
                        valueMap.put("residueAvaAmtBase",spCapitalPool_o.getBigDecimal("yem_residueavaamtbase"));
                        currMap.put(originCurrId,valueMap);
                    }
                }else{
                    Map<Long,Map<String, BigDecimal>> currMap = new HashMap<>();
                    Map<String, BigDecimal> valueMap = new HashMap<>();
                    valueMap.put("originAmt",spCapitalPool_o.getBigDecimal("yem_originamt"));
                    valueMap.put("amountBase",spCapitalPool_o.getBigDecimal("yem_amountbase"));
                    valueMap.put("chargeOffAmt",spCapitalPool_o.getBigDecimal("yem_chargeoffamt"));
                    valueMap.put("chargeOffAmtBase",spCapitalPool_o.getBigDecimal("yem_chargeoffamtbase"));
                    valueMap.put("residueAvaAmt",spCapitalPool_o.getBigDecimal("yem_residueavaamt"));
                    valueMap.put("residueAvaAmtBase",spCapitalPool_o.getBigDecimal("yem_residueavaamtbase"));
                    currMap.put(originCurrId,valueMap);
                    map.put(originTypeId,currMap);
                }
            }
        }

        BigDecimal amountBaseTotal = BigDecimal.ZERO;
        BigDecimal chargeOffAmtBaseTotal = BigDecimal.ZERO;
        BigDecimal residueAvaAmtBaseTotal = BigDecimal.ZERO;
        DynamicObjectCollection spCapitalPool_as = bill.getDynamicObjectCollection("yem_spcapitalpool_a");
        spCapitalPool_as.clear();
        Set<Long> originTypeIds = map.keySet();
        for(Long originTypeId : originTypeIds){
            Map<Long, Map<String, BigDecimal>> originCurrMap = map.get(originTypeId);
            Set<Long> originCurrIds = originCurrMap.keySet();
            for(Long originCurrId : originCurrIds){
                DynamicObject addNew = spCapitalPool_as.addNew();
                Map<String, BigDecimal> valueMap = originCurrMap.get(originCurrId);
                addNew.set("yem_creditype",originTypeId);
                addNew.set("yem_curr",originCurrId);
                //结算币别
                addNew.set("yem_sumamo",valueMap.get("originAmt"));
                addNew.set("yem_useamo",valueMap.get("chargeOffAmt"));
                addNew.set("yem_noamo",valueMap.get("residueAvaAmt"));
                //本位币
                BigDecimal amountBase = valueMap.get("amountBase");
                amountBaseTotal = amountBaseTotal.add(amountBase);
                addNew.set("yem_sumamobase",amountBase);
                BigDecimal chargeOffAmtBase = valueMap.get("chargeOffAmtBase");
                chargeOffAmtBaseTotal = chargeOffAmtBaseTotal.add(chargeOffAmtBase);
                addNew.set("yem_useamobase",chargeOffAmtBase);
                BigDecimal residueAvaAmtBase = valueMap.get("residueAvaAmtBase");
                residueAvaAmtBaseTotal = residueAvaAmtBaseTotal.add(residueAvaAmtBase);
                addNew.set("yem_noamobase",residueAvaAmtBase);
            }
        }
        bill.set("yem_partsamtsum",amountBaseTotal);
        bill.set("yem_totalusedamt",chargeOffAmtBaseTotal);
        bill.set("yem_surplusamt",residueAvaAmtBaseTotal);

    }





    public static void viewBill(IFormView view,String formId,Object pkId){
        BillShowParameter bsp = new BillShowParameter();
        bsp.setFormId(formId);
        bsp.setPkId(pkId);
        bsp.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        bsp.setStatus(OperationStatus.VIEW);
        view.showForm(bsp);
    }

    /**
     * @description
     * @author xwudd
     * @param[1] entity
     * return
     * @time 2023/8/14 10:16
     */

    public static void delDetailRowCalcuInfo(DynamicObject entity)
    {
        String sourceBillType = entity.getString("yem_sourcebilltype");
        long sourceBillId = entity.getLong("yem_sourcebillid");
        long sourceEntryId = entity.getLong("yem_sourceentryid");
        DynamicObject bill = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
        if (YEM.isNotEmpty(bill)) {
            DynamicObjectCollection detailedInfos = null;
            if ("yem_im_clientdemand".equals(sourceBillType)) {
                detailedInfos = bill.getDynamicObjectCollection("yem_im_detailedinfor");
            } else {
                detailedInfos = bill.getDynamicObjectCollection("yem_es_materialinfo");
            }
            long id = entity.getLong("id");
//            for (DynamicObject detailedInfo : detailedInfos) {
//                if (detailedInfo.getLong("id") == sourceEntryId) {
//                    detailedInfo.set("yem_intauditbusano", null);
//                    detailedInfo.set("yem_intauditbusaid", null);
//                    break;
//                }
//            }
            for (DynamicObject detailedInfo : detailedInfos) {
                Object existIdObj = detailedInfo.get("yem_intauditbusaid");
                if (YEM.isNotEmpty(existIdObj)) {
                    Long existId = (Long) existIdObj;
                    if (existId == id) {
                        detailedInfo.set("yem_intauditbusano", null);
                        detailedInfo.set("yem_intauditbusaid", null);
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{bill});
        }
    }

    /**
     * @description 生成内审预算单
     * @author xwudd
     * @param[1] e
     * @param[2] entryKey
     * @param[3] payEntryKey
     * return
     * @time 2023/8/14 10:37
     */

    public static void clientDemandStartZj(AbstractFormPlugin e,String entryKey,String payEntryKey){
        IFormView view = e.getView();
        IDataModel model = view.getModel();
        OperationStatus status = view.getFormShowParameter().getStatus();
        if(status == OperationStatus.ADDNEW){
            view.showErrorNotification("请先保存单据，再生成内审预算单！");
            return;
        }
        String inCommission = (String)model.getValue("yem_incommission");
        if("A".equals(inCommission)){
            BigDecimal commissionAmt = (BigDecimal)model.getValue("yem_commissionamt");
            if(commissionAmt.compareTo(BigDecimal.ZERO) <= 0){
                view.showErrorNotification("请先维护佣金，才能生成内审预算单！");
                return;
            }
        }
        List<String> strList = new ArrayList<>();
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObjectCollection detailEntrys = dataEntity.getDynamicObjectCollection(entryKey);
        EntryGrid entryGrid = view.getControl(entryKey);
        int[] selectRows = entryGrid.getSelectRows();
        for(int selectRow : selectRows){
            Boolean flag = false;
            String intAuditBuSaNo = (String)model.getValue("yem_intauditbusano");
            Object tempIntauditbusaid = model.getValue("yem_intauditbusaid");
            long intAuditBuSaId = 0l;
            if(tempIntauditbusaid instanceof Long){
                intAuditBuSaId = (long) tempIntauditbusaid;
            }
            String businessSort = (String)model.getValue("yem_businesssort", selectRow);
            if("P".equals(businessSort)){
                strList.add(selectRow+ 1 + "");
                continue;
            }
            DynamicObject intAuditBusAcc = null;
            if(YEM.isNotEmpty(intAuditBuSaNo) || YEM.isNotEmpty(intAuditBuSaId)){
                intAuditBusAcc = BusinessDataServiceHelper.loadSingle(intAuditBuSaId,"yem_im_intauditbusa");
                UpdateManualFilling(intAuditBusAcc,model);
                removeAtt(intAuditBusAcc);
                flag = false;
            }else{
                intAuditBusAcc = BusinessDataServiceHelper.newDynamicObject("yem_im_intauditbusa");
                setIntAuditBillType(intAuditBusAcc,view);//单据类型赋值
                setBillInfo(intAuditBusAcc,dataEntity,detailEntrys.get(selectRow).getLong("id"));
                intAuditBusAcc.set("org",model.getValue("org"));
                intAuditBusAcc.set("creator",RequestContext.get().getCurrUserId());//创建人
                intAuditBusAcc.set("createtime",new Date());//创建时间
                flag = true;
            }
            intAuditBusAcc.set("yem_sourceentryseq",selectRow + 1);
            intAuditBusAcc.set("billstatus","A");//单据状态
            intAuditBusAcc.set("creator",RequestContext.get().getCurrUserId());//创建人
            setIntAuditGaugeOutfit(intAuditBusAcc,model,selectRow,payEntryKey);//表头字段赋值
            setIntAuditMultiConfig(intAuditBusAcc,model,detailEntrys.get(selectRow),selectRow);//多功能配置分录赋值
            setIntAuditCostInfo(intAuditBusAcc,model,selectRow);//费用信息分录赋值
            setInsurancePremiums(intAuditBusAcc);//保险费默认等于保费，保险费人民币默认等于保费人民币；
            saveIntAuditBusAcc(view,model,intAuditBusAcc,flag,selectRow);
        }
        if(strList.size() > 0){
            view.showMessage("选中行中，第" + String.join(",",strList) + "行，业务分类为配件，无法生存内审核算单！");
        }
        view.invokeOperation("refresh");
    }

    private static void setInsurancePremiums(DynamicObject intAuditBusAcc)
    {
        BigDecimal marinsupreamt = intAuditBusAcc.getBigDecimal("yem_marinsupreamt");//保费
        BigDecimal marinsupreamtbase = intAuditBusAcc.getBigDecimal("yem_marinsupreamtbase");//保费人民币

        intAuditBusAcc.set("yem_premium", marinsupreamt);
        intAuditBusAcc.set("yem_premiumba", marinsupreamtbase);

    }

    public void zjNewDynamic(){

    }
    public static void clientDemandStartPj(AbstractFormPlugin e,String entryKey,String payEntryKey){
        IFormView view = e.getView();
        IDataModel model = view.getModel();
        int entryRowCount = model.getEntryRowCount(entryKey);
        OperationStatus status = view.getFormShowParameter().getStatus();
        if(status == OperationStatus.ADDNEW){
            view.showErrorNotification("请先保存单据，再生成内审预算单！");
            return;
        }
        if(!(entryRowCount > 0)){
            view.showErrorNotification("请填写商品明细信息！");
            return;
        }
        String inCommission = (String)model.getValue("yem_incommission");
        if("A".equals(inCommission)){
            BigDecimal commissionAmt = (BigDecimal)model.getValue("yem_commissionamt");
            if(commissionAmt.compareTo(BigDecimal.ZERO) <= 0){
                view.showErrorNotification("请先维护佣金，才能生成内审预算单！");
                return;
            }
        }
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObjectCollection detailEntrys = dataEntity.getDynamicObjectCollection(entryKey);
        Boolean flag = false;
        String intAuditBuSaNo = (String)model.getValue("yem_intauditbusano",0);
        Long intAuditBuSaId = (Long) model.getValue("yem_intauditbusaid",0);
        DynamicObject intAuditBusAcc = null;
        if(YEM.isNotEmpty(intAuditBuSaNo) || YEM.isNotEmpty(intAuditBuSaId)){
            intAuditBusAcc = BusinessDataServiceHelper.loadSingle(intAuditBuSaId,"yem_im_intauditbusa");
            UpdateManualFilling(intAuditBusAcc,model);
            removeAtt(intAuditBusAcc);
            flag = false;
        }else{
            intAuditBusAcc = BusinessDataServiceHelper.newDynamicObject("yem_im_intauditbusa");
            setIntAuditBillType(intAuditBusAcc,view);//单据类型赋值
            intAuditBusAcc.set("org",model.getValue("org"));
            intAuditBusAcc.set("creator",RequestContext.get().getCurrUserId());//创建人
            intAuditBusAcc.set("createtime",new Date());//创建时间
            setBillInfo(intAuditBusAcc,dataEntity,detailEntrys.get(0).getLong("id"));
            flag = true;
        }
        intAuditBusAcc.set("billstatus","A");//单据状态
        intAuditBusAcc.set("creator",RequestContext.get().getCurrUserId());//创建人
        setIntAuditGaugeOutfit(intAuditBusAcc,model,entryKey,payEntryKey);//表头字段赋值
        setIntAuditCostInfo(intAuditBusAcc,model);//费用信息分录赋值

        saveIntAuditBusAcc(view,model,intAuditBusAcc,flag);
        view.invokeOperation("refresh");
    }

    /**
     * @description 整机
     * @author xwudd
     * @param[1] view
     * @param[2] model
     * @param[3] intAuditBusAcc
     * @param[4] flag
     * @param[5] selectRow
     * return
     * @time 2023/9/21 15:59
     */

    public static void saveIntAuditBusAcc(IFormView view,IDataModel model,DynamicObject intAuditBusAcc,Boolean flag,int selectRow){
        OperationResult saveResult = OperationServiceHelper.executeOperate("save", "yem_im_intauditbusa", new DynamicObject[]{intAuditBusAcc}, OperateOption.create());
        if(saveResult.isSuccess()){
            if(flag){
                model.setValue("yem_intauditbusano",intAuditBusAcc.getString("billno"),selectRow);
                model.setValue("yem_intauditbusaid",intAuditBusAcc.getPkValue(),selectRow);
                view.showSuccessNotification("生成选中行内审预算单成功！");
                view.invokeOperation("save");
                viewBill(view,"yem_im_intauditbusa",intAuditBusAcc.getPkValue());
            }else{
                view.invokeOperation("save");
                view.showSuccessNotification("生成选中行内审预算单更新数据成功！");
            }

        }else{
            view.showErrorNotification("生成选中行内审预算单失败！");
        }
    }

    /**
     * @description 配件
     * @author xwudd
     * @param[1] view
     * @param[2] model
     * @param[3] intAuditBusAcc
     * @param[4] flag
     * return
     * @time 2023/9/21 15:59
     */

    public static void saveIntAuditBusAcc(IFormView view,IDataModel model,DynamicObject intAuditBusAcc,Boolean flag){
        OperationResult saveResult = OperationServiceHelper.executeOperate("save", "yem_im_intauditbusa", new DynamicObject[]{intAuditBusAcc}, OperateOption.create());
        if(saveResult.isSuccess()){
            if(flag){
                model.setValue("yem_intauditbusano",intAuditBusAcc.getString("billno"),0);
                model.setValue("yem_intauditbusaid",intAuditBusAcc.getPkValue(),0);
                view.showSuccessNotification("生成选中行内审预算单成功！");
                view.invokeOperation("save");
                viewBill(view,"yem_im_intauditbusa",intAuditBusAcc.getPkValue());
            }else{
                view.invokeOperation("save");
                view.showSuccessNotification("生成选中行内审预算单更新数据成功！");
            }

        }else{
            view.showErrorNotification("生成选中行内审预算单失败！");
        }
    }

    /**
     * @description 内审预算单单据类型赋值
     * @author xwudd
     * @param[1] intAuditBusAcc 内审预算单实体
     * @param[2] view 生成内审预算单的单据视图层
     * @time 2023/8/11 11:30
     */
    public static void setIntAuditBillType(DynamicObject intAuditBusAcc,IFormView view){
        QFilter qFilter = null;
        String formId = view.getFormShowParameter().getFormId();
        switch(formId){
            case "yem_im_clientdeman_zj" :
            case "yem_es_salesorder_zj" :
            case "yem_im_inclientdeman_zj" :
            case "yem_es_salesorder_nmzj" :
                qFilter = new QFilter("number",QCP.equals,"yem_im_intauditbusa_ZJWX");
                break;
            case "yem_im_clientdema_pj" :
            case "yem_es_salesorder_pj" :
            case "yem_im_inclientdema_pj" :
            case "yem_es_salesorder_nmpj" :
                qFilter = new QFilter("number",QCP.equals,"yem_im_intauditbusa_PJWX");
                break;
        }
        if(qFilter != null){
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
            intAuditBusAcc.set("yem_billtype",billType);
        }

    }

    /**
     * @description 整机内审预算单表头字段类型赋值
     * @author xwudd
     * @param[1] intAuditBusAcc
     * @param[2] model
     * @param[3] selectRow
     * return
     * @time 2023/8/11 16:07
     */
    public static void setIntAuditGaugeOutfit(DynamicObject intAuditBusAcc,IDataModel model,int selectRow,String payEntryKey){
        //基本信息
        intAuditBusAcc.set("yem_number",selectRow);//单据编号  <--  客户需求单-分录行序号
        intAuditBusAcc.set("yem_billnopact",model.getValue("billno"));//合同编号                    <--  客户需求单-单据编号
        intAuditBusAcc.set("yem_customer",model.getValue("yem_customer"));//客户名称                <--  客户需求单-客户
        intAuditBusAcc.set("yem_clientcountry",model.getValue("yem_clientcountry"));//买方国家      <--  客户需求单-贸易国别
        intAuditBusAcc.set("yem_reccondition",model.getValue("yem_reccondition"));//付款方式        <--  客户需求单-收款条件
        intAuditBusAcc.set("yem_bizdate",model.getValue("yem_bizdate"));//需求日期                  <--  客户需求单-报价日期
        intAuditBusAcc.set("yem_operator",model.getValue("yem_operator"));//人员                   <--  客户需求单-销售员
        intAuditBusAcc.set("yem_bd_products",model.getValue("yem_bd_products"));//产品分类          <--  客户需求单-产品分类
        intAuditBusAcc.set("yem_priceitem",model.getValue("yem_priceitem"));//价格条款              <--  客户需求单-价格条款
        intAuditBusAcc.set("yem_transportstyle",model.getValue("yem_transportstyle"));//运输方式    <--  客户需求单-运输方式
        String partsfollowcar = (String) model.getValue("yem_partsfollowcar");
        String partsfollowcarName = "";
        if ("Y".equals(partsfollowcar)) {
            partsfollowcarName = "是";
        }
        if ("N".equals(partsfollowcar)) {
            partsfollowcarName = "否";
        }
        intAuditBusAcc.set("yem_partsfollowcar", partsfollowcarName);
        DynamicObject cnperson = (DynamicObject) model.getValue("yem_cnperson");
        if (cnperson != null) {
            DynamicObject bd_customer = BusinessDataServiceHelper.loadSingle(cnperson.getPkValue(), "bd_customer");
            if (bd_customer != null) {
                intAuditBusAcc.set("yem_intermediary", bd_customer.getString("name"));
            } else {
                intAuditBusAcc.set("yem_intermediary", "");
            }
        } else {
            intAuditBusAcc.set("yem_intermediary", "");
        }

        //核算信息赋值
        DynamicObject productModel = (DynamicObject)model.getValue("yem_productmodel", selectRow);
        DynamicObject products = YEM.isNotEmpty(productModel)?productModel.getDynamicObject("yem_products"):null;
        BigDecimal bigCabinetNumbers = (BigDecimal) model.getValue("yem_bigcabinetnumbers", selectRow);
        BigDecimal minCabinetNumbers = (BigDecimal) model.getValue("yem_mincabinetnumbers", selectRow);
        DynamicObject bigCabinet = (DynamicObject)model.getValue("yem_bigcabinet", selectRow);
        DynamicObject minCabinet = (DynamicObject)model.getValue("yem_mincabinet", selectRow);
        DynamicObjectCollection destPorts = (DynamicObjectCollection) model.getValue("yem_destports");
        DynamicObjectCollection newDestPorts = intAuditBusAcc.getDynamicObjectCollection("yem_destports");
        DynamicObjectCollection shipPorts = (DynamicObjectCollection) model.getValue("yem_shipports");
        DynamicObjectCollection newShipPorts = intAuditBusAcc.getDynamicObjectCollection("yem_shipports");
        getNewMulti(destPorts,newDestPorts);
        getNewMulti(shipPorts,newShipPorts);
        intAuditBusAcc.set("yem_productmodel",products);//出口机型
        intAuditBusAcc.set("yem_deliverydate",model.getValue("yem_deliverydate"));
        intAuditBusAcc.set("yem_ordernumber",model.getValue("yem_ordersumnumber"));//订单总台数
        intAuditBusAcc.set("yem_singlenumber",model.getValue("yem_singlenumber"));//本单票数
        intAuditBusAcc.set("yem_destports",newDestPorts);//目的港
        intAuditBusAcc.set("yem_goalcountry",(DynamicObject)model.getValue("yem_clientcountry"));//目的国
        intAuditBusAcc.set("yem_shipports",newShipPorts);//起运港
        intAuditBusAcc.set("yem_unit",model.getValue("yem_unit",selectRow));//计量单位
        intAuditBusAcc.set("yem_quantityrequired",model.getValue("yem_qty", selectRow));//出口台数
        intAuditBusAcc.set("yem_bigcabinetnumber", model.getValue("yem_bigcabinetnumber"));//大柜数量
        intAuditBusAcc.set("yem_mincabinetnumber", model.getValue("yem_mincabinetnumber"));//小柜数量
        intAuditBusAcc.set("yem_resourceid",model.getValue("yem_resourcenog",selectRow));//产品资源号
        intAuditBusAcc.set("yem_orderallocation",model.getValue("yem_orderallocation",selectRow));//订单配置要求

        if(YEM.isNotEmpty(bigCabinet) && YEM.isNotEmpty(minCabinet)){

            StringBuilder name = new StringBuilder();

            int big = bigCabinetNumbers.intValue();

            int min = minCabinetNumbers.intValue();

            if (big > 0) {
                name.append(big).append("*").append(bigCabinet.getString("name"));
            }

            if (min > 0) {
                if (big > 0) {
                    name.append(";");
                }
                name.append(min).append("*").append(minCabinet.getString("name"));
            }

//            String name = stringDelTailZero(bigCabinetNumbers.toString()) + "*" + bigCabinet.getString("name") + ";"
//                    + stringDelTailZero(minCabinetNumbers.toString()) + "*" + minCabinet.getString("name");
            intAuditBusAcc.set("yem_encasementype",name);//装箱方式

        }

        //财务信息
        BigDecimal exrate = (BigDecimal)model.getValue("yem_exrate");
        BigDecimal cnExRate = (BigDecimal)model.getValue("yem_cnexrate");
        BigDecimal oneCarCom = (BigDecimal)model.getValue("yem_onecarcom",selectRow);
        intAuditBusAcc.set("yem_currency",model.getValue("yem_currency"));//结算币别
        intAuditBusAcc.set("yem_currencybase",model.getValue("yem_currencybase"));//本位币
        intAuditBusAcc.set("yem_exratetable",model.getValue("yem_exratetable"));//汇率表
        intAuditBusAcc.set("yem_exratedate",model.getValue("yem_exratedate"));//汇率日期
        intAuditBusAcc.set("yem_exrate",exrate);//汇率
        intAuditBusAcc.set("yem_quotation",model.getValue("yem_quotation"));//换算方式
        intAuditBusAcc.set("yem_cncurrency",model.getValue("yem_cncurrency"));//佣金币别
        intAuditBusAcc.set("yem_cnexrate",cnExRate);//佣金汇率
        intAuditBusAcc.set("yem_commissionamt",oneCarCom);//佣金
        intAuditBusAcc.set("yem_commissionamtba",oneCarCom.multiply(cnExRate));//佣金（人民币）
        intAuditBusAcc.set("yem_insurancefeerate",model.getValue("yem_insurancefeerate"));//保险费率%
        intAuditBusAcc.set("yem_insuranceaddrate",model.getValue("yem_insuranceaddrate"));//保险加成率%
        intAuditBusAcc.set("yem_sastandardprice",model.getValue("yem_sastandardprice", selectRow));//标准配置基本价格（FOB）青岛
        intAuditBusAcc.set("yem_sastandardpriceba",model.getValue("yem_sastandardpricesa", selectRow));//标准配置基本价格（FOB）青岛（人民币）
        BigDecimal priceFieldAccBa = (BigDecimal)model.getValue("yem_pricefieldaccba", selectRow);
        intAuditBusAcc.set("yem_pricefieldaccba",priceFieldAccBa);//资源配置单价
        intAuditBusAcc.set("yem_pricefieldaccbase",priceFieldAccBa.multiply(exrate));//资源配置单价（人民币）
        countSumCost(intAuditBusAcc);
        //赋值信保费率%
        int payAmtRows = model.getEntryRowCount(payEntryKey);
        for (int i = 0; i < payAmtRows; i++) {
            String isSinosure = (String)model.getValue("yem_issinosure");
            if("A".equals(isSinosure)){
                BigDecimal sinosureRate = (BigDecimal)model.getValue("yem_sinosurerate");
                if(sinosureRate.compareTo(BigDecimal.ZERO) > 0){
                    intAuditBusAcc.set("yem_creditrate",sinosureRate);
                    break;
                }
            }
        }
        //赋值拆装费用
        if(YEM.isNotEmpty(products)){
            DynamicObject costs = BusinessDataServiceHelper.loadSingle("yem_bd_costs", "id,yem_detail.yem_bd_mechanical,yem_detail.yem_tearamount",
                    new QFilter[]{new QFilter("yem_detail.yem_bd_mechanical", QCP.equals, products.getPkValue())});
            if(YEM.isNotEmpty(costs)){
                DynamicObjectCollection details = costs.getDynamicObjectCollection("yem_detail");
                for(DynamicObject detail : details){
                    DynamicObject mechanical = detail.getDynamicObject("yem_bd_mechanical");
                    if(YEM.isNotEmpty(mechanical)){
                        if(mechanical.getLong("id") == products.getLong("id")){
                            intAuditBusAcc.set("yem_dismountingcostba",detail.get("yem_tearamount"));
                            if(exrate.compareTo(BigDecimal.ZERO) > 0){
                                intAuditBusAcc.set("yem_dismountingcost",detail.getBigDecimal("yem_tearamount").divide(exrate, RoundingMode.HALF_UP));
                            }
                            break;
                        }
                    }
                }
            }
        }


    }


    public static String stringDelTailZero(String str){
        char[] chars = str.toCharArray();
        for (int i = chars.length - 1; i >= 0; i--) {
            if(chars[i] == '0'){
                continue;
            }else{
                str = str.substring(0,i + 1);
            }
        }
        return str;
    }

    /**
     * @description 配件内审核算单 表头字段赋值
     * @author xwudd
     * @param[1] intAuditBusAcc
     * @param[2] model
     * @param[3] selectRow
     * @param[4] payEntryKey
     * return
     * @time 2023/8/14 9:59
     */

    public static void setIntAuditGaugeOutfit(DynamicObject intAuditBusAcc,IDataModel model,String entryKey,String payEntryKey){
        //基本信息
        intAuditBusAcc.set("yem_billnopact",model.getValue("billno"));//合同编号                    <--  客户需求单-单据编号
        intAuditBusAcc.set("yem_customer",model.getValue("yem_customer"));//客户名称                <--  客户需求单-客户
        intAuditBusAcc.set("yem_clientcountry",model.getValue("yem_clientcountry"));//买方国家      <--  客户需求单-贸易国别
        intAuditBusAcc.set("yem_reccondition",model.getValue("yem_reccondition"));//付款方式        <--  客户需求单-收款条件
        intAuditBusAcc.set("yem_bizdate",model.getValue("yem_bizdate"));//需求日期                  <--  客户需求单-报价日期
        intAuditBusAcc.set("yem_operator",model.getValue("yem_operator"));//人员                   <--  客户需求单-销售员
        intAuditBusAcc.set("yem_bd_products",model.getValue("yem_bd_products"));//产品分类          <--  客户需求单-产品分类
        intAuditBusAcc.set("yem_priceitem",model.getValue("yem_priceitem"));//价格条款              <--  客户需求单-价格条款
        intAuditBusAcc.set("yem_transportstyle",model.getValue("yem_transportstyle"));//运输方式    <--  客户需求单-运输方式
        String partsfollowcar = (String) model.getValue("yem_partsfollowcar");
        String partsfollowcarName = "";
        if ("Y".equals(partsfollowcar)) {
            partsfollowcarName = "是";
        }
        if ("N".equals(partsfollowcar)) {
            partsfollowcarName = "否";
        }
        intAuditBusAcc.set("yem_partsfollowcar", partsfollowcarName);

        DynamicObject cnperson = (DynamicObject) model.getValue("yem_cnperson");
        if (cnperson != null) {
            DynamicObject bd_customer = BusinessDataServiceHelper.loadSingle(cnperson.getPkValue(), "bd_customer");
            if (bd_customer != null) {
                intAuditBusAcc.set("yem_intermediary", bd_customer.getString("name"));
            } else {
                intAuditBusAcc.set("yem_intermediary", "");
            }
        } else {
            intAuditBusAcc.set("yem_intermediary", "");
        }
        intAuditBusAcc.set("yem_fundpoolamt", model.getValue("yem_fundpoolamt"));//贷记单使用额度


        //核算信息赋值
        BigDecimal bigCabinetNumbers = (BigDecimal) model.getValue("yem_bigcabinetnumber");
        BigDecimal minCabinetNumbers = (BigDecimal) model.getValue("yem_mincabinetnumber");
        DynamicObjectCollection destPorts = (DynamicObjectCollection) model.getValue("yem_destports");
        DynamicObjectCollection newDestPorts = intAuditBusAcc.getDynamicObjectCollection("yem_destports");
        DynamicObjectCollection shipPorts = (DynamicObjectCollection) model.getValue("yem_shipports");
        DynamicObjectCollection newShipPorts = intAuditBusAcc.getDynamicObjectCollection("yem_shipports");
        getNewMulti(destPorts,newDestPorts);
        getNewMulti(shipPorts,newShipPorts);
        intAuditBusAcc.set("yem_deliverydate",model.getValue("yem_deliverydate"));
        intAuditBusAcc.set("yem_singlenumber",model.getValue("yem_singlenumber"));//本单票数
        intAuditBusAcc.set("yem_destports",newDestPorts);//目的港
        intAuditBusAcc.set("yem_goalcountry",model.getValue("yem_clientcountry"));//目的国
        intAuditBusAcc.set("yem_shipports",newShipPorts);//起运港
        intAuditBusAcc.set("yem_bigcabinetnumber",bigCabinetNumbers);//大柜数量
        intAuditBusAcc.set("yem_mincabinetnumber",minCabinetNumbers);//小柜数量

        //财务信息
        BigDecimal exrate = (BigDecimal)model.getValue("yem_exrate");
        BigDecimal cnExRate = (BigDecimal)model.getValue("yem_cnexrate");
        BigDecimal comMissionAmt = (BigDecimal)model.getValue("yem_commissionamt");
        BigDecimal comMissionAmtBa = (BigDecimal)model.getValue("yem_commissionamtba");
        BigDecimal insuranceFeeRate = (BigDecimal)model.getValue("yem_insurancefeerate");
        BigDecimal insuranceAddRate = (BigDecimal)model.getValue("yem_insuranceaddrate");
        intAuditBusAcc.set("yem_currency",model.getValue("yem_currency"));//结算币别
        intAuditBusAcc.set("yem_currencybase",model.getValue("yem_currencybase"));//本位币
        intAuditBusAcc.set("yem_exratetable",model.getValue("yem_exratetable"));//汇率表
        intAuditBusAcc.set("yem_exratedate",model.getValue("yem_exratedate"));//汇率日期
        intAuditBusAcc.set("yem_exrate",exrate);//汇率
        intAuditBusAcc.set("yem_quotation",model.getValue("yem_quotation"));//换算方式
        intAuditBusAcc.set("yem_cncurrency",model.getValue("yem_cncurrency"));//佣金币别
        intAuditBusAcc.set("yem_cnexrate",cnExRate);//佣金汇率
        intAuditBusAcc.set("yem_commissionamt",comMissionAmt);//佣金
        intAuditBusAcc.set("yem_commissionamtba",comMissionAmtBa);//佣金（人民币）
        intAuditBusAcc.set("yem_insurancefeerate",insuranceFeeRate);//保险费率%
        intAuditBusAcc.set("yem_insuranceaddrate",insuranceAddRate);//保险加成率%

        BigDecimal saFobAmountTotal = BigDecimal.ZERO;
        BigDecimal saFobAmountBaseTotal = BigDecimal.ZERO;
        int entryRows = model.getEntryRowCount(entryKey);
        for (int i = 0; i < entryRows; i++) {
            Boolean ifGift = (Boolean)model.getValue("yem_ifgift",i);
            if(!ifGift){
                saFobAmountTotal = saFobAmountTotal.add((BigDecimal)model.getValue("yem_safobamount",i));
                saFobAmountBaseTotal = saFobAmountBaseTotal.add((BigDecimal)model.getValue("yem_safobamountbase",i));
            }
        }
        BigDecimal marinSuPreAmt = saFobAmountTotal.multiply(insuranceFeeRate).multiply(insuranceAddRate).divide(new BigDecimal(100));
        intAuditBusAcc.set("yem_carloadfobprice",saFobAmountTotal);//exw
        intAuditBusAcc.set("yem_carloadfobpriceba",saFobAmountBaseTotal);//exw
        intAuditBusAcc.set("yem_contractpricesum",saFobAmountTotal);//合同总金额
        intAuditBusAcc.set("yem_contractpricesumba",saFobAmountBaseTotal);//合同总金额人民币
        intAuditBusAcc.set("yem_marinsupreamt",marinSuPreAmt);//海运保险费
        intAuditBusAcc.set("yem_marinsupreamtbase",marinSuPreAmt.multiply(exrate));//海运保险费人民币



        countSumCost(intAuditBusAcc);
        //赋值信保费率%
        int payAmtRows = model.getEntryRowCount(payEntryKey);
        for (int i = 0; i < payAmtRows; i++) {
            String isSinosure = (String)model.getValue("yem_issinosure");
            if("A".equals(isSinosure)){
                BigDecimal sinosureRate = (BigDecimal)model.getValue("yem_sinosurerate",i);
                if(sinosureRate.compareTo(BigDecimal.ZERO) > 0){
                    intAuditBusAcc.set("yem_creditrate",sinosureRate);
                    break;
                }
            }
        }
    }

    /**
     * @description 内审预算单多功能配置表赋值
     * @author xwudd
     * @param[1] intAuditBusAcc
     * @param[2] model
     * @param[3] materialEntry
     * @param[4] selectRow
     * return
     * @time 2023/8/11 16:08
     */

    public static void setIntAuditMultiConfig(DynamicObject intAuditBusAcc,IDataModel model,DynamicObject materialEntry,int selectRow){
        BigDecimal totalUnitSetAmount = BigDecimal.ZERO;
        BigDecimal qty = (BigDecimal)model.getValue("yem_qty", selectRow);
        BigDecimal exrate = intAuditBusAcc.getBigDecimal("yem_exrate");
        DynamicObjectCollection multiConfigs = intAuditBusAcc.getDynamicObjectCollection("yem_im_intauditbusa_b");
        DynamicObjectCollection contractMultiConfigs = materialEntry.getDynamicObjectCollection("yem_multiconfig");
        multiConfigs.clear();
        for (DynamicObject contractMultiConfig : contractMultiConfigs) {
            DynamicObject addNew = multiConfigs.addNew();
            BigDecimal unitsetamount = (BigDecimal)contractMultiConfig.get("yem_unitsetamount");
            addNew.set("yem_configurtype",contractMultiConfig.get("yem_configurtype"));//配置类型
            addNew.set("yem_configurname",contractMultiConfig.get("yem_configurname"));//配置名称
            addNew.set("yem_marketraiseprice",contractMultiConfig.get("yem_marketraiseprice"));//标准销售加价
            addNew.set("yem_unitsetnumber",contractMultiConfig.get("yem_unitsetnumber"));//单台数量
            addNew.set("yem_unitsetamount",unitsetamount);//单台加价金额
            addNew.set("yem_unitsetamountbase",contractMultiConfig.get("yem_unitsetamountbase"));//单台加价金额
            totalUnitSetAmount = totalUnitSetAmount.add(unitsetamount);
        }
        BigDecimal totalUnitSetAmountBase = totalUnitSetAmount.multiply(exrate);
        BigDecimal saStandardPrice = (BigDecimal)model.getValue("yem_sastandardprice", selectRow);
        BigDecimal saStandardPriceSa = (BigDecimal)model.getValue("yem_sastandardpricesa", selectRow);
        BigDecimal carLoadFobPrice = totalUnitSetAmount.add(saStandardPrice);
        BigDecimal carLoadFobPriceBase = totalUnitSetAmountBase.add(saStandardPriceSa);
        BigDecimal priceFieldAccBa = (BigDecimal) model.getValue("yem_pricefieldaccba", selectRow);
        BigDecimal priceFieldAccBase = priceFieldAccBa.multiply(exrate);
        intAuditBusAcc.set("yem_conrapricesum",totalUnitSetAmount);//配置加价合计
        intAuditBusAcc.set("yem_conrapricesumba",totalUnitSetAmountBase);//配置加价合计（人民币）
        intAuditBusAcc.set("yem_carloadfobprice",carLoadFobPrice);//整车FOB价格
        intAuditBusAcc.set("yem_carloadfobpriceba",carLoadFobPriceBase);//整车FOB价格（人民币）

        BigDecimal sumCost = intAuditBusAcc.getBigDecimal("yem_sumcost");//总费用
        BigDecimal sumCostaBase = intAuditBusAcc.getBigDecimal("yem_sumcostbase");//总费用（人民币）
        BigDecimal contractAmt = carLoadFobPrice.add(sumCost).add(priceFieldAccBa);
        BigDecimal contractAmtBase = carLoadFobPriceBase.add(sumCostaBase).add(priceFieldAccBase);
        intAuditBusAcc.set("yem_contractprice",contractAmt);//合同价格
        intAuditBusAcc.set("yem_contractpriceba",contractAmtBase);//合同价格本位币
        intAuditBusAcc.set("yem_contractpricesum",contractAmt.multiply(qty));//合同总额
        intAuditBusAcc.set("yem_contractpricesumba",contractAmtBase.multiply(qty));//合同总额本位币
        BigDecimal insuranceFeeRate = (BigDecimal)model.getValue("yem_insurancefeerate");
        BigDecimal insuranceAddRate = (BigDecimal)model.getValue("yem_insuranceaddrate");
        BigDecimal marinSuPreAmt = contractAmt.multiply(insuranceFeeRate).multiply(insuranceAddRate).divide(new BigDecimal(100));
        intAuditBusAcc.set("yem_marinsupreamt",marinSuPreAmt);
        intAuditBusAcc.set("yem_marinsupreamtbase",marinSuPreAmt.multiply(exrate));
    }

    /**
     * @description 整机内审预算单费用信息赋值
     * @author xwudd
     * @param[1] intAuditBusAcc
     * @param[2] model
     * @param[3] selectRow
     * return
     * @time 2023/8/11 16:08
     */

    public static void setIntAuditCostInfo(DynamicObject intAuditBusAcc,IDataModel model,int selectRow){
        DynamicObjectCollection costInfos = intAuditBusAcc.getDynamicObjectCollection("yem_costinfor");
        costInfos.clear();
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        Integer orderSumNumber = (Integer)model.getValue("yem_ordersumnumber");
        Integer singleNumber = (Integer)model.getValue("yem_singlenumber");
        BigDecimal bigCabinetNumbers = (BigDecimal)model.getValue("yem_bigcabinetnumber");
        BigDecimal minCabinetNumbers = (BigDecimal)model.getValue("yem_mincabinetnumber");
        int costInfoRows = model.getEntryRowCount("yem_costinfor");
        for (int i = 0; i < costInfoRows; i++) {
            DynamicObject addNew = costInfos.addNew();
            BigDecimal ticketPrice = (BigDecimal)model.getValue("yem_ticketprice", i);
            BigDecimal bigCabinetPrice = (BigDecimal)model.getValue("yem_bigcabinetprice", i);
            BigDecimal minCabinetPrice = (BigDecimal)model.getValue("yem_mincabinetprice", i);
            BigDecimal bigCabinetAmt = bigCabinetPrice.multiply(bigCabinetNumbers);
            BigDecimal minCabinetAmt = minCabinetPrice.multiply(minCabinetNumbers);
            BigDecimal byTicketAmt = ticketPrice.multiply(new BigDecimal(singleNumber));
            BigDecimal costSumAmountBba = bigCabinetAmt.add(minCabinetAmt).add(byTicketAmt);
            addNew.set("yem_addorsubc",model.getValue("yem_addorsub",i));//费用类型
            addNew.set("yem_padexpensec",model.getValue("yem_padexpense",i));//费用项目
            addNew.set("yem_bd_chargemode",model.getValue("yem_bd_chargemode",i));//计费方式
            addNew.set("yem_bigcabinetprice",bigCabinetPrice);//大柜单价
            addNew.set("yem_mincabinetprice",minCabinetPrice);//小柜单价
            addNew.set("yem_byticketprice",ticketPrice);//按票单价
            addNew.set("yem_bigcabinetamt",bigCabinetAmt);//大柜金额
            addNew.set("yem_mincabinetamt",minCabinetAmt);//小柜金额
            addNew.set("yem_byticketamt",byTicketAmt);//按票金额
            addNew.set("yem_costsumamountcba",costSumAmountBba);//费用金额本位币
            if(orderSumNumber != 0){
                BigDecimal cartFulAmountBa = costSumAmountBba.divide(new BigDecimal(orderSumNumber), RoundingMode.HALF_UP);
                addNew.set("yem_cartfulamountba",cartFulAmountBa);//单车费用金额本位币
                if(!(exrate.compareTo(BigDecimal.ZERO) == 0)){
                    addNew.set("yem_cartfulamount",cartFulAmountBa.divide(exrate, RoundingMode.HALF_UP));//单车费用金额
                }
            }
            if(!(exrate.compareTo(BigDecimal.ZERO) == 0)){
                BigDecimal costSumAmountC = costSumAmountBba.divide(exrate, RoundingMode.HALF_UP);
                addNew.set("yem_costsumamountc",costSumAmountC);//费用金额

            }

        }
    }

    /**
     * @description 配件内审预算单费用信息赋值
     * @author xwudd
     * @param[1] intAuditBusAcc
     * @param[2] model
     * return
     * @time 2023/8/11 16:08
     */

    public static void setIntAuditCostInfo(DynamicObject intAuditBusAcc,IDataModel model){
        DynamicObjectCollection costInfos = intAuditBusAcc.getDynamicObjectCollection("yem_costinfor");
        costInfos.clear();
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        Integer orderSumNumber = (Integer)model.getValue("yem_ordersumnumber");
        BigDecimal bigCabinetNumbers = (BigDecimal)model.getValue("yem_bigcabinetnumber");
        BigDecimal minCabinetNumbers = (BigDecimal)model.getValue("yem_mincabinetnumber");
        Integer singleNumber = (Integer)model.getValue("yem_singlenumber");
        int costInfoRows = model.getEntryRowCount("yem_costinfor");
        for (int i = 0; i < costInfoRows; i++) {
            DynamicObject addNew = costInfos.addNew();
            BigDecimal ticketPrice = (BigDecimal)model.getValue("yem_ticketprice", i);
            BigDecimal bigCabinetPrice = (BigDecimal)model.getValue("yem_bigcabinetprice", i);
            BigDecimal minCabinetPrice = (BigDecimal)model.getValue("yem_mincabinetprice", i);
            BigDecimal bigCabinetAmt = bigCabinetPrice.multiply(bigCabinetNumbers);
            BigDecimal minCabinetAmt = minCabinetPrice.multiply(minCabinetNumbers);
            BigDecimal byTicketAmt = ticketPrice.multiply(new BigDecimal(singleNumber));
            BigDecimal costSumAmountBba = bigCabinetAmt.add(minCabinetAmt).add(byTicketAmt);
            addNew.set("yem_addorsubc",model.getValue("yem_addorsub",i));//费用类型
            addNew.set("yem_padexpensec",model.getValue("yem_padexpense",i));//费用项目
            addNew.set("yem_bd_chargemode",model.getValue("yem_bd_chargemode",i));//计费方式
            addNew.set("yem_bigcabinetprice",bigCabinetPrice);//大柜单价
            addNew.set("yem_mincabinetprice",minCabinetPrice);//小柜单价
            addNew.set("yem_byticketprice",ticketPrice);//按票单价
            addNew.set("yem_bigcabinetamt",bigCabinetAmt);//大柜金额
            addNew.set("yem_mincabinetamt",minCabinetAmt);//小柜金额
            addNew.set("yem_byticketamt",byTicketAmt);//按票金额
            addNew.set("yem_costsumamountcba",costSumAmountBba);//费用金额本位币
            if(orderSumNumber != 0){
                BigDecimal cartFulAmountBa = costSumAmountBba.divide(new BigDecimal(orderSumNumber), RoundingMode.HALF_UP);
                addNew.set("yem_cartfulamountba",cartFulAmountBa);//单车费用金额本位币
                if(!(exrate.compareTo(BigDecimal.ZERO) == 0)){
                    addNew.set("yem_cartfulamount",cartFulAmountBa.divide(exrate, RoundingMode.HALF_UP));//单车费用金额
                }
            }
            if(!(exrate.compareTo(BigDecimal.ZERO) == 0)){
                BigDecimal costSumAmountC = costSumAmountBba.divide(exrate, RoundingMode.HALF_UP);
                addNew.set("yem_costsumamountc",costSumAmountC);//费用金额

            }

        }
    }

    public static void setBillInfo(DynamicObject intAuditBusAcc,DynamicObject sourceObj,Long sourceEntryId){

        intAuditBusAcc.set("yem_sourcebilltype",sourceObj.getDynamicObjectType().getName());//源单类型
        intAuditBusAcc.set("yem_sourcebillid",sourceObj.getPkValue());//来源单据ID
        intAuditBusAcc.set("yem_sourcebillno",sourceObj.getString("billno"));//来源单据编码
        intAuditBusAcc.set("yem_corebilltype",sourceObj.getString("yem_corebilltype"));//核心单类型
        intAuditBusAcc.set("yem_corebillno",sourceObj.getString("yem_corebillno"));//核心单据编码
        intAuditBusAcc.set("yem_corebillid",sourceObj.getLong("yem_corebillid"));//核心单据ID
        intAuditBusAcc.set("yem_sourceentryid",sourceEntryId);//来源明细分录行内码

    }


    /**
     * @description 删除明细信息分录校验
     * @author xwudd
     * @param[1] e
     * @param[2] view
     * @param[3] model
     * @param[4] rowIndexs
     * return
     * @time 2023/8/14 17:12
     */

    public static void deleteMaterialEntry(BeforeDeleteRowEventArgs e, IFormView view, IDataModel model, int[] rowIndexs){
        List<String> rows = new ArrayList();
        for(int rowIndex : rowIndexs){
            String intAuditBuSaNo = (String)model.getValue("yem_intauditbusano",rowIndex);
            Long intAuditBuSaId = (Long)model.getValue("yem_intauditbusaid",rowIndex);
            if(YEM.isNotEmpty(intAuditBuSaNo) && YEM.isNotEmpty(intAuditBuSaId)) {
                rows.add(rowIndex + 1 + "");
            }
        }
        if(rows.size() > 0){
            String join = String.join(",", rows);
            view.showErrorNotification("第" + join + "行已生成内审预算单,不可删除!");
            e.setCancel(true);
        }
    }


    /**
     * @description 外销合同给内审核算单赋值相关字段
     * @author xwudd
     * @param[1] model
     * @param[2] entryKey
     * return
     * @time 2023/8/14 17:12
     */

    public static void defaultValue(IDataModel model,String entryKey){
        int entryRowRows = model.getEntryRowCount(entryKey);
        DynamicObject dataEntity = model.getDataEntity();
        for (int i = 0; i < entryRowRows; i++) {
            String intAuditBuSaNo = (String)model.getValue("yem_intauditbusano",i);
            Long intAuditBuSaId = (Long)model.getValue("yem_intauditbusaid",i);
            if(YEM.isNotEmpty(intAuditBuSaNo) && YEM.isNotEmpty(intAuditBuSaId)) {
                DynamicObject intAuditBuSa = BusinessDataServiceHelper.loadSingle(intAuditBuSaId, "yem_im_intauditbusa");
                setBillInfo(intAuditBuSa,dataEntity,model.getEntryRowEntity("yem_es_materialinfo",i).getLong("id"));
                SaveServiceHelper.save(new DynamicObject[]{intAuditBuSa});
            }
        }
    }


    /**
     * @description 更新数据更新本位币数据
     * @author xwudd
     * @param[1] intAuditBusAcc
     * @param[2] model
     * return
     * @time 2023/8/18 16:44
     */

    public static void  UpdateManualFilling(DynamicObject intAuditBusAcc,IDataModel model){
        BigDecimal exrate = (BigDecimal)model.getValue("yem_exrate");
        BigDecimal seaFreight = intAuditBusAcc.getBigDecimal("yem_seafreight");//海运费
        BigDecimal preMium = intAuditBusAcc.getBigDecimal("yem_premium");//保险费
        BigDecimal commissionAmt = intAuditBusAcc.getBigDecimal("yem_commissionamt");//佣金
        BigDecimal bankCost = intAuditBusAcc.getBigDecimal("yem_bankcost");//银行费用
        BigDecimal interestAmt = intAuditBusAcc.getBigDecimal("yem_interestamt");//银行利息费
        BigDecimal landCarryCost = intAuditBusAcc.getBigDecimal("yem_landcarrycost");//陆运费
        BigDecimal airliftCost = intAuditBusAcc.getBigDecimal("yem_airliftcost");//空运费
        BigDecimal expressCost = intAuditBusAcc.getBigDecimal("yem_expresscost");//快递费
        BigDecimal forwarderCost = intAuditBusAcc.getBigDecimal("yem_forwardercost");//货代费
        BigDecimal packagingCost = intAuditBusAcc.getBigDecimal("yem_packagingcost");//包装费
        BigDecimal creditAmt = intAuditBusAcc.getBigDecimal("yem_creditamt");//信保费
        BigDecimal elseCost = intAuditBusAcc.getBigDecimal("yem_elsecost");//其他费用
        intAuditBusAcc.set("yem_seafreightba",seaFreight.multiply(exrate));
        intAuditBusAcc.set("yem_premiumba",preMium.multiply(exrate));
        intAuditBusAcc.set("yem_commissionamtba",commissionAmt.multiply(exrate));
        intAuditBusAcc.set("yem_bankcostba",bankCost.multiply(exrate));
        intAuditBusAcc.set("yem_interestamtba",interestAmt.multiply(exrate));
        intAuditBusAcc.set("yem_landcarrycostba",landCarryCost.multiply(exrate));
        intAuditBusAcc.set("yem_airliftcostba",airliftCost.multiply(exrate));
        intAuditBusAcc.set("yem_expresscostba",expressCost.multiply(exrate));
        intAuditBusAcc.set("yem_forwardercostba",forwarderCost.multiply(exrate));
        intAuditBusAcc.set("yem_packagingcostba",packagingCost.multiply(exrate));
        intAuditBusAcc.set("yem_creditamtba",creditAmt.multiply(exrate));
        intAuditBusAcc.set("yem_elsecostba",elseCost.multiply(exrate));

        DynamicObjectCollection intauditbusas = intAuditBusAcc.getDynamicObjectCollection("yem_im_intauditbusa_a");
        for(DynamicObject intauditbusa : intauditbusas){
            BigDecimal costSumAmounts = intauditbusa.getBigDecimal("yem_costsumamounts");
            intauditbusa.set("yem_costsumamountcoins",costSumAmounts.multiply(exrate));
        }
    }

    /**
     * @description new单据赋值多选基础资料处理
     * @author xwudd
     * @param[1] oldObjCols
     * @param[2] newObjCols
     * return
     * @time 2023/8/14 17:11
     */

    public static void getNewMulti(DynamicObjectCollection oldObjCols,DynamicObjectCollection newObjCols){
        newObjCols.clear();
        for(DynamicObject oldObjCol : oldObjCols){
            DynamicObject dynamicObject = new DynamicObject(newObjCols.getDynamicObjectType());
            DynamicObject fbasedataid = oldObjCol.getDynamicObject("fbasedataid");
            dynamicObject.set("fbasedataid",fbasedataid);
            newObjCols.add(dynamicObject);
        }
    }


    /**
     * @description 通过编码查基础资料实体
     * @author xwudd
     * @param[1] objKey
     * @param[2] number
     * return
     * @time 2023/8/21 14:35
     */

    public static DynamicObject getBaseDynamicObject(String objKey,String number){
        return BusinessDataServiceHelper.loadSingle(objKey,"id,number",new QFilter[]{new QFilter("number",QCP.equals,number)});
    }


    /**
     * @description 计算总费用
     * @author xwudd
     * * @param[1] intAuditBusAcc
     * return
     * @time 2023/9/26 10:37
     */

    public static void countSumCost(DynamicObject intAuditBusAcc){
        BigDecimal seaFreight = intAuditBusAcc.getBigDecimal("yem_seafreight");
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_premium"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_bankcost"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_commissionamt"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_interestamt"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_landcarrycost"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_airliftcost"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_expresscost"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_forwardercost"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_packagingcost"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_creditamt"));
        seaFreight = seaFreight.add(intAuditBusAcc.getBigDecimal("yem_elsecost"));
        BigDecimal seaFreightBa = intAuditBusAcc.getBigDecimal("yem_seafreightba");
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_premiumba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_bankcostba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_commissionamtba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_interestamtba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_landcarrycostba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_airliftcostba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_expresscostba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_forwardercostba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_packagingcostba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_creditamtba"));
        seaFreightBa = seaFreightBa.add(intAuditBusAcc.getBigDecimal("yem_elsecostba"));
        intAuditBusAcc.set("yem_sumcost",seaFreight);
        intAuditBusAcc.set("yem_sumcostbase",seaFreightBa);
    }



    public void deleteCorrespondingAtt(){

    }


    /**
     * 获取当前用户、当前组织对应部门
     * @param orgID 组织ID
     * @return
     */
    public static Set getOrgUserDeps(long orgID) {
        String longnumber = "";
        QFilter qFilter = new QFilter("org", QCP.equals, orgID);
        qFilter.and(new QFilter("view.number", QCP.equals, "15"));
        DynamicObject[] bos_org_s = BusinessDataServiceHelper.load("bos_org_structure",
                "id,name,number,longnumber", new QFilter[] { qFilter }, null);
        if(null != bos_org_s && bos_org_s.length>0){
            longnumber = bos_org_s[0].getString("longnumber");
        }

        Map org_map = new HashMap();
        qFilter = new QFilter("longnumber", QCP.like, longnumber+"%");
        bos_org_s = BusinessDataServiceHelper.load("bos_org_structure","id,name,number,org", new QFilter[] { qFilter }, null);
        if(null != bos_org_s && bos_org_s.length>0){
            for(DynamicObject bos_org:bos_org_s){
                org_map.put(bos_org.getDynamicObject("org").getLong("id"),bos_org.getDynamicObject("org"));
            }
        }
        return org_map.keySet();
    }

    public static void removeAtt(DynamicObject intAuditBusAcc){
        if(YEM.isNotEmpty(intAuditBusAcc)){
            List<String> attNameList = new ArrayList();
            DynamicObject billType = intAuditBusAcc.getDynamicObject("yem_billtype");
            String billTypeNumber = YEM.isNotEmpty(billType)?billType.getString("number"):"";
            if("yem_im_intauditbusa_PJWX".equals(billTypeNumber)){
                attNameList.add(setAttName("PJ",intAuditBusAcc) + ".pdf");
            }
            if("yem_im_intauditbusa_ZJWX".equals(billTypeNumber)) {
                attNameList.add(setAttName("NSZJ",intAuditBusAcc) + ".pdf");
                attNameList.add(setAttName("HSZJ",intAuditBusAcc) + ".pdf");
            }
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(intAuditBusAcc.getString("yem_sourcebilltype"), intAuditBusAcc.getLong("yem_sourcebillid"), "attachmentpanel");
            for(Map<String, Object> attachment : attachments){
                String name = (String)attachment.get("name");
                if(attNameList.contains(name)){
                    AttachmentServiceHelper.remove(intAuditBusAcc.getString("yem_sourcebilltype"), intAuditBusAcc.getLong("yem_sourcebillid"),attachment.get("uid"));
                }
            }
        }
    }

    public static String setAttName(String tplIdByNum,DynamicObject dataEntitie){
        Integer seq = dataEntitie.getInt("yem_sourceentryseq");
        DynamicObject productModel = dataEntitie.getDynamicObject("yem_productmodel");
        String productModelNum = YEM.isNotEmpty(productModel)?productModel.getString("number"):"";
        String sourceBillNo = dataEntitie.getString("yem_sourcebillno");
        if(tplIdByNum.contains("NSZJ")){
            return String.format("%s出口产品内部审批表-%s-%s",sourceBillNo,productModelNum,seq);
        }
        if(tplIdByNum.contains("HSZJ")){
            return String.format("%s整机自营出口核算表-%s-%s",sourceBillNo,productModelNum,seq);
        }
        if(tplIdByNum.contains("PJ")){
            return String.format("%s配件订单价格核算表",sourceBillNo);
        }
        return null;
    }
}
