package yem.wmc.imc.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//import json.JSONArray;
//import json.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.util.StringUtils;
import yem.base.common.utils.BigDecimalUtils;
import yem.base.common.utils.YEM;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author 金亮
 * @date 2023/12/26 11:37
 * @relevantfile
 * @description 发票jsonToData-将josn数据根据单据注册表新增到数据库中，dataToJson-将动态对象转化为指定的json格式
 * @versions 1.0
 */
public class JsonToDataUtils {
    static final String RegisterEntityName = "yem_imc_billsregister"; //单据注册 表名

    /**
     * 将json数据转化为动态对象，插入数据或者更新数据
     *  用于需要赋值单据编号并判断更新，用于最初的发票
     * @param entityName        单据标识（要插入的表名）
     * @param json              原生json
     * @param transformDatatype （转换类型）,查验json转换，还是识别数据转换 A 为识别， B为查验
     * @param invoiceSource     发票来源（手工录入，文件上传,发票归集...）
     * @return
     */
    public static DynamicObject jsonToData(String entityName, JSONObject json, String transformDatatype, String invoiceSource) {
        DynamicObject bill = null; //单据对象
        DynamicObjectCollection entryCollector = null;
        DynamicObject allDate = null;
        boolean isExist = false; // 数据库是否存在这条数据
        JSONObject invoiceVOs = null;
        JSONObject recognitionData = null;
        //发票代码
        String invoiceCode = "";
        //发票号码
        String invoiceNo = "";
        //单据编号（增值税专用发票）
        String billno = "";

        if (transformDatatype.equals("B")) { //转换数据类型为 查验
            JSONArray data = null;
            if (json.containsKey("data")) {
                data = json.getJSONArray("data");
            }
            if (data == null || data.size() == 0) {
                return null;
            }
            JSONObject invoiceVO = null;
            invoiceVOs = (JSONObject) data.get(0);
            if (invoiceVOs.containsKey("invoiceVO")) {

                invoiceVO = invoiceVOs.getJSONObject("invoiceVO");
                //发票代码 **
                if (invoiceVO.containsKey("invoiceCode")) {
                    invoiceCode = invoiceVO.getString("invoiceCode");
                }
                //发票号码
                if (invoiceVO.containsKey("invoiceNo")) {
                    invoiceNo = invoiceVO.getString("invoiceNo");
                }
                //单据编号（增值税专用发票）
                if (invoiceNo.equals("") || invoiceCode.equals("")) {
                    billno = invoiceNo + invoiceCode;
                } else {
                    billno = invoiceNo + "-" + invoiceCode;
                }
            }
        } else if (transformDatatype.equals("A")) { //识别  增值税发票识别和非增资税发票识别
            JSONArray recognitionList = null; // 识别 存储数据的那一层上面的list
            JSONObject recognitionJson = null; // 识别 存储数据的那一层
            if (json.containsKey("data")) {
                recognitionData = json.getJSONObject("data");
            }
            if (recognitionData.containsKey("invoiceList")) {
                String s = String.valueOf(recognitionData);

                if (recognitionData.getJSONArray("invoiceList").size() > 0) {
                    recognitionList = recognitionData.getJSONArray("invoiceList");//增值税发票信息List
                    recognitionJson = (JSONObject) recognitionList.get(0); //真正存储数据的那一层
                }
            }
            if (recognitionData.containsKey("nonVatInvoiceList")) {
                if (recognitionData.getJSONArray("nonVatInvoiceList").size() > 0) {
                    recognitionList = recognitionData.getJSONArray("nonVatInvoiceList");//非增值税发票信息List
                    recognitionJson = (JSONObject) recognitionList.get(0);
                }
            }
            //发票代码 **
            if (recognitionJson.containsKey("invoiceCode")) {
                invoiceCode = recognitionJson.getString("invoiceCode");
            }
            //发票号码
            if (recognitionJson.containsKey("invoiceNo")) {
                invoiceNo = recognitionJson.getString("invoiceNo");
            }
            //单据编号（增值税专用发票）
            if (invoiceNo.equals("") || invoiceCode.equals("")) {
                billno = invoiceNo + invoiceCode;
            } else {
                billno = invoiceNo + "-" + invoiceCode;
            }
        }
        try {
            // 判断：如果数据库中已经存在了这张表（根据单据编号），就不再往表中插入数据（增值税专用发票）,而是去更新数据
            DynamicObject dataBase = BusinessDataServiceHelper.loadSingle(entityName, "id", new QFilter[]{new QFilter("billno", QFilter.equals, billno)});
            if (dataBase != null) {
                //根据主键ID查询出所有的数据
                allDate = BusinessDataServiceHelper.loadSingle(dataBase.getPkValue(), entityName);
                bill = allDate; //使用数据库的数据
                isExist = true;
                //非增票 如果核销金额大于0，不允许更新。
                if (entityName.equals("yem_imc_taxi") || entityName.equals("yem_imc_trains") || entityName.equals("yem_imc_air")) {
                    boolean yemModifiable = bill.getBoolean("yem_modifiable");//是否可修改
                    if (!yemModifiable) {
                        return bill;
                    }
                }
            } else {
                // 新增单据
                bill = BusinessDataServiceHelper.newDynamicObject(entityName);
                bill.set("billno", billno);
            }
            // 判断对应的单据注册表是否存在，如果存在就使用，不存在的话就直接返回null
            QFilter qFilter1 = new QFilter("yem_formid.number", QCP.equals, entityName); // 单据标识
            QFilter qFilter2 = new QFilter("yem_transformway", QCP.equals, "B"); // 转换方式 (B 为 json转换data)
            QFilter qFilter3 = new QFilter("yem_datatype", QCP.equals, transformDatatype); // 转换数据类型
            DynamicObject registerObject = BusinessDataServiceHelper.loadSingle(RegisterEntityName, "id,billno,billstatus", new QFilter[]{qFilter1, qFilter2, qFilter3});
            String billnoName = registerObject.getString("billno");
            if (registerObject == null) {
                return null;
            }
            // 从单据注册表中查询出所有的数据
            registerObject = BusinessDataServiceHelper.loadSingle(registerObject.getPkValue(), RegisterEntityName);

            // 获取到单据注册表的单据体-实体容器，并且遍历实体容器
            DynamicObjectCollection yem_entitycontainer_s = registerObject.getDynamicObjectCollection("yem_entitycontainer");
            JSONObject realJson = null;
            if (null == yem_entitycontainer_s || yem_entitycontainer_s.size() == 0) {
                return null;
            }

            Map entry_map = new HashMap();
            //  把整个实体容器字段集合-左边的遍历
            for (int i = 0; i < yem_entitycontainer_s.size(); i++) {
                DynamicObject yem_entitycontainer = yem_entitycontainer_s.get(i);
                String yem_entitytype = yem_entitycontainer.getString("yem_entitytype");//实体类型
                String yem_entityformid = yem_entitycontainer.getString("yem_entityformid");//容器标识
                String yem_parentcontainer = yem_entitycontainer.getString("yem_parentcontainer");//父级容器
                String yem_jsonformid = yem_entitycontainer.getString("yem_jsonformid");//json标识
//                    boolean yem_issubentry = yem_entitycontainer.getBoolean("yem_issubentry");//是否子分录
                String yem_entryformid = yem_entitycontainer.getString("yem_entryformid");//分录标识
                DynamicObjectCollection yem_entityfieldcol_s = yem_entitycontainer.getDynamicObjectCollection("yem_entityfieldcol");//实体容器对应的整个实体字段集合
                if (StringUtils.isEmpty(yem_jsonformid)) {
                    continue;
                }
                if (null != yem_entityfieldcol_s && yem_entityfieldcol_s.size() > 0) {
                    if ("A".equals(yem_entitytype)) { //单据头
                        if (transformDatatype.equals("B")) { //查验
                            // 从源生josn里面获取 json标识
                            realJson = invoiceVOs.getJSONObject(yem_jsonformid);
                        } else if (transformDatatype.equals("A")) { //识别
                            realJson = (JSONObject) recognitionData.getJSONArray(yem_jsonformid).get(0);
                        }
                        // 遍历这一行对应的实体字段集合
                        for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                            DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                            //ERP字段标识（表单的字段）右边的
                            String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");
                            // 字段类型 数字类型是 munber String是text 基础资料是basedata
                            String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");
                            // json字段标识，对应的json数据上的标识
                            String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");
                            //默认值
                            String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");
                            //定义基础数据唯一标识 一般都是 ，，munber
                            String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");
                            // 字段类型名称 就是基础资料的使用的表名
                            String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");
                            String val = "";
                            //  优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                            if (StringUtils.isNotEmpty(yem_defaultvalue)) {//判断配置的默认值是否为空
                                val = yem_defaultvalue;
                            } else { //如果默认值为空，从json里面获取
                                if (realJson.containsKey(yem_jsonfieldid)) {
                                    val = realJson.getString(yem_jsonfieldid);
                                }
                            }
                            if ("basedata".equals(yem_filedtype)) { //如果字段是对象类型的值，给单据对象修改值
                                // 从基础资料表中查询出来并设置对应的基础资料
                                bill.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                            } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {//字段类型为时间的
                                if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                    bill.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                }
                            } else if ("number".equals(yem_filedtype)) { //字段类型为数字类型的
                                if (StringUtils.isNotEmpty(val)) {
                                    bill.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                }
                            } else { //否则就是文本类型的，直接使用获取到的json
                                if (StringUtils.isNotEmpty(val)) {
                                    bill.set(yem_erpfiledformid, val);
                                }
                            }
                            //赋值（根据单据注册表进行）
//                            if ("billno".equals(yem_erpfiledformid)) { //单据编号
//                                bill.set(yem_erpfiledformid, billno);
//                            }
                            if ("yem_check_status".equals(yem_erpfiledformid)) { //查验状态
                                if (transformDatatype.equals("B")) { //数据类型为 查验
                                    if (invoiceVOs.containsKey("checkFlag")) {
                                        Boolean checkFlag = invoiceVOs.getBoolean("checkFlag");
                                        if (checkFlag) {
                                            bill.set(yem_erpfiledformid, "1");//查验成功（已查验）
                                        } else {
                                            bill.set(yem_erpfiledformid, "2");//查验失败
                                        }
                                    }
                                }
                                if (invoiceSource.equals("发票归集")) { //如果是发票归集设置固定查验状态
                                    bill.set(yem_erpfiledformid, "1");//查验成功（已查验）
                                }
                            }
                            if ("yem_check_time".equals(yem_erpfiledformid)) { //查验时间（增值税发票）
                                if (entityName.equals("yem_imc_electric") || entityName.equals("yem_imc_eoinvoice") || entityName.equals("yem_imc_esinvoice")) {
                                    bill.set(yem_erpfiledformid, new Date());
                                }
                            }
                            if (entityName.equals("yem_imc_electric") || entityName.equals("yem_imc_eoinvoice") || entityName.equals("yem_imc_esinvoice")) {//查验次数
                                if ("yem_check_times".equals(yem_erpfiledformid) && isExist == false) { //第一次
                                    bill.set(yem_erpfiledformid, "1");
                                } else if ("yem_check_times".equals(yem_erpfiledformid) && isExist == true) {
                                    String checkFrequencyStr = bill.getString(yem_erpfiledformid);
                                    bill.set(yem_erpfiledformid, Integer.valueOf(checkFrequencyStr) + 1);
                                }
                            }
                            if ("auditor".equals(yem_erpfiledformid) || "modifier".equals(yem_erpfiledformid) || "creator".equals(yem_erpfiledformid)) { //设置为当前用户
                                bill.set(yem_erpfiledformid, CommonUtils.getCurrentUser());
                            }
                            if ("auditdate".equals(yem_erpfiledformid)) { //审核时间为当前时间
                                bill.set(yem_erpfiledformid, new Date());
                            }
                            if ("yem_invoice_info".equals(yem_erpfiledformid)) {  //发票信息
                                if (entityName.equals("yem_imc_esinvoice")) {
                                    //增值税专用发票，未用，已验，未签收）
                                    bill.set(yem_erpfiledformid, ",ty_4," + "ex_1," + "ch_1," + "or_0,");
                                } else if (entityName.equals("yem_imc_eoinvoice")) {
                                    //增值税普通发票，未用，已验,未签收
                                    bill.set(yem_erpfiledformid, ",ty_3," + "ex_1," + "ch_1," + "or_0,");
                                } else if (entityName.equals("yem_imc_electric")) {
                                    //全电专票，未用，已验,未签收,未勾选
                                    bill.set(yem_erpfiledformid, ",ty_27," + "ex_1," + "ch_1," + "or_0," + "au_0,");
                                } else if (entityName.equals("yem_imc_taxi")) {
                                    //出租车
                                    bill.set(yem_erpfiledformid, ",ty_8," + "ex_1," + "or_0,");
                                } else if (entityName.equals("yem_imc_trains")) {
                                    //火车
                                    bill.set(yem_erpfiledformid, ",ty_9," + "ex_1," + "or_0,");
                                } else if (entityName.equals("yem_imc_air")) {
                                    //飞机
                                    bill.set(yem_erpfiledformid, ",ty_10," + "ex_1," + "or_0,");
                                } else if (entityName.equals("yem_imc_travel")) {
                                    // 滴滴打车（暂时待定为 其他票）
                                    bill.set(yem_erpfiledformid, ",ty_11," + "ex_1," + "or_0,");
                                }
                            }
                            if ("yem_serial_no".equals(yem_erpfiledformid) || "yem_aws_serial_no".equals(yem_erpfiledformid)) { //流水号和AWS发票流水号
                                String serialNo = "";
                                if (json.containsKey("serialNo")) {
                                    serialNo = json.getString("serialNo");
                                }
                                bill.set("yem_serial_no", serialNo);
                                bill.set("yem_aws_serial_no", serialNo);
                            }
                            if ("yem_resource".equals(yem_erpfiledformid) && StringUtils.isNotEmpty(invoiceSource)) {  //发票来源
                                bill.set(yem_erpfiledformid, invoiceSource);
                            }
                            if ("yem_collect_type".equals(yem_erpfiledformid) && StringUtils.isNotEmpty(invoiceSource)) {  //采集方式
                                if (invoiceSource.equals("手工录入")) {//手工录入
                                    bill.set(yem_erpfiledformid, "5");
                                } else if (invoiceSource.equals("文件上传")) {
                                    bill.set(yem_erpfiledformid, "2");
                                } else if (invoiceSource.equals("发票归集")) {
                                    // 暂时单据上没有能对应的下拉项，后期调整
                                }
                            }
                            if ("yem_is_revise".equals(yem_erpfiledformid) && isExist == true) {  //是否修改
                                bill.set(yem_erpfiledformid, "1"); //是
                            } else if ("yem_is_revise".equals(yem_erpfiledformid) && isExist == false) {
                                bill.set(yem_erpfiledformid, "0"); //否
                            }
                        }
                    } else { //   B   这是单据体的
                        if (StringUtils.isNotEmpty(yem_parentcontainer)) {//父级容器不为空
                        } else {
                            entryCollector = bill.getDynamicObjectCollection(yem_entityformid);
                            if (!isExist) { //数据库里没有这个数据的时候,插入操作
                                // 获取到json上面的单据体
                                JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                                if (detailList != null) {
                                    for (int k = 0; k < detailList.size(); k++) {
                                        // 从json中获取每一层单据体数据
                                        JSONObject entryData = detailList.getJSONObject(k);
                                        DynamicObject entry = entryCollector.addNew(); //新增一行分录
                                        // 遍历实体字段集合
                                        for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                                            DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                                            String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");//ERP字段标识
                                            String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");//字段类型
                                            String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");//json字段标识
                                            String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");//默认值
                                            String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");//定义基础数据唯一标识
                                            String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");//字段类型名称

                                            String val = "";
                                            //优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                                            if (StringUtils.isNotEmpty(yem_defaultvalue)) {//判断配置的默认值是否为空
                                                val = yem_defaultvalue;
                                            } else {
                                                if (entryData.containsKey(yem_jsonfieldid)) {//判断jsom中之后包含配置的json标识
                                                    //配置中默认值为空并且动态默认也为空 则 根据字段类型赋值，类型有（基础资料、日期、文本、下拉列表、数值，单据类型，）
                                                    val = entryData.getString(yem_jsonfieldid);
                                                }
                                            }
                                            if ("basedata".equals(yem_filedtype)) {
                                                entry.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                                            } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {
                                                if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                                    entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                                } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                                    entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                                } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                                    entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                                } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                                    entry.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                                }
                                            } else if ("number".equals(yem_filedtype)) {
                                                entry.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                            } else {
                                                if (StringUtils.isNotEmpty(val)) {
                                                    entry.set(yem_erpfiledformid, val);
                                                }
                                            }
                                        }
                                        // 判断map里面是否存在这个单据体或者表的标识
                                        if (entry_map.containsKey(yem_entityformid)) {
                                            List index_s = (List) entry_map.get(yem_entityformid);
                                            index_s.add(entryCollector.size() - 1);
                                            entry_map.put(yem_entityformid, index_s);
                                        } else {
                                            List index_s = new ArrayList();
                                            index_s.add(entryCollector.size() - 1);
                                            entry_map.put(yem_entityformid, index_s);
                                        }
                                    }
                                }
                            } else if (isExist) { //数据库存在数据的时候，更新操作
                                // 获取到json上面的单据体
                                JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                                if (detailList != null) {
                                    for (int k = 0; k < detailList.size(); k++) {
                                        // 从json中获取每一行单据体数据
                                        JSONObject entryData = detailList.getJSONObject(k);
                                        DynamicObject dynamicObject = entryCollector.get(k);
                                        //遍历
                                        for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                                            DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                                            String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");//ERP字段标识
                                            String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");//字段类型
                                            String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");//json字段标识
                                            String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");//默认值
//                                                String yem_modledefaultvalue = yem_entityfieldcol.getString("yem_modledefaultvalue");//动态默认
                                            String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");//定义基础数据唯一标识
                                            String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");//字段类型名称
                                            String val = "";
                                            //优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                                            if (StringUtils.isNotEmpty(yem_defaultvalue)) {//判断配置的默认值是否为空
                                                val = yem_defaultvalue;
                                            } else {
                                                if (entryData.containsKey(yem_jsonfieldid)) {//判断jsom中之后包含配置的json标识
                                                    //配置中默认值为空并且动态默认也为空 则 根据字段类型赋值，类型有（基础资料、日期、文本、下拉列表、数值，单据类型，）
                                                    val = entryData.getString(yem_jsonfieldid);
                                                }
                                            }
                                            if ("basedata".equals(yem_filedtype)) {
                                                dynamicObject.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                                            } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {
                                                if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                                    dynamicObject.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                                } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                                    dynamicObject.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                                } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                                    dynamicObject.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                                } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                                    dynamicObject.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                                }
                                            } else if ("number".equals(yem_filedtype)) {
                                                dynamicObject.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                            } else {
                                                if (StringUtils.isNotEmpty(val)) {
                                                    dynamicObject.set(yem_erpfiledformid, val);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            // 设置 非增票 如果核销金额大于0，不允许更新。
            if (!isExist) {
                if (entityName.equals("yem_imc_taxi") || entityName.equals("yem_imc_trains") || entityName.equals("yem_imc_air")) { //非增票
                    BigDecimal yemWriteoffamt = bill.getBigDecimal("yem_writeoffamt");//账票已核销金额
                    if (yemWriteoffamt.compareTo(BigDecimal.ZERO) > 0) { //如果核销金额大于零，则不能修改
                        bill.set("yem_modifiable", false);
                    } else {
                        bill.set("yem_modifiable", true);
                    }
                } else { //增值税发票都是可以修改的
                    bill.set("yem_modifiable", true);
                }
            }
            // 设置 采集用户单据体
            if (!isExist) { //新增数据
                DynamicObjectCollection gatherUser = bill.getDynamicObjectCollection("yem_collect_user_entry");
                DynamicObject dynamicObject = gatherUser.addNew();//新增一行分录
                dynamicObject.set("yem_collect_user", CommonUtils.getCurrentUser());//用户
                Long currentUserId = UserServiceHelper.getCurrentUserId();
                long userMainOrgId = UserServiceHelper.getUserMainOrgId(currentUserId);
                DynamicObject bosOrg = BusinessDataServiceHelper.loadSingle(userMainOrgId, "bos_org");
                dynamicObject.set("yem_collect_user_org", bosOrg);//采集人最后一次操作组织
                dynamicObject.set("yem_collect_user_time", new Date());//操作时间
                if (StringUtils.isNotEmpty(invoiceSource)) {
                    dynamicObject.set("yem_source", invoiceSource);//来源
                }
                dynamicObject.set("yem_datetime", new Date());//时间
            } else { //新增一行
                DynamicObjectCollection gatherUser = bill.getDynamicObjectCollection("yem_collect_user_entry");
                DynamicObject rowNew = gatherUser.addNew();
                if (StringUtils.isNotEmpty(invoiceSource)) {
                    rowNew.set("yem_source", invoiceSource);//来源
                }
                rowNew.set("yem_collect_user", CommonUtils.getCurrentUser());//用户
                Long currentUserId = UserServiceHelper.getCurrentUserId();
                long userMainOrgId = UserServiceHelper.getUserMainOrgId(currentUserId);//组织id
                DynamicObject bosOrg = BusinessDataServiceHelper.loadSingle(userMainOrgId, "bos_org");
                rowNew.set("yem_collect_user_org", bosOrg);//采集人最后一次操作组织
                rowNew.set("yem_collect_user_time", new Date());//操作时间
                rowNew.set("yem_datetime", new Date());//时间
            }

            // 设置表头字段-主要商品名称（使用分录里面出现次数最多的商品名称）
            if (entryCollector != null && entryCollector.size() > 0) {
                HashMap<String, Integer> goodsNameMap = new HashMap<>();
                for (DynamicObject dynamicObject : entryCollector) {
                    String goodsName = "";
                    if (dynamicObject.containsProperty("yem_goods_name")) {
                        goodsName = dynamicObject.getString("yem_goods_name");
                    } else if (dynamicObject.containsProperty("yem_goodsname")) { //全电发票的商品名称标识不一样
                        goodsName = dynamicObject.getString("yem_goodsname");
                    }
                    if (goodsNameMap.containsKey(goodsName)) { //判断集合中是否有这个元素,如果有则value+1;
                        Integer i = goodsNameMap.get(goodsName);
                        goodsNameMap.put(goodsName, 1 + i);
                    } else {
                        goodsNameMap.put(goodsName, 1);
                    }
                }
                // 遍历Map，将key和value存入不同的集合中
                ArrayList<String> goodsNames = new ArrayList<>();
                ArrayList<Integer> goodsNamesCount = new ArrayList<>();
                for (String goodsName : goodsNameMap.keySet()) {
                    goodsNames.add(goodsName); //存入遍历的商品名
                    goodsNamesCount.add(goodsNameMap.get(goodsName)); //存入遍历的商品名出现次数
                }
                Integer max = Collections.max(goodsNamesCount);
                String moreGoodsName = goodsNames.get(goodsNamesCount.indexOf(max));
                if (bill.containsProperty("yem_main_goods_name")) {
                    bill.set("yem_main_goods_name", moreGoodsName);
                }
            }
            // 保存
            OperationServiceHelper.executeOperate("save", entityName, new DynamicObject[]{bill},
                    OperateOption.create());
        } catch (Exception e) {
            return null;
        }
        return bill;
    }


    /**
     * 用于不需要单据编码直接新增
     * @param entityName 单据标识（要插入的表名）
     * @param realJson 要插入的josn数据
     * @param elseJson 其他json数据
     * @return
     */

    public static DynamicObject jsonToData(String entityName, JSONObject realJson, JSONObject elseJson) {
        boolean isExist = false; // 数据库是否存在这条数据

        // 判断：数据应该更新还是新增
        DynamicObject bill = null;
        bill = BusinessDataServiceHelper.newDynamicObject(entityName);
        QFilter qFilter1 = new QFilter("yem_formid.number", QCP.equals, entityName); // 单据标识
        DynamicObject registerObject = BusinessDataServiceHelper.loadSingle(RegisterEntityName, "id,billno,billstatus", new QFilter[]{qFilter1});
        if (registerObject == null) {
            return null;
        }
        registerObject = BusinessDataServiceHelper.loadSingle(registerObject.getPkValue(), RegisterEntityName);
        //实体容器
        DynamicObjectCollection yem_entitycontainer_s = registerObject.getDynamicObjectCollection("yem_entitycontainer");
        if (null == yem_entitycontainer_s || yem_entitycontainer_s.size() == 0) {
            return null;
        }
        // 遍历实体容器
        for (int i = 0; i < yem_entitycontainer_s.size(); i++) {
            DynamicObject yem_entitycontainer = yem_entitycontainer_s.get(i);
            String yem_entitytype = yem_entitycontainer.getString("yem_entitytype");//实体类型
            String yem_entityformid = yem_entitycontainer.getString("yem_entityformid");//容器标识
            String yem_parentcontainer = yem_entitycontainer.getString("yem_parentcontainer");//父级容器
            String yem_jsonformid = yem_entitycontainer.getString("yem_jsonformid");//json标识
            String yem_entryformid = yem_entitycontainer.getString("yem_entryformid");//分录标识
            DynamicObjectCollection yem_entityfieldcol_s = yem_entitycontainer.getDynamicObjectCollection("yem_entityfieldcol");//实体容器对应的整个实体字段集合
            if (null != yem_entityfieldcol_s && yem_entityfieldcol_s.size() > 0) {
                if ("A".equals(yem_entitytype)) { //单据头
                    traversalAssignment(yem_entityfieldcol_s, realJson, bill);
                } else if ("B".equals(yem_entitytype)) { //单据体
                    DynamicObjectCollection entryCollector = bill.getDynamicObjectCollection(yem_entityformid);
                    if (!isExist) {
                        JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                        if (detailList != null) {
                            for (int k = 0; k < detailList.size(); k++) {
                                JSONObject entryData = detailList.getJSONObject(k);
                                DynamicObject entry = entryCollector.addNew(); //新增一行分录
                                traversalAssignment(yem_entityfieldcol_s, entryData, entry);
                            }
                        }
                    } else if (isExist) { //更新操作
                        JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                        if (detailList != null) {
                            for (int k = 0; k < detailList.size(); k++) {
                                JSONObject entryData = detailList.getJSONObject(k);
                                DynamicObject dynamicObject = entryCollector.get(k);
                                traversalAssignment(yem_entityfieldcol_s, entryData, dynamicObject);
                            }
                        }
                    }
                } else if ("C".equals(yem_entitytype)) { //子单据体
                    // 获取父容器标识
                    if (yem.base.common.utils.StringUtils.isEmpty(yem_parentcontainer)) {
                        return null;
                    }
                    String fatherJsonBS = null;
                    for (DynamicObject yemEntitycontainer : yem_entitycontainer_s) { //单据注册表
                        String yemEntityformid = yemEntitycontainer.getString("yem_entityformid");//容器标识
                        if (yemEntityformid.equals(yem_parentcontainer)) {
                            fatherJsonBS = yemEntitycontainer.getString("yem_jsonformid");//json标识（父级json标识）
                        }
                    }
                    if (fatherJsonBS == null) {
                        return null;
                    }
                    DynamicObjectCollection superiorContainer = bill.getDynamicObjectCollection(yem_parentcontainer);//父级分录（已存入数据）
                    for (int index = 0; index < superiorContainer.size(); index++) {
                        DynamicObject rowDynamic = superiorContainer.get(index);
                        DynamicObjectCollection subordinate = rowDynamic.getDynamicObjectCollection(yem_entityformid);//子容器标识
                        if (!isExist) { //数据库里没有这个数据的时候,插入操作
                            JSONArray detailList = realJson.getJSONArray(fatherJsonBS);
                            if (detailList != null && detailList.size() > 0) {
                                JSONObject jsonObject = detailList.getJSONObject(index);
                                JSONArray jsonArray = jsonObject.getJSONArray(yem_jsonformid);
                                for (Object object : jsonArray) {
                                    JSONObject sonRowJsonObj = (JSONObject) object;
                                    DynamicObject entry = subordinate.addNew();
                                    // 遍历实体字段集合
                                    traversalAssignment(yem_entityfieldcol_s, sonRowJsonObj, entry);
                                }
                            }
                        } else if (isExist) { //更新
                            subordinate.clear();
                            JSONArray detailList = realJson.getJSONArray(fatherJsonBS);
                            if (detailList != null && detailList.size() > 0) {
                                JSONObject jsonObject = detailList.getJSONObject(index);
                                JSONArray jsonArray = jsonObject.getJSONArray(yem_jsonformid);//子jssonA 数据
                                for (Object object : jsonArray) {
                                    JSONObject sonRowJsonObj = (JSONObject) object;
                                    DynamicObject entry = subordinate.addNew();
                                    traversalAssignment(yem_entityfieldcol_s, sonRowJsonObj, entry);
                                }
                            }
                        }
                    }
                }
            }
        }
        // 保存
        OperationResult operationResult = OperationServiceHelper.executeOperate("save", entityName, new DynamicObject[]{bill},
                OperateOption.create());
        boolean success = operationResult.isSuccess();
        if (!success) {
            return null;
        }
        return bill;
    }
    
    /**
     * @param entityName 单据标识（要插入的表名）
     * @param realJson   原生json
     * @return
     */
    public static DynamicObject jsonToData(String entityName, JSONObject realJson) {
        DynamicObject bill = null; //单据对象
        DynamicObjectCollection entryCollector = null; //单据体对象
        DynamicObject allDate = null; //数据库存在的对象
        boolean isExist = false; // 数据库是否存在这条数据

        //主键
        String billno = null;
        if (realJson.containsKey("keyid")) {
            billno = realJson.getString("keyid").substring(0, 21) + "3011";
        } else {
            return null;
        }

        // 判断：如果数据库中已经存在了这张表（根据单据编号），就不再往表中插入数据（增值税专用发票）,而是去更新数据
        DynamicObject dataBase = BusinessDataServiceHelper.loadSingle(entityName, "id", new QFilter[]{new QFilter("billno", QFilter.equals, billno)});
        if (dataBase != null) {
            //根据主键ID查询出所有的数据
            bill = BusinessDataServiceHelper.loadSingle(dataBase.getPkValue(), entityName);
            isExist = true;
        } else {
            // 新增单据
            bill = BusinessDataServiceHelper.newDynamicObject(entityName);
        }

        String RegisterEntityName = "yem_cm_billogon"; //单据注册 - 新
        // 判断对应的单据注册表是否存在，如果存在就使用，不存在的话就直接返回null
        QFilter qFilter1 = new QFilter("yem_formid.number", QCP.equals, entityName); // 单据标识
        DynamicObject registerObject = BusinessDataServiceHelper.loadSingle(RegisterEntityName, "id,billno,billstatus", new QFilter[]{qFilter1});
        String billnoName = registerObject.getString("billno");
        if (registerObject == null) {
            return null;
        }
        // 从单据注册表中查询出所有的数据
        registerObject = BusinessDataServiceHelper.loadSingle(registerObject.getPkValue(), RegisterEntityName);

        // 获取到单据注册表的单据体-实体容器，并且遍历实体容器
        DynamicObjectCollection yem_entitycontainer_s = registerObject.getDynamicObjectCollection("yem_entitycontainer");
        if (null == yem_entitycontainer_s || yem_entitycontainer_s.size() == 0) {
            return null;
        }
        Map entry_map = new HashMap();
        //  把整个实体容器字段集合-左边的遍历
        for (int i = 0; i < yem_entitycontainer_s.size(); i++) {
            DynamicObject yem_entitycontainer = yem_entitycontainer_s.get(i);
            String yem_entitytype = yem_entitycontainer.getString("yem_entitytype");//实体类型
            String yem_entityformid = yem_entitycontainer.getString("yem_entityformid");//容器标识
            String yem_parentcontainer = yem_entitycontainer.getString("yem_parentcontainer");//父级容器
            String yem_jsonformid = yem_entitycontainer.getString("yem_jsonformid");//json标识
//                    boolean yem_issubentry = yem_entitycontainer.getBoolean("yem_issubentry");//是否子分录
            String yem_entryformid = yem_entitycontainer.getString("yem_entryformid");//分录标识
            DynamicObjectCollection yem_entityfieldcol_s = yem_entitycontainer.getDynamicObjectCollection("yem_entityfieldcol");//实体容器对应的整个实体字段集合
            if (StringUtils.isEmpty(yem_jsonformid)) {
                continue;
            }
            if (null != yem_entityfieldcol_s && yem_entityfieldcol_s.size() > 0) {
                if ("A".equals(yem_entitytype)) { //单据头
                    // 遍历这一行对应的实体字段集合
                    for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                        DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                        //ERP字段标识（表单的字段）右边的
                        String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");
                        // 字段类型 数字类型是 munber String是text 基础资料是basedata
                        String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");
                        // json字段标识，对应的json数据上的标识
                        String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");
                        //默认值
                        String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");
                        //定义基础数据唯一标识 一般都是 ，，munber
                        String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");
                        // 字段类型名称 就是基础资料的使用的表名
                        String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");
                        String val = "";
                        //  优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                        if (StringUtils.isNotEmpty(yem_defaultvalue)) {
                            val = yem_defaultvalue;
                        } else { //如果默认值为空，从json里面获取
                            if (realJson.containsKey(yem_jsonfieldid)) {
                                val = realJson.getString(yem_jsonfieldid);//都可以使用String来获取
                            }
                        }
                        if ("basedata".equals(yem_filedtype)) { //如果字段是对象类型的值，给单据对象修改值
                            // 从基础资料表中查询出来并设置对应的基础资料
                            bill.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                        } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {//字段类型为时间的
                            if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                            } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                            } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                            } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                bill.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                            }
                        } else if ("number".equals(yem_filedtype)) { //字段类型为数字类型的
                            if (StringUtils.isNotEmpty(val)) {
                                bill.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                            }
                        } else if ("org".equals(yem_filedtype)) { //组织
                            Long currentUserId = UserServiceHelper.getCurrentUserId();
                            Long mainOrgId = UserServiceHelper.getUserMainOrgId(currentUserId);
                            bill.set(yem_erpfiledformid, mainOrgId);
                        } else { //否则就是文本类型的，直接使用获取到的json
                            if (StringUtils.isNotEmpty(val)) {
                                if (val.length() > 50) {
                                    bill.set(yem_erpfiledformid, val.substring(0, 39));
                                } else {
                                    bill.set(yem_erpfiledformid, val);
                                }
                            }
                        }
                        //赋值（不根据单据注册表进行）
                        if ("billno".equals(yem_erpfiledformid)) { //单据编号
                            bill.set(yem_erpfiledformid, billno);
                        }
                        if ("auditor".equals(yem_erpfiledformid)) { //审核人设置为当前用户
                            bill.set(yem_erpfiledformid,CommonUtils.getCurrentUser());
                        }
                        if ("auditdate".equals(yem_erpfiledformid)) { //审核时间为当前时间
                            bill.set(yem_erpfiledformid, new Date());
                        }
                        if ("modifier".equals(yem_erpfiledformid)) { //修改人设置为当前用户
                            bill.set(yem_erpfiledformid,CommonUtils.getCurrentUser());
                        }
                        if ("creator".equals(yem_erpfiledformid)) { //创建人为设置为当前用户
                            bill.set(yem_erpfiledformid, CommonUtils.getCurrentUser());
                        }
                    }
                } else if ("B".equals(yem_entitytype)) { //这是单据体
                        entryCollector = bill.getDynamicObjectCollection(yem_entityformid);
                        if (!isExist) { //数据库里没有这个数据的时候,插入操作
                            // 获取到json上面的单据体
                            JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                            if (detailList != null) {
                                for (int k = 0; k < detailList.size(); k++) {
                                    // 从json中获取每一层单据体数据
                                    JSONObject entryData = detailList.getJSONObject(k);
                                    DynamicObject entry = entryCollector.addNew(); //新增一行分录
                                    // 遍历实体字段集合
                                    for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                                        DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                                        String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");//ERP字段标识
                                        String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");//字段类型
                                        String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");//json字段标识
                                        String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");//默认值
                                        String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");//定义基础数据唯一标识
                                        String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");//字段类型名称
                                        String val = "";
                                        //优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                                        if (StringUtils.isNotEmpty(yem_defaultvalue)) {//判断配置的默认值是否为空
                                            val = yem_defaultvalue;
                                        } else {
                                            if (entryData.containsKey(yem_jsonfieldid)) {//判断jsom中之后包含配置的json标识
                                                //配置中默认值为空并且动态默认也为空 则 根据字段类型赋值，类型有（基础资料、日期、文本、下拉列表、数值，单据类型，）
                                                val = entryData.getString(yem_jsonfieldid);
                                            }
                                        }
                                        if ("basedata".equals(yem_filedtype)) {
                                            entry.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                                        } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {
                                            if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                            } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                            }
                                        } else if ("number".equals(yem_filedtype)) {
                                            entry.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                        } else { //文本类型
                                            if (StringUtils.isNotEmpty(val)) {
                                                if (val.length() > 50) {
                                                    entry.set(yem_erpfiledformid, val.substring(0, 39));
                                                } else {
                                                    entry.set(yem_erpfiledformid, val);
                                                }
                                            }
                                        }
                                    }
                                    // 判断map里面是否存在这个单据体或者表的标识  不知道这一步是干嘛
                                    if (entry_map.containsKey(yem_entityformid)) {
                                        List index_s = (List) entry_map.get(yem_entityformid);
                                        index_s.add(entryCollector.size() - 1);
                                        entry_map.put(yem_entityformid, index_s);
                                    } else {
                                        List index_s = new ArrayList();
                                        index_s.add(entryCollector.size() - 1);
                                        entry_map.put(yem_entityformid, index_s);
                                    }
                                }
                            }
                        } else if (isExist) { //数据库存在数据的时候，更新操作
                            // 获取到json上面的单据体
                            JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                            if (detailList != null) {
                                for (int k = 0; k < detailList.size(); k++) {
                                    // 从json中获取每一行单据体数据
                                    JSONObject entryData = detailList.getJSONObject(k);
                                    DynamicObject dynamicObject = entryCollector.get(k);
                                    //遍历
                                    for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                                        DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                                        String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");//ERP字段标识
                                        String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");//字段类型
                                        String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");//json字段标识
                                        String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");//默认值
//                                                String yem_modledefaultvalue = yem_entityfieldcol.getString("yem_modledefaultvalue");//动态默认
                                        String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");//定义基础数据唯一标识
                                        String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");//字段类型名称
                                        String val = "";
                                        //优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                                        if (StringUtils.isNotEmpty(yem_defaultvalue)) {//判断配置的默认值是否为空
                                            val = yem_defaultvalue;
                                        } else {
                                            if (entryData.containsKey(yem_jsonfieldid)) {//判断jsom中之后包含配置的json标识
                                                //配置中默认值为空并且动态默认也为空 则 根据字段类型赋值，类型有（基础资料、日期、文本、下拉列表、数值，单据类型，）
                                                val = entryData.getString(yem_jsonfieldid);
                                            }
                                        }
                                        if ("basedata".equals(yem_filedtype)) {
                                            dynamicObject.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                                        } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {
                                            if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                                dynamicObject.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                                dynamicObject.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                            } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                                dynamicObject.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                                dynamicObject.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                            }
                                        } else if ("number".equals(yem_filedtype)) {
                                            dynamicObject.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                        } else {
                                            if (StringUtils.isNotEmpty(val)) {
                                                dynamicObject.set(yem_erpfiledformid, val);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                } else if ("C".equals(yem_entitytype)) { //子单据体
                    // 获取父容器标识
                    if (StringUtils.isEmpty(yem_parentcontainer)) {
                        return null;
                    }
                    // 获取到父级容器的json标识
                    String fatherJsonBS = null;
                    for (DynamicObject yemEntitycontainer : yem_entitycontainer_s) { //单据注册表
                        String yemEntityformid = yemEntitycontainer.getString("yem_entityformid");//容器标识
                        if (yemEntityformid.equals(yem_parentcontainer)) {
                            fatherJsonBS = yemEntitycontainer.getString("yem_jsonformid");//json标识（父级json标识）
                        }
                    }
                    if (fatherJsonBS ==null ){
                        return null;
                    }
                    DynamicObjectCollection superiorContainer = bill.getDynamicObjectCollection(yem_parentcontainer);//父级分录（已存入数据）
                    for (int index = 0; index < superiorContainer.size(); index++) {//遍历父容器
                        DynamicObject rowDynamic = superiorContainer.get(index);//每一行父分录
                        DynamicObjectCollection subordinate = rowDynamic.getDynamicObjectCollection(yem_entityformid);//子容器标识
                        if (!isExist) { //数据库里没有这个数据的时候,插入操作
                            // 获取到json上面的单据体
                            JSONArray detailList = realJson.getJSONArray(fatherJsonBS);//json（父级json）
                            if (detailList != null && detailList.size() > 0) {
                                JSONObject jsonObject = detailList.getJSONObject(index);//获取对应父分录哪一行的json数据
                                // 从json中获取每一层单据体数据
                                JSONArray jsonArray = jsonObject.getJSONArray(yem_jsonformid);//子jssonA 数据
                                for (Object object : jsonArray) {
                                    JSONObject sonRowJsonObj = (JSONObject) object;
                                    DynamicObject entry = subordinate.addNew();
                                    // 遍历实体字段集合
                                    for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                                        DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                                        String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");//ERP字段标识
                                        String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");//字段类型
                                        String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");//json字段标识
                                        String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");//默认值
                                        String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");//定义基础数据唯一标识
                                        String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");//字段类型名称
                                        String val = "";
                                        //优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                                        if (StringUtils.isNotEmpty(yem_defaultvalue)) {//判断配置的默认值是否为空
                                            val = yem_defaultvalue;
                                        } else {
                                            if (sonRowJsonObj.containsKey(yem_jsonfieldid)) {//判断jsom中之后包含配置的json标识
                                                //配置中默认值为空并且动态默认也为空 则 根据字段类型赋值，类型有（基础资料、日期、文本、下拉列表、数值，单据类型，）
                                                val = sonRowJsonObj.getString(yem_jsonfieldid);
                                            }
                                        }
                                        if ("basedata".equals(yem_filedtype)) {
                                            entry.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                                        } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {
                                            if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                            } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                            }
                                        } else if ("number".equals(yem_filedtype)) {
                                            entry.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                        } else { //文本类型
                                            if (StringUtils.isNotEmpty(val)) {
                                                if (val.length() > 50) {
                                                    entry.set(yem_erpfiledformid, val.substring(0, 39));
                                                } else {
                                                    entry.set(yem_erpfiledformid, val);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }else if(isExist){ //更新
                            subordinate.clear();//清空
                            // 获取到json上面的单据体
                            JSONArray detailList = realJson.getJSONArray(fatherJsonBS);//json（父级json）
                            if (detailList != null && detailList.size() > 0) {
                                JSONObject jsonObject = detailList.getJSONObject(index);//获取对应父分录哪一行的json数据
                                // 从json中获取每一层单据体数据
                                JSONArray jsonArray = jsonObject.getJSONArray(yem_jsonformid);//子jssonA 数据
                                for (Object object : jsonArray) {
                                    JSONObject sonRowJsonObj = (JSONObject) object;
                                    DynamicObject entry = subordinate.addNew();
                                    // 遍历实体字段集合
                                    for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
                                        DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
                                        String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");//ERP字段标识
                                        String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");//字段类型
                                        String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");//json字段标识
                                        String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");//默认值
                                        String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");//定义基础数据唯一标识
                                        String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");//字段类型名称
                                        String val = "";
                                        //优先判断是否有默认值，有默认值的情况不需要配置json字段标识
                                        if (StringUtils.isNotEmpty(yem_defaultvalue)) {
                                            val = yem_defaultvalue;
                                        } else {
                                            if (sonRowJsonObj.containsKey(yem_jsonfieldid)) {//判断jsom中之后包含配置的json标识
                                                val = sonRowJsonObj.getString(yem_jsonfieldid);
                                            }
                                        }
                                        if ("basedata".equals(yem_filedtype)) {
                                            entry.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
                                        } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {
                                            if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                                            } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                                            } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                                                entry.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                                            }
                                        } else if ("number".equals(yem_filedtype)) {
                                            entry.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                                        } else { //文本类型
                                            if (StringUtils.isNotEmpty(val)) {
                                                if (val.length() > 50) {
                                                    entry.set(yem_erpfiledformid, val.substring(0, 39));
                                                } else {
                                                    entry.set(yem_erpfiledformid, val);
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }
        }
        // 保存
        OperationResult operationResult = OperationServiceHelper.executeOperate("save", entityName, new DynamicObject[]{bill},
                OperateOption.create());
        boolean success = operationResult.isSuccess();
        return bill;
    }   //***

    /**
     * 根据基础资料的编码 和表名 去确定一条基础资料单据
     * 根据编码/名称查询基础资料
     *
     * @param yem_filedtypename   字段类型名称 就是基础使用的表名
     * @param yem_identifierbasic 定义基础数据唯一标识（number）
     * @param filterVal           json里面获取的值
     * @return obj
     */
    public static DynamicObject getObjDynamicObject(String yem_filedtypename, String yem_identifierbasic, String filterVal) {

        DynamicObject obj = null;
        if (StringUtils.isNotEmpty(yem_filedtypename) && StringUtils.isNotEmpty(filterVal)) {
            // munber =
            QFilter filter = new QFilter(yem_identifierbasic, QCP.equals, filterVal);
            obj = BusinessDataServiceHelper.loadSingle(yem_filedtypename, "id,name,number", new QFilter[]{filter});
        }
        return obj;
    }

    public static boolean CheckFormat(String str) {
        boolean falg = false;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = formatter.parse(str);
            falg = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return falg;
    }


    /**
     * 将动态对象转换为指定格式json
     *
     * @Param dynamicObject对象
     * @Param transformWay 转化类型
     */
    public static JSONObject dataToJson(DynamicObject dynamicObject) {
        String invoiceTypeKey = "";  //发票类型 json标识
        String invoiceTypeValue = "";  //发票类型值

        // 获取单据标识
        String name = dynamicObject.getDynamicObjectType().getName();

        // 从数据库中查询（根据单据标识的munber）和 转换方式
        QFilter qFilter1 = new QFilter("yem_formid.number", QCP.equals, name);
        QFilter qFilter2 = new QFilter("yem_transformway", QCP.equals, "A"); //动态对象转换为json
        DynamicObject registerObject = BusinessDataServiceHelper.loadSingle(RegisterEntityName, "id,billno,billstatus", new QFilter[]{qFilter1, qFilter2});
        if (registerObject == null) {
            return null;
        }
        // 创建初始json
        JSONObject jsonObject = new JSONObject();
        // 添加第一层 data
        JSONObject dataOne = new JSONObject();
        jsonObject.put("data", dataOne);

        // 添加第二层 data
        JSONObject dataTwo = new JSONObject();
        dataOne.put("data", dataTwo);

        // 查询出所有数据
        registerObject = BusinessDataServiceHelper.loadSingle(registerObject.getPkValue(), RegisterEntityName);

        // 获取 实体容器单据体（左边的）,并遍历
        DynamicObjectCollection entityContainer = registerObject.getDynamicObjectCollection("yem_entitycontainer");

        JSONObject valueObject = null; //存储数据的那一层
        // 遍历实体容器
        for (DynamicObject object : entityContainer) {
            // 获取单据体中每一行实体类型（单据头，单据体什么的）
            String yem_entitytype = object.getString("yem_entitytype");//实体类型
            // 获取单据体中每一行容器标识
            String yem_entityformid = object.getString("yem_entityformid");//容器标识
            // 获取单据体中每一行json标识 和容器标识 一一对应
            String yem_jsonformid = object.getString("yem_jsonformid");//json标识
            //  json标识外面的一层
            String yem_entryformid = object.getString("yem_entryformid");//分录标识
            // 获取整个实体字段集合
            DynamicObjectCollection entityFieldList = object.getDynamicObjectCollection("yem_entityfieldcol");
            if (StringUtils.isEmpty(yem_jsonformid)) {
                continue;
            }
            if (yem_entitytype.equals("A")) { //单据头
                // 添加第三层 imc_eoinvoice
                JSONArray eoinvoiceJSonArray = new JSONArray();
                dataTwo.put(yem_jsonformid, eoinvoiceJSonArray);
                // 给imc_eoinvoice添加的数据
                valueObject = new JSONObject();
                eoinvoiceJSonArray.add(valueObject);

                for (DynamicObject entityField : entityFieldList) {
                    //ERP字段标识
                    String fieldIdentification = entityField.getString("yem_erpfiledformid");
                    //  字段类型 数字类型是 munber String是text 基础资料是basedata
                    String filedType = entityField.getString("yem_filedtype");
                    //json字段标识
                    String JsonName = entityField.getString("yem_jsonfieldid");
                    //默认值（dataToJson方法不使用）
                    String defaultValue = entityField.getString("yem_defaultvalue");

                    // json里面的数据 需要这个编码去数据库中查询 定义基础数据唯一标识 一般都是 ，，munber
                    String yem_identifierbasic = entityField.getString("yem_identifierbasic");
                    // 字段类型名称 就是基础资料的使用的表名
                    String entieyDataName = entityField.getString("yem_filedtypename");
                    String val = "";

                    if ("basedata".equals(filedType)) {
                        //如果字段是对象类型的值，查询出对应的 定义基础数据唯一标识（一般都是munber），存入json
                        if (StringUtils.isNotEmpty(JsonName) && StringUtils.isNotEmpty(yem_identifierbasic)) { //判断单据注册表上的json标识不为空
                            if (fieldIdentification.equals("yem_invoice_type")) { //如果是发票类型字段的话放到最外两层json之间
                                DynamicObject dynamicObject1 = dynamicObject.getDynamicObject(fieldIdentification);
                                if (dynamicObject1 != null) {
                                    invoiceTypeKey = JsonName;
                                    invoiceTypeValue = dynamicObject1.getString(yem_identifierbasic);
                                }
                            } else { //不是 发票类型 字段
                                DynamicObject dynamicObject1 = dynamicObject.getDynamicObject(fieldIdentification);
                                if (dynamicObject1 != null) {
                                    String munber = dynamicObject1.getString(yem_identifierbasic);
                                    valueObject.put(JsonName, munber);
                                }
                            }
                        }
                    } else if ("datetime".equals(filedType) || "date".equals(filedType)) {//字段类型为时间的
                        if (StringUtils.isNotEmpty(JsonName)) { //判断单据注册表上的json标识不为空
                            Date date = dynamicObject.getDate(fieldIdentification);
                            if (date != null) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                String strDate = sdf.format(date);
                                valueObject.put(JsonName, strDate);
                            }
                        }
                    } else if ("number".equals(filedType)) { //字段类型为数字类型的
                        if (StringUtils.isNotEmpty(JsonName)) {
                            BigDecimal bigDecimal = dynamicObject.getBigDecimal(fieldIdentification);
                            valueObject.put(JsonName, bigDecimal);
                        }
                    } else if ("user".equals(filedType)) { //修改人审核人创建人什么的
                        DynamicObject userDynamOBJ = dynamicObject.getDynamicObject(fieldIdentification);
                        if (userDynamOBJ != null) {
                            String number = userDynamOBJ.getString("number");
                            valueObject.put(JsonName, number);
                        } else {
                            valueObject.put(JsonName, null);
                        }
                    } else { //否则就是文本类型的，直接从对象中获取到
                        if (StringUtils.isNotEmpty(JsonName)) { //判断单据注册表上的json标识不为空
                            String value = dynamicObject.getString(fieldIdentification);
                            valueObject.put(JsonName, value);
                        }
                    }
                }
            } else if (yem_entitytype.equals("B")) { //单据体
                JSONArray detailListJson = new JSONArray(); // 存储单据体的
                valueObject.put(yem_jsonformid, detailListJson);

                // 遍历 数据库的单据体
                DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection(yem_entityformid);
                for (DynamicObject dynamicObj : dynamicObjectCollection) { //每一行就是单据体的一行
                    JSONObject jsonDJT = new JSONObject(); //没循环一次，创建一个存入数据的json对象

                    // 遍历实体容器标识的单据体（实体字段集合），每一行就是数据库单据体的一个字段
                    for (DynamicObject entityField : entityFieldList) {
                        //ERP字段标识
                        String fieldIdentification = entityField.getString("yem_erpfiledformid");
                        //  字段类型 数字类型是 munber String是text 基础资料是basedata
                        String filedType = entityField.getString("yem_filedtype");
                        //json字段标识
                        String JsonName = entityField.getString("yem_jsonfieldid");
                        //默认值
                        String defaultValue = entityField.getString("yem_defaultvalue");
                        // json里面的数据 需要这个编码去数据库中查询 定义基础数据唯一标识 一般都是 ，，munber
                        String yem_identifierbasic = entityField.getString("yem_identifierbasic");
                        // 字段类型名称 就是基础资料的使用的表名
                        String entieyDataName = entityField.getString("yem_filedtypename");
                        String val = "";

                        if ("basedata".equals(filedType)) {
                            //如果字段是对象类型的值，查询出对应的 定义基础数据唯一标识（一般都是munber），存入json
                            if (StringUtils.isNotEmpty(JsonName) && StringUtils.isNotEmpty(yem_identifierbasic)) { //判断单据注册表上的json标识不为空
                                DynamicObject dynamicObject1 = dynamicObj.getDynamicObject(fieldIdentification);
                                if (dynamicObject1 != null) {
                                    String munber = dynamicObject1.getString(yem_identifierbasic);
                                    jsonDJT.put(JsonName, munber);
                                }
                            }
                        } else if ("datetime".equals(filedType) || "date".equals(filedType)) {//字段类型为时间的
                            if (StringUtils.isNotEmpty(JsonName)) { //判断单据注册表上的json标识不为空
                                Date date = dynamicObj.getDate(fieldIdentification);
                                if (date != null) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                    String strDate = sdf.format(date);
                                    jsonDJT.put(JsonName, strDate);
                                }
                            }
                        } else if ("number".equals(filedType)) { //字段类型为数字类型的
                            if (StringUtils.isNotEmpty(JsonName)) {
                                BigDecimal bigDecimal = dynamicObj.getBigDecimal(fieldIdentification);
                                jsonDJT.put(JsonName, bigDecimal);
                            }
                        } else if ("user".equals(filedType)) { // 修改人审核人创建人什么的
                            DynamicObject userDynamOBJ = dynamicObject.getDynamicObject(fieldIdentification);
                            if (userDynamOBJ != null) {
                                String number = userDynamOBJ.getString("number");
                                valueObject.put(JsonName, number);
                            } else {
                                valueObject.put(JsonName, null);
                            }
                        } else { //否则就是文本类型的，直接从对象中获取到
                            if (StringUtils.isNotEmpty(JsonName)) { //判断单据注册表上的json标识不为空
                                String value = dynamicObj.getString(fieldIdentification);
                                jsonDJT.put(JsonName, value);
                            }
                        }
                    }
                    // 添加数据
                    detailListJson.add(jsonDJT);
                }
            }
        }
        dataOne.put(invoiceTypeKey, invoiceTypeValue);//发票类型，特殊字段放到两层data之间
        return jsonObject;
    }

    /**
     * 发票归集数据插入底表
     *
     * @param json
     * @return
     */
    public static ArrayList<DynamicObject> collectionJsonToData(JSONObject json) {
        String serialNo = "";//流水号
        if (json.containsKey("serialNo")) {
            serialNo = json.getString("serialNo");
        }
        JSONObject dataInitial = json.getJSONObject("data");
        JSONArray recordsArrJson = dataInitial.getJSONArray("records");//存储数据的集合
        if (recordsArrJson.size() == 0) {
            return null;
        }

        ArrayList<DynamicObject> jsonArrayList = new ArrayList<DynamicObject>(recordsArrJson.size());
        for (Object o : recordsArrJson) {
            //开始拼装
            JSONObject jsonObj = (JSONObject) o;
            //获取表名
            String invoiceType = jsonObj.getString("invoiceType");//发票类型
            String entityName = "";
            switch (invoiceType) {
                case "01": //增值税专用发票
                case "08": //增值税专用发票（电子）
                    entityName = "yem_imc_esinvoice"; //增值税专用发票表名
                    break;
                case "04": //增值税普通发票
                case "10": //增值税普通发票（电子）
                case "11": //增值税普通发票（卷票）
                    entityName = "yem_imc_eoinvoice";  //增值税普通发票
                    break;
                case "09": //全电发票（增值税专用发票）
                case "90": //全电发票（普通发票）
                    entityName = "yem_imc_electric"; //全电发票
                    break;
                case "14": //道路通行费电子普通发票
                    //待添加......
                    break;
                default:
                    break;
            }
            JSONObject dataInside = new JSONObject();
            dataInside.put("invoiceVO", jsonObj);
            JSONArray data = new JSONArray();
            data.add(dataInside);

            JSONObject outermostLayerJson = new JSONObject();//源生json
            outermostLayerJson.put("data", data);
            outermostLayerJson.put("serialNo", serialNo);

            DynamicObject newData = jsonToData(entityName, outermostLayerJson, "B", "发票归集");
            jsonArrayList.add(newData);
        }
        return jsonArrayList;
    }

    /**
     * 循环实体字段分录赋值处理方式
     * @param yem_entityfieldcol_s 实体字段分录
     * @param realJson             josn对象
     * @param bill                 要插入的对象
     */
    public static void traversalAssignment(DynamicObjectCollection yem_entityfieldcol_s, JSONObject realJson, DynamicObject bill) {
        for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
            DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
            //ERP字段标识
            String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");
            // 字段类型
            String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");
            // json字段标识
            String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");
            //默认值
            String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");
            //定义基础数据唯一标识
            String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");
            // 字段类型名称-基础资料的的表名
            String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");
            String val = "";
            //  优先判断是否有默认值
            if (yem.base.common.utils.StringUtils.isNotEmpty(yem_defaultvalue)) {
                val = yem_defaultvalue;
            } else {
                if (realJson.containsKey(yem_jsonfieldid)) {
                    val = realJson.getString(yem_jsonfieldid);
                }
            }
            if ("basedata".equals(yem_filedtype)) {
                bill.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
            } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {//字段类型为时间的
                if (yem_erpfiledformid.equals("auditdate")) { //审核时间
                    bill.set(yem_erpfiledformid, new Date());
                }
                if (yem.base.common.utils.StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                } else if (yem.base.common.utils.StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                } else if (yem.base.common.utils.StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                } else if (yem.base.common.utils.StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                }
            } else if ("number".equals(yem_filedtype)) { //字段类型为数字类型的
                if (yem.base.common.utils.StringUtils.isNotEmpty(val)) {
                    bill.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                }
            } else if ("org".equals(yem_filedtype)) { //组织-默认当前登录人组织
                bill.set(yem_erpfiledformid, YEM.getCurrentOrgId());
            } else if ("user".equals(yem_filedtype)) { //人员
                if ("auditor".equals(yem_erpfiledformid) || "creator".equals(yem_erpfiledformid) || "modifier".equals(yem_erpfiledformid)) {
                    bill.set(yem_erpfiledformid, YEM.getCurrentUserId());
                }
            } else { //否则就是文本类型的，直接使用获取到的json
                if (yem.base.common.utils.StringUtils.isNotEmpty(val)) {
                    if (val.contains("{}")) {
                        bill.set(yem_erpfiledformid, null);
                    } else {
                        bill.set(yem_erpfiledformid, val);
                    }
                }
            }
        }
    }


}
