package com.yem.wm.es.Util;

import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author xwudd
 * @date 15:02
 * @Description
 **/
public class ZJUtils {

    /**
     * @description 汇总数量到 订单总台数
     * @author xwudd
     * return
     * @time 2023/7/29 16:38
     */

    public static void countOrderSumNumberZJ(IDataModel model) {
        BigDecimal total = BigDecimal.ZERO;
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        if (YEM.isNotEmpty(billType)) {
            String number = billType.getString("number");
            int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
            for (int i = 0; i < materialInfoRows; i++) {
                String businessSort = (String) model.getValue("yem_businesssort", i);
                if ("Z".equals(businessSort)) {
                    total = total.add((BigDecimal) model.getValue("yem_qty", i));
                }
            }

        }
        model.setValue("yem_ordersumnumber", total);
    }

    /**
     * @description 整机计算费用信息分录信息
     * @author xwudd
     * return
     * @time 2023/8/4 15:47
     */

    public static void countCostSumAmountZJ(IDataModel model) {
        int salesRrderRows = model.getEntryRowCount("yem_costinfor");
        BigDecimal bigCabinetQty = (BigDecimal) model.getValue("yem_bigcabinetnumber");
        BigDecimal minCabinetQty = (BigDecimal) model.getValue("yem_mincabinetnumber");
        Integer singleQty = (Integer) model.getValue("yem_singlenumber");
        BigDecimal rate = (BigDecimal) model.getValue("yem_exrate");

        for (int i = 0; i < salesRrderRows; i++) {
            DynamicObject billInGWay = (DynamicObject) model.getValue("yem_bd_chargemode", i);
            String number = YEM.isEmpty(billInGWay) ? "" : billInGWay.getString("number");
            BigDecimal amt = BigDecimal.ZERO;
            if ("JFFS-0002".equals(number)) {
                BigDecimal bigCabinetPrice = (BigDecimal) model.getValue("yem_bigcabinetprice", i);
                BigDecimal minCabinetPrice = (BigDecimal) model.getValue("yem_mincabinetprice", i);
                amt = bigCabinetPrice.multiply(bigCabinetQty).add(minCabinetPrice.multiply(minCabinetQty));
            }
            if ("JFFS-0003".equals(number)) {
                BigDecimal ticketPrice = (BigDecimal) model.getValue("yem_ticketprice", i);
                amt = ticketPrice.multiply(new BigDecimal(singleQty));

            }
            if (rate.compareTo(BigDecimal.ZERO) > 0) {
                model.setValue("yem_costsumamount", amt.divide(rate, RoundingMode.HALF_DOWN), i);
            }
            model.setValue("yem_costsumamountcoin", amt, i);
        }
    }


    /**
     * @description 选择收款计划时带出收款计划分录
     * @author xwudd
     * @time 2023/7/25 9:24
     */

    public static void setSalesContracZJ(IDataModel model) {
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        model.deleteEntryData("yem_es_salescontrac_s");
        if (recCondition != null) {
            String basis = recCondition.getString("basis");
            DynamicObjectCollection entrys = recCondition.getDynamicObjectCollection("entry");
            for (DynamicObject entry : entrys) {
                int entryRow = model.createNewEntryRow("yem_es_salescontrac_s");
                model.setValue("yem_ispre", entry.getBoolean("ispre"), entryRow);
                model.setValue("yem_payment", recCondition, entryRow);
                model.setValue("yem_isprepayment", entry.getString("yem_isprepayment"), entryRow);
                model.setValue("yem_isshippayment", entry.getString("yem_isshippayment"), entryRow);
                if ("A".equals(basis)) {
                    model.setValue("yem_raprate", entry.getBigDecimal("rate"), entryRow);
                }
                if ("B".equals(basis)) {
                    model.setValue("yem_rapamt", entry.getBigDecimal("amount"), entryRow);
                }
            }
        }
    }

    /**
     * @description 计算收汇金额
     * @author xwudd
     * return
     * @time 2023/8/7 18:04
     */

    public static void countRapAmt(IDataModel model) {
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        if (YEM.isNotEmpty(recCondition)) {
            String basis = recCondition.getString("basis");
            BigDecimal billAmt = (BigDecimal) model.getValue("yem_offeramount");
            if ("A".equals(basis) && billAmt.compareTo(BigDecimal.ZERO) > 0) {
                int salescontracs = model.getEntryRowCount("yem_es_salescontrac_s");
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapRate = (BigDecimal) model.getValue("yem_raprate", i);
                    model.setValue("yem_rapamt", billAmt.multiply(rapRate.divide(new BigDecimal(100))), i);
                }
            }
        }
    }

    /**
     * @description 计算收汇比率
     * @author xwudd
     * return
     * @time 2023/8/7 18:04
     */

    public static void countRapRate(IDataModel model) {
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        if (YEM.isNotEmpty(recCondition)) {
            String basis = recCondition.getString("basis");
            BigDecimal total = BigDecimal.ZERO;
            if ("B".equals(basis)) {
                int salescontracs = model.getEntryRowCount("yem_es_salescontrac_s");
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                    total = total.add(rapAmt);
                }
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                    model.setValue("yem_raprate", rapAmt.multiply(new BigDecimal(100)).divide(total, RoundingMode.HALF_DOWN), i);
                }
            }
        }
    }

    /**
     * @description 汇总分录 BigDecimal类型字段到 表头
     * @author xwudd
     * @param[1] model
     * return
     * @time 2023/8/18 9:22
     */
    public static void countSumQtyTypeField(IDataModel model, String key, String entryKey, String entryFieldKey) {
        int materialInfoRows = model.getEntryRowCount(entryKey);
        BigDecimal sumPiece = BigDecimal.ZERO;
        for (int i = 0; i < materialInfoRows; i++) {
            sumPiece = sumPiece.add((BigDecimal) model.getValue(entryFieldKey, i));
        }
        model.setValue(key, sumPiece);
    }

    /**
     * @description 当物料分类为整机时，选择产品型号带出 随机资料及配件工具包分录
     * @author xwudd
     * return
     * @time 2023/7/25 9:09
     */

    public static void setRandomDataTools(IDataModel model) {
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        String yem_saleorderno = (String) model.getValue("yem_saleorderno");
        model.deleteEntryData("yem_es_salesorder_p");
        String selectfields = DynamicObjectUtil.getSelectfields("yem_overalltoollib", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_overalltoollib", "yem_infor", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_overalltoollib", "yem_spareparts", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_overalltoollib", "yem_tools", false);
        Map<Long, BigDecimal> map = new HashMap();
        for (int i = 0; i < materialInfoRows; i++) {
            String materialClass = (String) model.getValue("yem_businesssort", i);
            DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", i);
            if (YEM.isNotEmpty(materialClass) && YEM.isNotEmpty(productModel)) {
                if ("Z".equals(materialClass)) {
                    DynamicObject products = productModel.getDynamicObject("yem_products");
                    if (YEM.isNotEmpty(products)) {
                        Long id = products.getLong("id");
                        if (map.containsKey(id)) {
                            map.put(id, map.get(id).add((BigDecimal) model.getValue("yem_qty", i)));
                        } else {
                            map.put(id, (BigDecimal) model.getValue("yem_qty", i));
                        }
                    }

                }
            }
        }
        Set<Long> ids = map.keySet();
        for (Long id : ids) {
            DynamicObject overAllToolLib = BusinessDataServiceHelper.loadSingle("yem_overalltoollib", selectfields, new QFilter[]{new QFilter("yem_productmodel", QCP.equals, id)});
            if (overAllToolLib != null) {
                DynamicObjectCollection infors = overAllToolLib.getDynamicObjectCollection("yem_infor");
                DynamicObjectCollection spareparts = overAllToolLib.getDynamicObjectCollection("yem_spareparts");
                DynamicObjectCollection tools = overAllToolLib.getDynamicObjectCollection("yem_tools");
//                for (DynamicObject infor : infors) {
//                    int entryRow = model.createNewEntryRow("yem_es_salesorder_p");
//                    model.setValue("yem_accessorytype", overAllToolLib.getDynamicObject("yem_productmodel"), entryRow);
//                    model.setValue("yem_volvotype", "A", entryRow);
//                    model.setValue("yem_accesmaterial", infor.getDynamicObject("yem_material_i"), entryRow);
//                    model.setValue("yem_acunit", infor.getDynamicObject("yem_unit_i"), entryRow);
//                    model.setValue("yem_bicycleqty", infor.getBigDecimal("yem_qty_i"), entryRow);
//                    model.setValue("yem_acremark", infor.getString("yem_remark_i"), entryRow);
//                    model.setValue("yem_pcstype", map.get(id), entryRow);
//                    model.setValue("yem_acallqty", map.get(id).multiply(infor.getBigDecimal("yem_qty_i")), entryRow);
//                }
                for (DynamicObject sparepart : spareparts) {
                    int entryRow = model.createNewEntryRow("yem_es_salesorder_p");
                    model.setValue("yem_saleorderno_p", yem_saleorderno, entryRow);
                    model.setValue("yem_accessorytype", overAllToolLib.getDynamicObject("yem_productmodel"), entryRow);
                    model.setValue("yem_volvotype", "B", entryRow);
                    model.setValue("yem_accesmaterial", sparepart.getDynamicObject("yem_material_s"), entryRow);
                    model.setValue("yem_acunit", sparepart.getDynamicObject("yem_unit_s"), entryRow);
                    model.setValue("yem_bicycleqty", sparepart.getBigDecimal("yem_qty_s"), entryRow);
                    model.setValue("yem_acremark", sparepart.getString("yem_remark_s"), entryRow);
                    model.setValue("yem_pcstype", map.get(id), entryRow);
                    model.setValue("yem_acallqty", map.get(id).multiply(sparepart.getBigDecimal("yem_qty_s")), entryRow);
                }
                for (DynamicObject tool : tools) {
                    int entryRow = model.createNewEntryRow("yem_es_salesorder_p");
                    model.setValue("yem_saleorderno_p", yem_saleorderno, entryRow);
                    model.setValue("yem_accessorytype", overAllToolLib.getDynamicObject("yem_productmodel"), entryRow);
                    model.setValue("yem_volvotype", "C", entryRow);
                    model.setValue("yem_accesmaterial", tool.getDynamicObject("yem_material_t"), entryRow);
                    model.setValue("yem_acunit", tool.getDynamicObject("yem_unit_t"), entryRow);
                    model.setValue("yem_bicycleqty", tool.getBigDecimal("yem_qty_t"), entryRow);
                    model.setValue("yem_acremark", tool.getString("yem_remark_t"), entryRow);
                    model.setValue("yem_pcstype", map.get(id), entryRow);
                    model.setValue("yem_acallqty", map.get(id).multiply(tool.getBigDecimal("yem_qty_t")), entryRow);
                }
            }
        }
    }


    public static void renewMachineProductInfo(IFormView view, IDataModel model) {
        HashMap<String, Object> map = new HashMap<>();
        Set<String> resourcesCodeSet = new HashSet();
        Set<String> vehicleNoSet = new HashSet();
        int machineProductInfoRows = model.getEntryRowCount("yem_es_salesorder_z");
        for (int i = 0; i < machineProductInfoRows; i++) {
            DynamicObject resourcesCode = (DynamicObject) model.getValue("yem_resourcescode", i);
            if (YEM.isNotEmpty(resourcesCode)) {
                resourcesCodeSet.add(resourcesCode.getString("number"));
            }
            String vehicleNo = (String) model.getValue("yem_vehicleno", i);
            vehicleNoSet.add(vehicleNo);
        }
        if (resourcesCodeSet.size() > 0) {
            map.put(PlanJobCMMP.productCode, resourcesCodeSet);
        }
        if (vehicleNoSet.size() > 0) {
            map.put(PlanJobCMMP.planPin, vehicleNoSet);
        }
        long productsid = ((DynamicObject) model.getValue("yem_bd_products")).getLong("id");
        List<Map> dockings = ViewInterfaceDocking.docking(ViewInterfaceDocking.PLAN_JOB, map, productsid);

        if (YEM.isNotEmpty(dockings)) {
            dockings.sort(new Comparator<Map>() {
                @Override
                public int compare(Map o1, Map o2) {
                    Date date1 = (Date) o1.get(PlanJobCMMP.jobTime);
                    Date date2 = (Date) o1.get(PlanJobCMMP.jobTime);
                    return date1.compareTo(date2);
                }
            });
            for (int i = 0; i < machineProductInfoRows; i++) {
                DynamicObject resourcesCodeObj = (DynamicObject) model.getValue("yem_resourcescode", i);
                String resourcesCode = YEM.isNotEmpty(resourcesCodeObj) ? resourcesCodeObj.getString("number") : "";
                String vehicleNo = (String) model.getValue("yem_vehicleno", i);
                for (Map docking : dockings) {
                    String planPin = (String) docking.get(PlanJobCMMP.planPin);
                    String productCode = (String) docking.get(PlanJobCMMP.productCode);
                    if (resourcesCode.equals(productCode) && vehicleNo.equals(planPin)) {
                        model.setValue("yem_engineno", docking.get(PlanJobCMMP.stockBatch), i);//发动机号
                        model.setValue("yem_enginemodel", docking.get(PlanJobCMMP.specification), i);//发动机型号
                        model.setValue("yem_enginevendor", docking.get(PlanJobCMMP.supName), i);//发动机厂商
                        setInstructionValue(model, docking, i);
                    }
                }
            }
        }
        view.invokeOperation("save");
    }

    /**
     * @description 赋值指令信息
     * @author xwudd
     * @param[1] docking
     * @param[2] i
     * return
     * @time 2023/9/4 18:13
     */

    public static void setInstructionValue(IDataModel model, Map docking, int i) {
        String instructionCode = (String) docking.get(PlanJobCMMP.instructionCode);
        Date instructionTime = (Date) docking.get(PlanJobCMMP.jobTime);
        String instructionName = (String) docking.get(PlanJobCMMP.instructionName);
        model.setValue("yem_currentstate", instructionName, i);
        model.setValue("yem_currentstatedate", instructionTime, i);
        String prepareWay = (String) model.getValue("yem_prepareway", i);
        switch (prepareWay) {
            case "A":
                ZZ(model, instructionCode, instructionTime, instructionName, i);
                break;
            case "B":
                GZ(model, instructionCode, instructionTime, instructionName, i);
                break;
        }

    }


    public static void ZZ(IDataModel model, String instructionCode, Date instructionTime, String instructionName, int i) {
        switch (instructionCode) {
            case "SX":
                model.setValue("yem_assembleupline", "A", i);
                model.setValue("yem_upline", instructionTime, i);
                break;
            case "XX":
                model.setValue("yem_assembledownline", "A", i);
                model.setValue("yem_downline", instructionTime, i);
                break;
            case "TS":
                model.setValue("yem_debugst", "A", i);
                model.setValue("yem_debugstatdate", instructionTime, i);
                break;
            case "JS":
                model.setValue("yem_accuracytest", "A", i);
                model.setValue("yem_accuratdate", instructionTime, i);
                break;
            case "DJ":
                model.setValue("yem_waitforinspection", "A", i);
                model.setValue("yem_waitforinspecdate", instructionTime, i);
                break;
            case "ZJHG":
                model.setValue("yem_qualitytest", "A", i);
                model.setValue("yem_qualitytestdate", instructionTime, i);
                break;
            case "RK":
                model.setValue("yem_factputstor", "A", i);
                model.setValue("yem_factputstordate", instructionTime, i);
                break;
            case "FGSX":
                model.setValue("yem_backonline", "A", i);
                model.setValue("yem_backonlinedate", instructionTime, i);
                break;
            case "FGRK":
                model.setValue("yem_putintostorage", "A", i);
                model.setValue("yem_putintostoragedate", instructionTime, i);
                break;
        }
    }


    public static void GZ(IDataModel model, String instructionCode, Date instructionTime, String instructionName, int i) {
        switch (instructionCode) {
            case "SX":
                model.setValue("yem_assembleupline", "A", i);
                model.setValue("yem_upline", instructionTime, i);
                break;
            case "GZSX":
                model.setValue("yem_assembleupline", "A", i);
                model.setValue("yem_upline", instructionTime, i);
                break;
            case "GZRK":
                model.setValue("yem_factputstor", "A", i);
                model.setValue("yem_factputstordate", instructionTime, i);
                break;
            case "RK":
                model.setValue("yem_factputstor", "A", i);
                model.setValue("yem_factputstordate", instructionTime, i);
                break;
            case "XX":
                model.setValue("yem_assembledownline", "A", i);
                model.setValue("yem_downline", instructionTime, i);
                break;
            case "TS":
                model.setValue("yem_debugst", "A", i);
                model.setValue("yem_debugstatdate", instructionTime, i);
                break;
            case "JS":
                model.setValue("yem_accuracytest", "A", i);
                model.setValue("yem_accuratdate", instructionTime, i);
                break;
            case "DJ":
                model.setValue("yem_waitforinspection", "A", i);
                model.setValue("yem_waitforinspecdate", instructionTime, i);
                break;
            case "ZJHG":
                model.setValue("yem_qualitytest", "A", i);
                model.setValue("yem_qualitytestdate", instructionTime, i);
                break;
            case "FGSX":
                model.setValue("yem_backonline", "A", i);
                model.setValue("yem_backonlinedate", instructionTime, i);
                break;
            case "FGRK":
                model.setValue("yem_putintostorage", "A", i);
                model.setValue("yem_putintostoragedate", instructionTime, i);
                break;
        }
    }


    /**
     * @description 分录合同号汇总
     * @author xwudd
     * @param[1] model
     * return
     * @time 2023/9/14 9:47
     */

    public static void totalContractNo(IDataModel model) {
        Set<String> set = new HashSet();
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            String contractNumbers = (String) model.getValue("yem_contractnumbers_m", i);
            if (YEM.isNotEmpty(contractNumbers)) {
                set.add(contractNumbers);
            }
        }
        model.setValue("yem_totalcontractno", String.join(";", set));
    }

    /**
     * @description 生成资源申请单
     * @author xwudd
     * @param[1] view
     * @param[2] model
     * @param[3] entryKey
     * return
     * @time 2023/10/12 17:15
     */

    public static void createSourceApply(IFormView view, IDataModel model, String entryKey, String flag) {
        EntryGrid materialEntry = view.getControl(entryKey);
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObjectCollection entry = dataEntity.getDynamicObjectCollection(entryKey);
        int[] selectRows = materialEntry.getSelectRows();
        List<String> rows = new ArrayList<>();
        List<String> createRows = new ArrayList<>();
        for (int selectRow : selectRows) {
            String sourceApplyNo = (String) model.getValue("yem_sourceapplyno", selectRow);
            Long sourceApplyId = (Long) model.getValue("yem_sourceapplyid", selectRow);
            if (YEM.isNotEmpty(sourceApplyNo) && YEM.isNotEmpty(sourceApplyId)) {
                createRows.add(selectRow + 1 + "");
                continue;
            }
            DynamicObject sourceApply = BusinessDataServiceHelper.newDynamicObject("yem_sourceapply");
            int currentRowIndex = model.getEntryCurrentRowIndex(entryKey);
            sourceApply.set("billno", model.getValue("billno") + "-" + (selectRow + 1));//单据编号
            sourceApply.set("yem_bizdate", new Date());//业务日期
            sourceApply.set("yem_reqdate", new Date());//需求日期
            sourceApply.set("yem_operator", model.getValue("yem_operator"));//业务员
            sourceApply.set("yem_requser", model.getValue("yem_operator"));//国贸需求业务员
            sourceApply.set("yem_department", model.getValue("yem_department"));//业务部门
            sourceApply.set("yem_bd_products", model.getValue("yem_bd_products"));//产品分类
            if ("A".equals(flag)) {
                sourceApply.set("yem_country", model.getValue("yem_clientcountry"));//国家
            } else {
                QFilter qFilter = new QFilter("billno", QCP.equals, model.getValue("yem_contractnumber"));
                DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id", qFilter.toArray());
                if (billType != null) {
                    sourceApply.set("yem_contract", billType.getLong("id"));//合同号
                }
                DynamicObject value = dataEntity.getDynamicObject("yem_customer");
                if (value != null) {
                    sourceApply.set("yem_country", value.getDynamicObject("country"));//国家
                }
            }
            DynamicObject BillType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", new QFilter[]{new QFilter("number", QCP.equals, "yem_sourceapply_BT")});
            sourceApply.set("yem_billtype", BillType);//单据类型
            sourceApply.set("org", model.getValue("org"));//公司
            sourceApply.set("billstatus", "A");//单据状态
            sourceApply.set("creator", RequestContext.get().getCurrUserId());//创建人
            sourceApply.set("createtime", new Date());//创建时间
            sourceApply.set("modifier", RequestContext.get().getCurrUserId());//修改人
            sourceApply.set("modifytime", new Date());//修改时间
            String name = model.getDataEntityType().getName();
            String pro = name.replace("_prod", "");
            if ("A".equals(flag)) {
                sourceApply.set("yem_sourcebilltype", "yem_es_saleorder_prod");//源单类型
            } else {
                sourceApply.set("yem_sourcebilltype", "yem_tracktaskconsole_prod");//源单类型
            }
            sourceApply.set("yem_sourcebillid", model.getDataEntity().getPkValue());//来源单据ID
            sourceApply.set("yem_sourcebillno", model.getValue("billno"));//来源单据编码
            sourceApply.set("yem_corebillno", model.getValue("yem_corebillno"));//核心单据编码
            sourceApply.set("yem_corebillid", model.getValue("yem_corebillid"));//核心单据ID
            sourceApply.set("yem_corebilltype", model.getValue("yem_corebilltype"));//核心单类型
            sourceApply.set("yem_sourceentryid", entry.get(selectRow).getLong("id"));//分录行内码
            DynamicObjectCollection detailInfos = sourceApply.getDynamicObjectCollection("yem_detailinfo");
            DynamicObject addNew = detailInfos.addNew();
            DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", currentRowIndex);
            addNew.set("yem_productmodel", YEM.isNotEmpty(productModel) ? productModel.get("yem_products") : null);//机型
            addNew.set("yem_qty", model.getValue("yem_qty", currentRowIndex));//数量
            addNew.set("yem_unit", model.getValue("yem_unit", currentRowIndex));//计量单位
            if ("A".equals(flag)) {
                addNew.set("yem_config", model.getValue("yem_orderallocation", currentRowIndex));//主要配置及特殊要求
            }
            OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_sourceapply", new DynamicObject[]{sourceApply}, OperateOption.create());
            if (operationResult.isSuccess()) {
                model.setValue("yem_sourceapplyno", sourceApply.get("billno"), selectRow);
                model.setValue("yem_sourceapplyid", sourceApply.getPkValue(), selectRow);
            } else {
                rows.add(selectRow + 1 + "");
            }
        }
        view.invokeOperation("save");
        if (rows.size() > 0) {
            view.showErrorNotification(String.format("明细信息第%s行生成资源申请单失败！", String.join(",", rows)));
        }
        if (createRows.size() > 0) {
            view.showSuccessNotification(String.format("第%s行已生成资源申请单！", String.join(",", createRows)));
        }

    }


    /**
     * @description 生成资源申请单
     * @author power
     * @param[1] view
     * @param[2] model
     * @param[3] entryKey
     * return
     * @time 2023/12/15 17:15
     */

    public static void createSourceApplys(IFormView view, IDataModel model, String entryKey, String flag) {
        EntryGrid materialEntry = view.getControl(entryKey);
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObjectCollection entry = dataEntity.getDynamicObjectCollection(entryKey);
        int[] selectRows = materialEntry.getSelectRows();
        List<String> rows = new ArrayList<>();
        List<String> createRows = new ArrayList<>();
        String productsber = dataEntity.getString("yem_bd_products.number");
        //装载机
        if ("ZZJ".equals(productsber)) {
            for (int selectRow : selectRows) {
                String sourceApplyNo = (String) model.getValue("yem_sourceapplyno", selectRow);
                Long sourceApplyId = (Long) model.getValue("yem_sourceapplyid", selectRow);
                if (YEM.isNotEmpty(sourceApplyNo) && YEM.isNotEmpty(sourceApplyId)) {
                    createRows.add(selectRow + 1 + "");
                    continue;
                }
                DynamicObject sourceApply = BusinessDataServiceHelper.newDynamicObject("yem_sourceapply");
                int currentRowIndex = model.getEntryCurrentRowIndex(entryKey);
                sourceApply.set("billno", model.getValue("billno") + "-" + (selectRow + 1));//单据编号
                sourceApply.set("yem_bizdate", new Date());//业务日期
                sourceApply.set("yem_reqdate", new Date());//需求日期
                sourceApply.set("yem_operator", model.getValue("yem_operator"));//业务员
                sourceApply.set("yem_requser", model.getValue("yem_operator"));//国贸需求业务员
                sourceApply.set("yem_department", model.getValue("yem_department"));//业务部门
                sourceApply.set("yem_bd_products", model.getValue("yem_bd_products"));//产品分类
                if ("A".equals(flag)) {
                    sourceApply.set("yem_country", model.getValue("yem_clientcountry"));//国家
                } else {
                    QFilter qFilter = new QFilter("billno", QCP.equals, model.getValue("yem_contractnumber"));
                    DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id", qFilter.toArray());
                    if (billType != null) {
                        sourceApply.set("yem_contract", billType.getLong("id"));//合同号
                    }
                    DynamicObject value = dataEntity.getDynamicObject("yem_customer");
                    if (value != null) {
                        sourceApply.set("yem_country", value.getDynamicObject("country"));//国家
                    }
                }
                DynamicObject BillType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", new QFilter[]{new QFilter("number", QCP.equals, "yem_sourceapply_BT")});
                sourceApply.set("yem_billtype", BillType);//单据类型
                sourceApply.set("org", model.getValue("org"));//公司
                sourceApply.set("billstatus", "A");//单据状态
                sourceApply.set("creator", RequestContext.get().getCurrUserId());//创建人
                sourceApply.set("createtime", new Date());//创建时间
                sourceApply.set("modifier", RequestContext.get().getCurrUserId());//修改人
                sourceApply.set("modifytime", new Date());//修改时间
                String name = model.getDataEntityType().getName();
                String pro = name.replace("_prod", "");
                if ("A".equals(flag)) {
                    sourceApply.set("yem_sourcebilltype", "yem_es_saleorder_prod");//源单类型
                } else {
                    sourceApply.set("yem_sourcebilltype", "yem_tracktaskconsole_prod");//源单类型
                }
                sourceApply.set("yem_sourcebillid", model.getDataEntity().getPkValue());//来源单据ID
                sourceApply.set("yem_sourcebillno", model.getValue("billno"));//来源单据编码
                sourceApply.set("yem_corebillno", model.getValue("yem_corebillno"));//核心单据编码
                sourceApply.set("yem_corebillid", model.getValue("yem_corebillid"));//核心单据ID
                sourceApply.set("yem_corebilltype", model.getValue("yem_corebilltype"));//核心单类型
                sourceApply.set("yem_sourceentryid", entry.get(selectRow).getLong("id"));//分录行内码
                DynamicObjectCollection detailInfos = sourceApply.getDynamicObjectCollection("yem_detailinfo");
                DynamicObject addNew = detailInfos.addNew();
                DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", currentRowIndex);
                addNew.set("yem_productmodel", YEM.isNotEmpty(productModel) ? productModel.get("yem_products") : null);//机型
                addNew.set("yem_qty", model.getValue("yem_qty", currentRowIndex));//数量
                addNew.set("yem_unit", model.getValue("yem_unit", currentRowIndex));//计量单位
                if ("A".equals(flag)) {
                    addNew.set("yem_config", model.getValue("yem_orderallocation", currentRowIndex));//主要配置及特殊要求
                }
                OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_sourceapply", new DynamicObject[]{sourceApply}, OperateOption.create());
                if (operationResult.isSuccess()) {
                    model.setValue("yem_sourceapplyno", sourceApply.get("billno"), selectRow);
                    model.setValue("yem_sourceapplyid", sourceApply.getPkValue(), selectRow);
                } else {
                    rows.add(selectRow + 1 + "");
                }
            }
        }
        //拖拉机
        if ("TLJ".equals(productsber)) {
            for (int selectRow : selectRows) {
                String sourceApplyNo = (String) model.getValue("yem_sourceapplyno", selectRow);
                Long sourceApplyId = (Long) model.getValue("yem_sourceapplyid", selectRow);
//                if (YEM.isNotEmpty(sourceApplyNo) && YEM.isNotEmpty(sourceApplyId)) {
//                    createRows.add(selectRow + 1 + "");
//                    continue;
//                }
                DynamicObject sourceApply = BusinessDataServiceHelper.newDynamicObject("yem_acsourceapply");
                int currentRowIndex = model.getEntryCurrentRowIndex(entryKey);
                sourceApply.set("billno", model.getValue("billno") + "-" + (selectRow + 1));//单据编号
                sourceApply.set("yem_bizdate", new Date());//业务日期
                sourceApply.set("yem_date", new Date());//申请时间
                sourceApply.set("yem_operator", model.getValue("yem_operator"));//业务员
                sourceApply.set("org", model.getValue("org"));//公司
                sourceApply.set("yem_department", model.getValue("yem_department"));//业务部门
                sourceApply.set("yem_sonumber", model.getValue("billno"));//来源单号
                sourceApply.set("yem_bd_products", model.getValue("yem_bd_products"));//产品分类
                sourceApply.set("yem_reqpostdate", new Date());//需求下发时间
                DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", currentRowIndex);
                sourceApply.set("yem_productmodelb", YEM.isNotEmpty(productModel) ? productModel.get("yem_products") : null);//机型
                DynamicObject BillType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", new QFilter[]{new QFilter("number", QCP.equals, "yem_acsourceapply_BT")});
                sourceApply.set("yem_billtype", BillType);//单据类型
                if ("A".equals(flag)) {
                    sourceApply.set("yem_country", model.getValue("yem_clientcountry"));//国家
                }
                if ("B".equals(flag)) {
                    QFilter qFilter = new QFilter("billno", QCP.equals, model.getValue("yem_contractnumber"));
                    DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id", qFilter.toArray());
                    if (billType != null) {
                        sourceApply.set("yem_contract", billType.getLong("id"));//合同号
                    }
                    DynamicObject value = dataEntity.getDynamicObject("yem_customer");
                    if (value != null) {
                        sourceApply.set("yem_country", value.getDynamicObject("country"));//国家
                    }
                }
                sourceApply.set("billstatus", "A");//单据状态
                sourceApply.set("creator", RequestContext.get().getCurrUserId());//创建人
                sourceApply.set("createtime", new Date());//创建时间
                sourceApply.set("modifier", RequestContext.get().getCurrUserId());//修改人
                sourceApply.set("modifytime", new Date());//修改时间
                if ("A".equals(flag)) {
                    sourceApply.set("yem_sourcebilltype", "yem_es_saleorder_prod");//源单类型
                } else {
                    sourceApply.set("yem_sourcebilltype", "yem_tracktaskconsole_prod");//源单类型
                }
                sourceApply.set("yem_sourcebillid", model.getDataEntity().getPkValue());//来源单据ID
                sourceApply.set("yem_sourcebillno", model.getValue("billno"));//来源单据编码
                sourceApply.set("yem_corebillno", model.getValue("yem_corebillno"));//核心单据编码
                sourceApply.set("yem_corebillid", model.getValue("yem_corebillid"));//核心单据ID
                sourceApply.set("yem_corebilltype", model.getValue("yem_corebilltype"));//核心单类型
                sourceApply.set("yem_sourceentryids", entry.get(selectRow).getLong("id"));//分录行内码


                DynamicObjectCollection detailInfos = sourceApply.getDynamicObjectCollection("yem_es_materialinfo");
                DynamicObject addNew = detailInfos.addNew();
                DynamicObject productModels = (DynamicObject) model.getValue("yem_productmodel");
                addNew.set("yem_model", YEM.isNotEmpty(productModels) ? productModels.get("yem_products") : null);//机型
                addNew.set("yem_qtynumber", model.getValue("yem_qty"));//数量
                addNew.set("yem_measuremen", model.getValue("yem_unit"));//计量单位
                OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_acsourceapply", new DynamicObject[]{sourceApply}, OperateOption.create());
                if (operationResult.isSuccess()) {
                    model.setValue("yem_sourceapplyno", sourceApply.get("billno"), selectRow);
                    model.setValue("yem_sourceapplyid", sourceApply.getPkValue(), selectRow);
                } else {
                    rows.add(selectRow + 1 + "");
                }
            }
        }
        //叉车
        if ("CC".equals(productsber)) {
            for (int selectRow : selectRows) {
                String sourceApplyNo = (String) model.getValue("yem_sourceapplyno", selectRow);
                Long sourceApplyId = (Long) model.getValue("yem_sourceapplyid", selectRow);
                if (YEM.isNotEmpty(sourceApplyNo) && YEM.isNotEmpty(sourceApplyId)) {
                    createRows.add(selectRow + 1 + "");
                    continue;
                }
                DynamicObject sourceApply = BusinessDataServiceHelper.newDynamicObject("yem_sourceapply_fok");
                int currentRowIndex = model.getEntryCurrentRowIndex(entryKey);
                sourceApply.set("billno", model.getValue("billno") + "-" + (selectRow + 1));//单据编号
                sourceApply.set("yem_bizdate", new Date());//业务日期
                sourceApply.set("yem_reqdate", new Date());//需求日期
                sourceApply.set("yem_operator", model.getValue("yem_operator"));//业务员
                sourceApply.set("yem_requser", model.getValue("yem_operator"));//国贸需求业务员
                sourceApply.set("yem_department", model.getValue("yem_department"));//业务部门
                sourceApply.set("yem_bd_products", model.getValue("yem_bd_products"));//产品分类
                if ("A".equals(flag)) {
                    sourceApply.set("yem_country", model.getValue("yem_clientcountry"));//国家
                } else {
                    QFilter qFilter = new QFilter("billno", QCP.equals, model.getValue("yem_contractnumber"));
                    DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id", qFilter.toArray());
                    if (billType != null) {
                        sourceApply.set("yem_contract", billType.getLong("id"));//合同号
                    }
                    DynamicObject value = dataEntity.getDynamicObject("yem_customer");
                    if (value != null) {
                        sourceApply.set("yem_country", value.getDynamicObject("country"));//国家
                    }
                }
                DynamicObject BillType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", new QFilter[]{new QFilter("number", QCP.equals, "yem_sourceapply_fok_BT")});
                sourceApply.set("yem_billtype", BillType);//单据类型
                sourceApply.set("org", model.getValue("org"));//公司
                sourceApply.set("billstatus", "A");//单据状态
                sourceApply.set("creator", RequestContext.get().getCurrUserId());//创建人
                sourceApply.set("createtime", new Date());//创建时间
                sourceApply.set("modifier", RequestContext.get().getCurrUserId());//修改人
                sourceApply.set("modifytime", new Date());//修改时间
                String name = model.getDataEntityType().getName();
                String pro = name.replace("_prod", "");
                if ("A".equals(flag)) {
                    sourceApply.set("yem_sourcebilltype", "yem_es_saleorder_prod");//源单类型
                } else {
                    sourceApply.set("yem_sourcebilltype", "yem_tracktaskconsole_prod");//源单类型
                }
                sourceApply.set("yem_sourcebillid", model.getDataEntity().getPkValue());//来源单据ID
                sourceApply.set("yem_sourcebillno", model.getValue("billno"));//来源单据编码
                sourceApply.set("yem_corebillno", model.getValue("yem_corebillno"));//核心单据编码
                sourceApply.set("yem_corebillid", model.getValue("yem_corebillid"));//核心单据ID
                sourceApply.set("yem_corebilltype", model.getValue("yem_corebilltype"));//核心单类型
                sourceApply.set("yem_sourceentryid", entry.get(selectRow).getLong("id"));//分录行内码
                DynamicObjectCollection detailInfos = sourceApply.getDynamicObjectCollection("yem_detailinfo");
                DynamicObject addNew = detailInfos.addNew();
                DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", currentRowIndex);
                addNew.set("yem_productmodel", YEM.isNotEmpty(productModel) ? productModel.get("yem_products") : null);//机型
                addNew.set("yem_qty", model.getValue("yem_qty", currentRowIndex));//数量
                addNew.set("yem_unit", model.getValue("yem_unit", currentRowIndex));//计量单位
                if ("A".equals(flag)) {
                    addNew.set("yem_config", model.getValue("yem_orderallocation", currentRowIndex));//主要配置及特殊要求
                }
                OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_sourceapply_fok", new DynamicObject[]{sourceApply}, OperateOption.create());
                if (operationResult.isSuccess()) {
                    model.setValue("yem_sourceapplyno", sourceApply.get("billno"), selectRow);
                    model.setValue("yem_sourceapplyid", sourceApply.getPkValue(), selectRow);
                } else {
                    rows.add(selectRow + 1 + "");
                }
            }
        }
        view.invokeOperation("save");
        if (rows.size() > 0) {
            view.showErrorNotification(String.format("明细信息第%s行生成资源申请单失败！", String.join(",", rows)));
        }
        if (createRows.size() > 0) {
            view.showSuccessNotification(String.format("第%s行已生成资源申请单！", String.join(",", createRows)));
        }
    }


    /**
     * @description 超链接打开资源申请单
     * @author xwudd
     * @param[1] view
     * @param[2] model
     * @param[3] row
     * return
     * @time 2023/10/12 17:15
     */

    public static void openSourceApply(IFormView view, IDataModel model, int row) {
        Long sourceApplyId = (Long) model.getValue("yem_sourceapplyid", row);
        DynamicObject dataEntity = model.getDataEntity();
        String prodType = dataEntity.getDynamicObject("yem_bd_products").getString("number");

        // 装载机
        if ("ZZJ".equals(prodType)) {
            FunctionalCommon.viewBill(view, "yem_sourceapply", sourceApplyId);
        }
        // 叉车
        if ("CC".equals(prodType)) {
            FunctionalCommon.viewBill(view, "yem_sourceapply_fok", sourceApplyId);
        }
        // 拖拉机
        if ("TLJ".equals(prodType)) {
            FunctionalCommon.viewBill(view, "yem_acsourceapply", sourceApplyId);
        }
    }


    public static void delSourceApply(DynamicObject entity) {
        String sourceBillType = entity.getString("yem_sourcebilltype");
        long sourceBillId = entity.getLong("yem_sourcebillid");
        DynamicObject yem_billtype = entity.getDynamicObject("yem_billtype");
        long sourceEntryId = 0L;
        if (yem_billtype != null) {
            if ("yem_acsourceapply_BT".equals(yem_billtype.getString("number"))) {
                sourceEntryId = entity.getLong("yem_sourceentryids");
            } else {
                sourceEntryId = entity.getLong("yem_sourceentryid");
            }
            if (sourceEntryId > 0) {
//        DynamicObject bill = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
                DynamicObject bill = BusinessDataServiceHelper.loadSingle(sourceBillType,
                        new QFilter[]{new QFilter("id", QCP.equals, sourceBillId)});
                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");
                    }
                    for (DynamicObject detailedInfo : detailedInfos) {
                        if (detailedInfo.getLong("id") == sourceEntryId) {
                            detailedInfo.set("yem_sourceapplyno", "");
                            detailedInfo.set("yem_sourceapplyid", 0L);
                            break;
                        }
                    }
                    SaveServiceHelper.save(new DynamicObject[]{bill});
                }
            }
        }
    }


    /**
     * @description 过滤赠送配件分录产品机型
     * @author xwudd
     * @param[1] model
     * @param[2] e
     * return
     * @time 2023/11/15 10:33
     */

    public static void selectF7GiveProAcType(IDataModel model, BeforeF7SelectEvent e) {
        List<Long> ids = new ArrayList();
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", i);
            if (YEM.isNotEmpty(productModel)) {
                DynamicObject products = productModel.getDynamicObject("yem_products");
                if (YEM.isNotEmpty(products)) {
                    ids.add(products.getLong("id"));
                }
            }
        }
        int saleOrder_zpRows = model.getEntryRowCount("yem_es_salesorder_zp");
        for (int i = 0; i < saleOrder_zpRows; i++) {
            DynamicObject giveProAcType = (DynamicObject) model.getValue("yem_giveproactype", i);
            if (YEM.isNotEmpty(giveProAcType)) {
                ids.remove(giveProAcType.getLong("id"));
            }
        }
        e.addCustomQFilter(new QFilter("id", QCP.in, ids));
    }

    /**
     * @description 【赠送配件】页签，产品机型的台数不允许超出商品明细页签同一机型的数量合计值
     * @author xwudd
     * @param[1] view
     * @param[2] model
     * @param[3] oldValue
     * @param[4] rowIndex
     * return
     * @time 2023/11/15 11:00
     */

    public static void limitQtyInt(IFormView view, IDataModel model, Object oldValue, int rowIndex) {
        DynamicObject giveProAcType = (DynamicObject) model.getValue("yem_giveproactype", rowIndex);
        if (YEM.isNotEmpty(giveProAcType)) {
            Integer qtyInt = (Integer) model.getValue("yem_qtyint", rowIndex);
            long giveProAcTypeId = giveProAcType.getLong("id");
            BigDecimal materialQty = BigDecimal.ZERO;
            int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
            for (int i = 0; i < materialInfoRows; i++) {
                DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", i);
                if (YEM.isNotEmpty(productModel)) {
                    DynamicObject products = productModel.getDynamicObject("yem_products");
                    if (YEM.isNotEmpty(products)) {
                        long productsId = products.getLong("id");
                        if (giveProAcTypeId == productsId) {
                            materialQty = materialQty.add((BigDecimal) model.getValue("yem_qty", i));
                        }
                    }
                }
            }
            if (materialQty.compareTo(new BigDecimal(qtyInt)) < 0) {
                model.setValue("yem_qtyint", oldValue, rowIndex);
                view.showErrorNotification(String.format("产品机型%s的台数不允许超出商品明细页签同一机型的数量合计值【%s】", giveProAcType.getString("number"), materialQty));
            }
        } else {
            model.setValue("yem_qtyint", oldValue, rowIndex);
            view.showErrorNotification("请先选择产品机型！");
        }
    }
}
