package com.kingdee.eas.custom.beisen.synchronousorg;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.function.WfEventListenerStateManager;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.bos.util.BOSObjectType;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.attachment.AttachmentFactory;
import com.kingdee.eas.base.attachment.AttachmentInfo;
import com.kingdee.eas.base.attachment.BoAttchAssoFactory;
import com.kingdee.eas.base.attachment.BoAttchAssoInfo;
import com.kingdee.eas.base.codingrule.CodingRuleManagerFactory;
import com.kingdee.eas.base.codingrule.ICodingRuleManager;
import com.kingdee.eas.base.permission.UserCollection;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.org.*;
import com.kingdee.eas.basedata.person.PersonCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.beisen.utils.Helper;
import com.kingdee.eas.custom.beisenconfig.*;
import com.kingdee.eas.custom.enumerations.ViewTypeEnum;
import com.kingdee.eas.custom.interfacelog.businessoperationlog.*;
import com.kingdee.eas.fi.arap.util.DBUtil;
import com.kingdee.eas.framework.CoreBaseCollection;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.eas.framework.ICoreBase;
import com.kingdee.eas.hr.affair.*;
import com.kingdee.eas.hr.base.*;
import com.kingdee.eas.hr.emp.PersonPhotoFactory;
import com.kingdee.eas.hr.emp.PersonPhotoInfo;
import com.kingdee.shr.attachment.AttachmentState;
import com.kingdee.shr.attachment.AttachmentTypeEnum;
import com.kingdee.shr.attachment.SHRAttachmentExtFactory;
import com.kingdee.shr.attachment.SHRAttachmentExtInfo;
import com.kingdee.shr.base.syssetting.MSFServiceFacadeFactory;
import com.kingdee.shr.base.syssetting.UIType;
import com.kingdee.shr.base.syssetting.UIViewFactory;
import com.kingdee.shr.base.syssetting.UIViewInfo;
import com.kingdee.shr.base.syssetting.app.util.XMLUtil;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.ml.SHRWebResource;
import com.kingdee.shr.base.syssetting.util.MetaDataUtil;
import com.kingdee.shr.base.syssetting.util.SysSettingUIViewUtil;
import com.kingdee.shr.base.syssetting.web.dynamic.model.FieldInfo;
import com.kingdee.shr.base.syssetting.web.dynamic.view.converter.IUIViewConverter;
import com.kingdee.shr.base.syssetting.web.dynamic.view.converter.UIViewConverterFactory;
import com.kingdee.shr.ml.MLServiceFactory;
import com.kingdee.shr.ml.ResourceType;
import com.kingdee.util.LocaleUtils;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;

import java.io.IOException;

import com.kingdee.bos.*;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;
import org.json.JSONException;

import java.lang.String;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class SynchronousEmpBillControllerBean extends AbstractSynchronousEmpBillControllerBean {
    Context context = null;
    Helper helper = null;
    private static Logger logger =
            Logger.getLogger("com.kingdee.eas.custom.beisen.synchronousorg.SynchronousEmpBillControllerBean");

    /**
     * 创建或更新组织信息并同步到外部系统的方法。
     *
     * @param ctx          上下文对象，包含系统运行时的环境信息
     * @param param        补充参数
     * @param viewConfigId 配置编码
     * @throws BOSException 执行过程中发生业务异常时抛出
     */
    @Override
    public String empBill(Context ctx, String param, String viewConfigId, String userName) throws BOSException {
        this.context = ctx;
        helper = new Helper(context);
        IObjectPK caller = context.getCaller();
        UserCollection userCollection = UserFactory.getLocalInstance(context)
                .getUserCollection("select *,person.* where id = '" + caller.toString() + "'");
        if (userCollection.size() > 0) {
            UserInfo userInfo = userCollection.get(0);
            if (userInfo.getPerson() == null) {
                userCollection = UserFactory.getLocalInstance(context)
                        .getUserCollection("select *,person.* where number = '" + userName + "'");
                if (userCollection.size() > 0) {
                    UserInfo userInfo1 = userCollection.get(0);
                    BOSUuid id = userInfo1.getId();
                    System.out.println("===userInfo======" + userInfo1.getPerson().getName());
                    context.setCaller(new ObjectUuidPK(id));
                    SHRContext shrContext = new SHRContext(null, null, null);
                    context.put("UserInfo", userInfo1);
                    shrContext.setContext(context);
                    SHRContext.setInstance(shrContext);
                }

            } else {
                SHRContext instance = SHRContext.getInstance();
                System.out.println("++++++++" + instance);
                if (instance == null) {
                    System.out.println("======================" + null);
                    SHRContext shrContext = new SHRContext(null, null, null);
                    context.put("UserInfo", userCollection.get(0));
                    shrContext.setContext(context);
                    SHRContext.setInstance(shrContext);
                }
            }
        }
        EntityViewInfo entityViewInfo = new EntityViewInfo();
        FilterInfo filterInfo = new FilterInfo();
        filterInfo.getFilterItems().add(new FilterItemInfo("isEnabled", true, CompareType.EQUALS));
        filterInfo.getFilterItems().add(new FilterItemInfo("number", viewConfigId, CompareType.EQUALS));
        entityViewInfo.setFilter(filterInfo);
        //获取北森视图配置信息
        BSViewConfigCollection bsViewConfigCollection = BSViewConfigFactory.getLocalInstance(context).getBSViewConfigCollection(entityViewInfo);
        if (bsViewConfigCollection.size() <= 0) {
            throw new RuntimeException("配置未启用或者不存在");
        }
        BSViewConfigInfo bsViewConfigInfo = bsViewConfigCollection.get(0);
        String osfParam = bsViewConfigInfo.getOsfParam();
        String osfSericeName = bsViewConfigInfo.getOsfSericeName();
        Map<String, Object> serviceParam = new HashMap<String, Object>();
        if (param != null && !param.equals("")) {
            JSONObject jsonObject = JSONObject.parseObject(osfParam);
            jsonObject.put("staffId", param);
            osfParam = jsonObject.toJSONString();
        }
        serviceParam.put("param", osfParam);
        JSONArray beiSenData = null;
        String id = "";
        SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
        selectorItemCollection.add("*");
        selectorItemCollection.add("view.*");

        Object o = null;
        try {
            o = MSFServiceFacadeFactory.getLocalInstance(context).processService(osfSericeName, serviceParam);
        } catch (EASBizException e) {
            throw new RuntimeException(e);
        }
        beiSenData = JSONArray.parseArray(o.toString());
        //查询头部视图配置 头部视图配置只能有一个
        EntityViewInfo entryHeadEntityViewInfo = new EntityViewInfo();
        FilterInfo entryHeadFilterInfo = new FilterInfo();
        entryHeadFilterInfo.getFilterItems().add(new FilterItemInfo("parent", bsViewConfigInfo.getId().toString(), CompareType.EQUALS));
        entryHeadFilterInfo.getFilterItems().add(new FilterItemInfo("boy", ViewTypeEnum.HEAD_VALUE, CompareType.EQUALS));
        entryHeadEntityViewInfo.setSelector(selectorItemCollection);
        entryHeadEntityViewInfo.setFilter(entryHeadFilterInfo);
        BSViewConfigEntryCollection headBsViewConfigEntryCollection = BSViewConfigEntryFactory
                .getLocalInstance(context).getBSViewConfigEntryCollection(entryHeadEntityViewInfo);
        if (headBsViewConfigEntryCollection.size() != 1) {
            throw new RuntimeException("头部配置有且只能有一个");
        }
        BSViewConfigEntryInfo bsViewConfigEntryInfo = headBsViewConfigEntryCollection.get(0);
        UIViewInfo view = bsViewConfigEntryInfo.getView();
        String file = bsViewConfigEntryInfo.getFile();
        IOperateLog localInstance = OperateLogFactory.getLocalInstance(ctx);
        for (int i = 0; i < beiSenData.size(); i++) {
            JSONObject jsonObject1 = beiSenData.getJSONObject(i);
            JSONArray fileArray = jsonObject1.getJSONArray(file);
            boolean isCreateData = bsViewConfigEntryInfo.isIsCreateData();
            String headId = null;
            OperateLogInfo operateLogInfo = new OperateLogInfo();
            if (isCreateData) {
                String headDataEntry = bsViewConfigEntryInfo.getHeadDataEntry();
                if (headDataEntry != null && !headDataEntry.equals("")) {
                    Class objectValueClass = null;
                    try {
                        objectValueClass = MetaDataUtil.getObjectValueClass(headDataEntry);
                    } catch (ShrWebBizException e) {
                        System.out.println("获取头部元数据失败");
                        e.printStackTrace();
                        continue;
                    }
                    // 创建对应的实体对象
                    CoreBaseInfo coreBaseInfo = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass, headDataEntry);
                    EntityObjectInfo entityObjectInfo = MetaDataUtil.getEntityObjectByBosType(coreBaseInfo.getBOSType());
                    operateLogInfo.setBusinessName(entityObjectInfo.getAlias());
                    operateLogInfo.setBosType(coreBaseInfo.getBOSType().toString());
                    OperateLogEntryCollection entrys = operateLogInfo.getEntrys();
                    if (coreBaseInfo instanceof EmpEnrollBizBillInfo) {
                        System.out.println("针对入职单处理");
                        String string = jsonObject1.getJSONObject("staffInfos").getString("id");
                        JSONArray entryRecord = jsonObject1.getJSONArray("entryRecord");
                        String entryRecordId = "";
                        if (entryRecord.size()>1){
                            JSONArray datas = paixu(entryRecord, "entryDate");
                            System.out.println("排序后"+datas);
                            entryRecordId = datas.getJSONObject(0).getString("id");
                        }else {
                            entryRecordId = entryRecord.getJSONObject(0).getString("id");
                        }

                        EmpEnrollBizBillCollection collection = EmpEnrollBizBillFactory.getLocalInstance(context)
                                .getEmpEnrollBizBillCollection("select *,entrys.*,entrys.person.* where entryRecordId='" + entryRecordId + "'");
                        if (collection.size() > 0) {
                            System.out.println("=======入职单已存在=============");//0044610
                            OperateLogEntryInfo operateLogEntryInfo = new OperateLogEntryInfo();
                            operateLogEntryInfo.setErrorInfo("入职单已存在");
                            EmpEnrollBizBillEntryCollection entrys1 = collection.get(0).getEntrys();
                            String empName = entrys1.get(0).getEmpName();
                            operateLogInfo.setName(empName);
                            entrys.add(operateLogEntryInfo);
                            try {
                                localInstance.save(operateLogInfo);
                            } catch (EASBizException e) {
                                e.printStackTrace();
                                System.out.println(e.getMessage());
                            }
                            continue;
                        }else {
                            EmpEnrollBizBillCollection collection1 = EmpEnrollBizBillFactory.getLocalInstance(context)
                                    .getEmpEnrollBizBillCollection("select *,entrys.*,entrys.person.* where beisenid='" + string + "'");
                            if (collection1.size() > 0) {
                                System.out.println("==========清空beisenid=========");
                                String sql = "update T_HR_EmpEnrollBizBill set cfbeisenid = null where cfbeisenid = '"+string+"'";
                                DBUtil.execute(ctx,sql);
                            }
                        }

                    }
                }
                try {
                    headId = headProcessing(view, jsonObject1, fileArray, file);
                    //operateLogInfo = new OperateLogInfo();
                    operateLogInfo.setBusinessId(headId);
                    OperateLogEntryCollection entrys = operateLogInfo.getEntrys();
                    OperateLogEntryInfo operateLogEntryInfo = new OperateLogEntryInfo();
                    String boy = jsonObject1.toJSONString();
                    if (boy.length()>500){
                        boy = boy.substring(0, 500);
                    }
                    operateLogEntryInfo.setErrorInfo(boy);
                    entrys.add(operateLogEntryInfo);
                    try {
                        localInstance.save(operateLogInfo);
                    } catch (EASBizException e) {
                        e.printStackTrace();
                        System.out.println(e.getMessage());
                    }
                } catch (Exception e) {
                    //operateLogInfo.setBusinessId(headId);
                    OperateLogEntryCollection entrys = operateLogInfo.getEntrys();
                    OperateLogEntryInfo operateLogEntryInfo = new OperateLogEntryInfo();
                    String f = e.getMessage();
                    if (f!=null&&f.length()>500){
                        f = f.substring(0, 500);
                    }
                    operateLogInfo.setName(f);
                    operateLogEntryInfo.setErrorInfo("整理保存头部数据失败！！！！" + f);
                    entrys.add(operateLogEntryInfo);
                    System.out.println(e.getMessage());
                    System.out.println("整理保存头部数据失败！！！！");
                    try {
                        localInstance.save(operateLogInfo);
                    } catch (EASBizException ex) {
                        ex.printStackTrace();
                    }
                    e.printStackTrace();
                    continue;
                }
                id += headId + ",";
            } else {
                //operateLogInfo = new OperateLogInfo();
                String headDataEntry = bsViewConfigEntryInfo.getHeadDataEntry();
                Class objectValueClass = null;
                try {
                    objectValueClass = MetaDataUtil.getObjectValueClass(headDataEntry);
                } catch (ShrWebBizException e) {
                    System.out.println("获取元数据失败！！！");
                    e.printStackTrace();
                    continue;
                }
                operateLogInfo.setBusinessId(headId);
                OperateLogEntryCollection entrys1 = operateLogInfo.getEntrys();
                OperateLogEntryInfo operateLogEntryInfo = new OperateLogEntryInfo();

                // 创建对应的实体对象
                CoreBaseInfo coreBaseInfo = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass, headDataEntry);
                if (coreBaseInfo instanceof EmpEnrollBizBillInfo) {
                    System.out.println("针对入职单处理");
                    String string = jsonObject1.getJSONObject("staffInfos").getString("id");
                    EmpEnrollBizBillCollection collection = EmpEnrollBizBillFactory.getLocalInstance(context)
                            .getEmpEnrollBizBillCollection("select *,entrys.*,entrys.person.* where beisenid='" + string + "'");
                    if (collection.size() > 0) {
                        EmpEnrollBizBillInfo empEnrollBizBillInfo = collection.get(0);
                        EmpEnrollBizBillEntryCollection entrys = empEnrollBizBillInfo.getEntrys();
                        if (entrys.size() > 0) {
                            PersonInfo person = entrys.get(0).getPerson();
                            if (view != null) {
                                System.out.println("======修改信息=========");
                                try {
                                    headProcessing(view, jsonObject1, person, fileArray, file);
                                } catch (Exception e) {
                                    String f = e.getMessage();
                                    if (f!=null&&f.length()>500){
                                        f = f.substring(0, 500);
                                    }
                                    operateLogEntryInfo.setErrorInfo("获取头部信息失败！！！！" + f);
                                    entrys1.add(operateLogEntryInfo);
                                    try {
                                        localInstance.save(operateLogInfo);
                                    } catch (EASBizException ex) {

                                    }

                                    System.out.println("获取头部信息失败");
                                    e.printStackTrace();
                                    continue;
                                }
                            }
                            headId = person.getId().toString();
                            id += headId + ",";
                        }
                    }
                } else {
                    //其他处理 还没想好怎么做 暂时满足需求 后续有想法在填入
                }
            }
            if (headId == null) {
                continue;
            }

            EntityViewInfo entryBoyEntityViewInfo = new EntityViewInfo();
            FilterInfo entryBoyFilterInfo = new FilterInfo();
            entryBoyFilterInfo.getFilterItems().add(new FilterItemInfo("parent", bsViewConfigInfo.getId().toString(), CompareType.EQUALS));
            entryBoyFilterInfo.getFilterItems().add(new FilterItemInfo("boy", ViewTypeEnum.BOY_VALUE, CompareType.EQUALS));
            entryBoyEntityViewInfo.setSelector(selectorItemCollection);
            entryBoyEntityViewInfo.setFilter(entryBoyFilterInfo);
            BSViewConfigEntryCollection boyBsViewConfigEntryCollection = BSViewConfigEntryFactory
                    .getLocalInstance(context).getBSViewConfigEntryCollection(entryBoyEntityViewInfo);
            for (int j = 0; j < boyBsViewConfigEntryCollection.size(); j++) {
                operateLogInfo = new OperateLogInfo();
                //operateLogInfo.setBusinessId(headId);
                OperateLogEntryCollection entrys1 = operateLogInfo.getEntrys();
                OperateLogEntryInfo operateLogEntryInfo = new OperateLogEntryInfo();

                BSViewConfigEntryInfo boybsViewConfigEntryInfo = boyBsViewConfigEntryCollection.get(j);
                UIViewInfo view1 = boybsViewConfigEntryInfo.getView();
                String beiSenData1 = boybsViewConfigEntryInfo.getBeiSenData();
                UIType type = view1.getType();
                operateLogInfo.setBusinessName(view1.getName());
                boolean isCreateData1 = boybsViewConfigEntryInfo.isIsCreateData();
                try {
                    BOSUuid read = BOSUuid.read(headId);
                    ICoreBase bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, read.getType()));
                    CoreBaseInfo coreBaseInfo = bosObject.getValue(new ObjectUuidPK(read));
                    operateLogInfo.setName(coreBaseInfo.getString("name"));
                    operateLogInfo.setNumber(coreBaseInfo.getString("number"));
                    if (type.getValue().equals("list")) {
                        JSONArray jsonArray = jsonObject1.getJSONArray(beiSenData1);
                        if (jsonArray==null||jsonArray.size()==0){
                            operateLogEntryInfo.setErrorInfo("北森数据不存在"+beiSenData1);
                        }else {
                            boyProcessing(view1, headId, jsonArray, null, "fileInfos", beiSenData1);
                            String boy = jsonObject1.getJSONArray(beiSenData1).toJSONString();
                            if (boy.length()>500){
                                boy = boy.substring(0, 500);
                            }
                            operateLogEntryInfo.setErrorInfo(boy);
                        }
                    } else {
                        JSONObject jsonObject11 = jsonObject1.getJSONObject(beiSenData1);
                        if (jsonObject11==null||jsonObject11.size()==0){
                            operateLogEntryInfo.setErrorInfo("北森数据不存在"+beiSenData1);
                        }else {
                            boyProcessing(view1, isCreateData1, headId,jsonObject11, null, "fileInfos", beiSenData1);
                            String boy =jsonObject1.getJSONObject(beiSenData1).toJSONString();
                            if (boy.length()>500){
                                boy = boy.substring(0, 500);
                            }
                            operateLogEntryInfo.setErrorInfo(boy);
                        }

                    }
                    entrys1.add(operateLogEntryInfo);
                    try {
                        localInstance.save(operateLogInfo);
                    } catch (EASBizException ex) {
                        ex.printStackTrace();
                    }

                } catch (Exception e) {
                    System.out.println("整理报错主题信息失败！！！");
                    e.printStackTrace();
                    String f = e.getMessage();
                    if (f!=null&&f.length()>500){
                        f = f.substring(0, 500);
                    }
                    operateLogEntryInfo.setErrorInfo("获取头部信息失败！！！！" + f);
                    entrys1.add(operateLogEntryInfo);
                    try {
                        localInstance.save(operateLogInfo);
                    } catch (EASBizException ex) {

                    }
                    continue;
                }
            }

        }
        return id;
    }


    /**
     * 处理表单类型的主体信息
     *
     * @param id         关联的 ID
     * @param jsonObject 主体信息的 JSON 对象
     * @param fileJSON   文件信息的 JSON 数组
     * @return 保存后的对象主键
     * @throws JSONException   JSON 处理异常
     * @throws SHRWebException SHR 网页异常
     * @throws BOSException    BOS 异常
     * @throws EASBizException EAS 业务异常
     * @throws ParseException  解析异常
     * @throws IOException     输入输出异常
     */
    public String boyProcessing(UIViewInfo uiViewInfo, boolean isCreateData1, String id, JSONObject jsonObject, JSONArray fileJSON, String fileName, String beiSenData1)
            throws JSONException, SHRWebException, BOSException, EASBizException, ParseException, IOException {
        // 根据 UI 视图的主键生成动态 UI 视图信息
        com.kingdee.shr.base.syssetting.web.dynamic.model.UIViewInfo uiViewInfo1 =
                generateUIView(context, uiViewInfo.getUipk());
        // 获取实体名称
        String entityName = uiViewInfo1.getEntityName();
        // 获取字段列表
        List<FieldInfo> fields = uiViewInfo1.getFields();
        // 根据实体名称获取对应的对象值类

        Class objectValueClass = MetaDataUtil.getObjectValueClass(entityName);
        // 创建对应的实体对象
        CoreBaseInfo coreBaseInfo = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass, entityName);
        // 处理字段信息
        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put(beiSenData1, jsonObject);
        // 创建对应的业务对象
        ICoreBase bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, coreBaseInfo.getBOSType()));
        // 获取关联字段
        String relateField = uiViewInfo1.getRelatedField();
        System.out.println("==============判断是否需要同步====="+!isCreateData1+"============"+isCreateData1);
        if (!isCreateData1) {
            System.out.println("=============查询不需要同步数据============" + "where " + relateField + " = '" + id + "'");
            CoreBaseCollection collection = bosObject.getCollection("where " + relateField + " = '" + id + "'");
            if (collection.size() > 0) {
                coreBaseInfo = collection.get(0);
                System.out.println("=========同步修改数据ID=======" + coreBaseInfo.getId());
            }

        }
        JSONArray jsonArray = this.fieldProcessing(fields, coreBaseInfo, jsonObject2, fileName);

        // 根据 ID 获取对应的实体对象信息
        EntityObjectInfo entityObject = MetaDataUtil.getEntityObject(id);
        // 获取实体对象的全名称
        String fullName = entityObject.getFullName();
        // 根据全名称获取对应的对象值类
        Class objectValueClass1 = MetaDataUtil.getObjectValueClass(fullName);
        // 创建对应的实体对象
        CoreBaseInfo coreBaseInfo1 = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass1, fullName);
        // 设置实体对象的 ID
        coreBaseInfo1.setId(BOSUuid.read(id));
        // 将关联的实体对象设置到当前实体对象中
        coreBaseInfo.put(relateField, coreBaseInfo1);
        IObjectPK save = null;
        // 保存实体对象
        if (coreBaseInfo instanceof EmpEnrollBizBillInfo) {
            System.out.println("========submit===========");
            coreBaseInfo.put("billState", HRBillStateEnum.SUBMITED);
            coreBaseInfo.put("approveType", ApproveTypeEnum.WORKFLOW);
            coreBaseInfo.setExtendedProperty("isAddNew", "isAddNew");
            boolean isOpen = WfEventListenerStateManager.getInstance().isEnable();//开启工作流事务
            System.out.println("工作流事务：" + isOpen);
            if (!isOpen) {
                WfEventListenerStateManager.getInstance().enableEventListener();
            }
            save = bosObject.submit(coreBaseInfo); //如果本来工作流服务状态不是关的，将它关掉
            if (!isOpen) {
                WfEventListenerStateManager.getInstance().disableEventListener();
            }
            System.out.println("工作流事务：" + isOpen);
        } else {
            System.out.println("========save===========");
            save = bosObject.save(coreBaseInfo);

        }
        // 处理文件信息
        fileProcessor(save.toString(), jsonArray);

        if (fileJSON != null) {
            // 获取文件信息的第一个 JSON 对象
            JSONObject jsonObject1 = fileJSON.getJSONObject(0);
            if (!save.toString().equals("")) {
                // 遍历字段列表
                for (int i = 0; i < fields.size(); i++) {
                    // 获取单个字段信息
                    FieldInfo fieldInfo = fields.get(i);
                    // 获取字段的别名
                    String alias = fieldInfo.getAlias();//CertificateNu
                    // 获取字段的名称
                    String name = fieldInfo.getName();//idCardNO
                    if (!name.equals("attachments")) {
                        continue;
                    }
                    // 分割字段别名
                    String[] split = alias.split("#");
                    // 获取字段的属性
                    Map<String, String> attributes = fieldInfo.getAttributes();
                    // 获取数据的 UI 主键
                    String dataUipk = attributes.get("data-uipk");
                    // 获取文件信息
                    JSONObject data = jsonObject1.getJSONObject(split[1]);
                    if (data != null) {
                        // 获取下载链接
                        String downloadUrl = data.getString("downloadUrl");
                        // 分割下载链接
                        String[] split1 = downloadUrl.split(",");
                        // 获取文件名
                        String text = data.getString("text");
                        // 分割文件名
                        String[] split2 = text.split(",");
                        for (int k = 0; k < split1.length; k++) {
                            byte[] dataImg = new byte[0];
                            // 拼接完整的下载链接
                            String URL = "http:" + split1[k];
                            System.out.println("===========" + URL + "==========");
                            // 从网络下载文件数据
                            dataImg = helper.getBytesByNetURL(URL);
                            // 插入人员附件信息
                            insertPersonAttachment(split2[k], dataUipk, save.toString(), dataImg);
                        }
                    }

                }
            }
        }
        // 返回保存后的对象主键
        return save.toString();
    }

    /**
     * 处理列表类型的主体信息
     *
     * @param id        关联的 ID
     * @param jsonArray 主体信息的 JSON 数组
     * @param fileJSON  文件信息的 JSON 数组
     * @return 保存后的对象主键
     * @throws JSONException   JSON 处理异常
     * @throws SHRWebException SHR 网页异常
     * @throws BOSException    BOS 异常
     * @throws EASBizException EAS 业务异常
     * @throws ParseException  解析异常
     * @throws IOException     输入输出异常
     */
    public String boyProcessing(UIViewInfo uiViewInfo, String id, JSONArray jsonArray, JSONArray fileJSON, String fileName, String beiSenData1)
            throws JSONException, SHRWebException, BOSException, EASBizException, ParseException, IOException {
        // 根据 UI 视图的主键生成动态 UI 视图信息
        com.kingdee.shr.base.syssetting.web.dynamic.model.UIViewInfo uiViewInfo1 =
                generateUIView(context, uiViewInfo.getUipk());

        String fileId = "";
        // 获取实体名称
        String entityName = uiViewInfo1.getEntityName();
        // 获取字段列表
        List<FieldInfo> fields = uiViewInfo1.getFields();
        // 获取关联字段
        String relateField = uiViewInfo1.getRelatedField();

        // 根据 ID 获取对应的实体对象信息
        EntityObjectInfo entityObject = MetaDataUtil.getEntityObject(id);
        // 获取实体对象的全名称
        String fullName = entityObject.getFullName();
        // 根据全名称获取对应的对象值类
        Class objectValueClass1 = MetaDataUtil.getObjectValueClass(fullName);
        // 创建对应的实体对象
        CoreBaseInfo coreBaseInfo1 = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass1, fullName);
        // 设置实体对象的 ID
        coreBaseInfo1.setId(BOSUuid.read(id));
        // 获取排序方法
        String sorterMethod = uiViewInfo1.getOrderBy();
        // 遍历主体信息的 JSON 数组
        for (int i = 0; i < jsonArray.size(); i++) {
            // 根据实体名称获取对应的对象值类
            Class objectValueClass = MetaDataUtil.getObjectValueClass(entityName);
            // 创建对应的实体对象
            CoreBaseInfo coreBaseInfo = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass, entityName);
            // 处理字段信息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put(beiSenData1, jsonArray.getJSONObject(i));
            JSONArray jsonArray1 = this.fieldProcessing(fields, coreBaseInfo, jsonObject, fileName);
            // 创建对应的业务对象
            ICoreBase bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, coreBaseInfo.getBOSType()));
            // 将关联的实体对象设置到当前实体对象中
            coreBaseInfo.put(relateField, coreBaseInfo1);
            // 设置是否最高的标志
            coreBaseInfo.put("IsHighest", "1");
            // 设置是否单个的标志
            coreBaseInfo.put("isSingle", "1");
            IObjectPK save = null;
            // 保存实体对象
            if (coreBaseInfo instanceof EmpEnrollBizBillInfo) {
                System.out.println("=======submit=======");
                coreBaseInfo.put("billState", HRBillStateEnum.SUBMITED);
                coreBaseInfo.put("approveType", ApproveTypeEnum.WORKFLOW);
                coreBaseInfo.setExtendedProperty("isAddNew", "isAddNew");
                boolean isOpen = WfEventListenerStateManager.getInstance().isEnable();//开启工作流事务
                System.out.println("工作流事务：" + isOpen);
                if (!isOpen) {
                    WfEventListenerStateManager.getInstance().enableEventListener();
                }
                save = bosObject.submit(coreBaseInfo); //如果本来工作流服务状态不是关的，将它关掉
                if (!isOpen) {
                    WfEventListenerStateManager.getInstance().disableEventListener();
                }
                System.out.println("工作流事务：" + isOpen);
            } else {
                System.out.println("=======save=======");
                save = bosObject.save(coreBaseInfo);

            }

            if (sorterMethod != null && !sorterMethod.equals("")) {
                // 根据关联字段和排序方法查询实体对象集合
                CoreBaseCollection collection = bosObject.getCollection(" where " + relateField + " = '" + id + "' order by " + sorterMethod);
                if (collection.size() > 1) {
                    // 获取第一个实体对象
                    CoreBaseInfo coreBaseInfo2 = collection.get(0);
                    // 设置是否最高的标志
                    coreBaseInfo2.put("IsHighest", "1");
                    // 设置是否单个的标志
                    coreBaseInfo2.put("isSingle", "1");
                    // 保存实体对象
                    IObjectPK save1 = bosObject.save(coreBaseInfo2);
                    // 获取保存后的对象主键
                    fileId = save1.toString();
                    for (int j = 1; j < collection.size(); j++) {
                        // 获取其他实体对象
                        CoreBaseInfo coreBaseInfo3 = collection.get(j);
                        // 设置是否最高的标志
                        coreBaseInfo3.put("IsHighest", "0");
                        // 设置是否单个的标志
                        coreBaseInfo3.put("isSingle", "0");
                        // 保存实体对象
                        bosObject.save(coreBaseInfo3);
                    }
                }
            }
            // 处理文件信息
            fileProcessor(save.toString(), jsonArray1);
        }
        if (fileJSON != null) {
            // 获取文件信息的第一个 JSON 对象
            JSONObject jsonObject = fileJSON.getJSONObject(0);
            if (!fileId.equals("")) {
                // 遍历字段列表
                for (int i = 0; i < fields.size(); i++) {
                    // 获取单个字段信息
                    FieldInfo fieldInfo = fields.get(i);
                    // 获取字段的别名
                    String alias = fieldInfo.getAlias();//CertificateNu
                    // 获取字段的名称
                    String name = fieldInfo.getName();//idCardNO
                    if (!name.equals("attachments")) {
                        continue;
                    }
                    // 分割字段别名
                    String[] split = alias.split("#");
                    // 获取字段的属性
                    Map<String, String> attributes = fieldInfo.getAttributes();
                    // 获取数据的 UI 主键
                    String dataUipk = attributes.get("data-uipk");
                    // 获取文件信息
                    JSONObject data = jsonObject.getJSONObject(split[1]);
                    if (data != null) {
                        // 获取下载链接
                        String downloadUrl = data.getString("downloadUrl");
                        // 分割下载链接
                        String[] split1 = downloadUrl.split(",");
                        // 获取文件名
                        String text = data.getString("text");
                        // 分割文件名
                        String[] split2 = text.split(",");
                        for (int k = 0; k < split1.length; k++) {
                            byte[] dataImg = new byte[0];
                            // 拼接完整的下载链接
                            String URL = "http:" + split1[k];
                            System.out.println("===========" + URL + "==========");
                            // 从网络下载文件数据
                            dataImg = helper.getBytesByNetURL(URL);
                            // 插入人员附件信息
                            insertPersonAttachment(split2[k], dataUipk, fileId, dataImg);
                        }
                    }

                }
            }
        }


        return null;
    }

    /**
     * 处理字段信息
     *
     * @param fields       字段列表
     * @param coreBaseInfo 实体对象
     * @param jsonObject   数据的 JSON 对象
     * @return 处理后的文件信息的 JSON 数组
     * @throws JSONException      JSON 处理异常
     * @throws ShrWebBizException SHR 网页业务异常
     * @throws BOSException       BOS 异常
     * @throws ParseException     解析异常
     */
    public JSONArray fieldProcessing(List<FieldInfo> fields, CoreBaseInfo coreBaseInfo, JSONObject jsonObject, String fileName) throws JSONException, ShrWebBizException, BOSException, ParseException {
        System.out.println("===============+" + jsonObject);
        // 用于存储处理后的文件信息的 JSON 数组
        JSONArray files = new JSONArray();
        // 用于存储单个文件信息的 JSON 对象
        JSONObject file = null;
        // 遍历字段列表
        for (int i = 0; i < fields.size(); i++) {

            // 获取单个字段信息
            FieldInfo fieldInfo = fields.get(i);
            // 获取字段的属性信息
            PropertyInfo property = fieldInfo.getProperty();
            // 获取字段的数据类型
            DataType dataType = fieldInfo.getDataType();
            // 获取字段的别名
            String alias = fieldInfo.getAlias();//CertificateNumber.value
            // 获取字段的名称
            String name = fieldInfo.getName();//idCardNO
            // 分割字段别名
            String[] split = alias.split("#");
            Object value = null;
            // 获取字段的属性
            Map<String, String> attributes = fieldInfo.getAttributes();
            System.out.println("===============alias:" + alias);
            Object dataObject = jsonObject.get(split[0]);
            String s1 = attributes.get("data-valueType");
            fileName = attributes.get("data-fileName");
            if (s1 != null && s1.equals("url")) {
                if (dataObject instanceof JSONObject) {
                    JSONObject data = jsonObject.getJSONObject(split[0]);
                    if (data != null) {
                        value = data.get(split[1]);
                        if (value instanceof JSONObject) {
                            value = data.getJSONObject(split[1]).get(split[2]);
                            if (value instanceof JSONArray) {
                                JSONArray jsonArray = data.getJSONObject(split[1]).getJSONArray(split[2]);
                                String tempValue = "";
                                for (int j = 0; j < jsonArray.size(); j++) {
                                    String string = jsonArray.getString(j);
                                    file = new JSONObject();
                                    // 将数据的 UI 主键、下载链接和文件名添加到文件信息的 JSON 对象中
                                    file.put("uipk", attributes.get("data-uipk"));
                                    file.put("url", string);
                                    file.put("name", fileName);
                                    // 将文件信息的 JSON 对象添加到文件信息的 JSON 数组中
                                    files.add(file);
                                }
                                continue;
                            }
                        }else if (value instanceof String){
                            String string = data.getString(split[1]);
                            file = new JSONObject();
                            // 将数据的 UI 主键、下载链接和文件名添加到文件信息的 JSON 对象中
                            file.put("uipk", attributes.get("data-uipk"));
                            file.put("url", string);
                            file.put("name", fileName);
                            // 将文件信息的 JSON 对象添加到文件信息的 JSON 数组中
                            files.add(file);
                            continue;
                        }
                        if (value == null || value.equals("null") || value.equals("{}") || value.equals("")) {
                            continue;
                        }
//                        // 将数据的 UI 主键、下载链接和文件名添加到文件信息的 JSON 对象中
//                        file.put("uipk", attributes.get("data-uipk"));
//                        file.put("url", value);
//                        file.put("name", data.getString("text"));
//                        // 将文件信息的 JSON 对象添加到文件信息的 JSON 数组中
//                        files.add(file);
                    }

                } else if (dataObject instanceof JSONArray) {
                    JSONArray jsonArray1 = jsonObject.getJSONArray(split[0]);
                    if ((split[0].equals("entryRecord")||split[0].equals("employmentRecord"))&&jsonArray1.size()>0){
                        jsonArray1 = paixu(jsonArray1, "entryDate");
                        System.out.println("排序后entryRecord/employmentRecord"+jsonArray1);
                        // （可选）将排序后的List转回JSONArray
                    }
                    for (int j = 0; j < jsonArray1.size(); j++) {
                        JSONObject data = jsonArray1.getJSONObject(j);
                        if (data != null) {
                            value = data.get(split[1]);
                            if (value instanceof JSONObject) {
                                value = data.getJSONObject(split[1]).get(split[2]);
                                if (value instanceof JSONArray) {
                                    JSONArray jsonArray = data.getJSONObject(split[1]).getJSONArray(split[2]);
                                    System.out.println("===========" + jsonArray);
                                    String tempValue = "";
                                    for (int k = 0; k < jsonArray.size(); k++) {
                                        String string = jsonArray.getString(k);
                                        file = new JSONObject();
                                        // 将数据的 UI 主键、下载链接和文件名添加到文件信息的 JSON 对象中
                                        file.put("uipk", attributes.get("data-uipk"));
                                        file.put("url", string);
                                        file.put("name", fileName);
                                        // 将文件信息的 JSON 对象添加到文件信息的 JSON 数组中
                                        files.add(file);
                                    }
                                    //continue;
                                }
                            }
//                            if (value == null || value.equals("null") || value.equals("{}") || value.equals("")) {
//                                continue;
//                            }
//                            // 将数据的 UI 主键、下载链接和文件名添加到文件信息的 JSON 对象中
//                            file.put("uipk", attributes.get("data-uipk"));
//                            file.put("url", value);
//                            file.put("name", data.getString("text"));
//                            // 将文件信息的 JSON 对象添加到文件信息的 JSON 数组中
//                            files.add(file);
                        }
                    }
                    continue;
                }


            }
            Object data = jsonObject.get(split[0]);
            // 获取数据的 JSON 对象

            if (data == null) {
                // 如果数据为空，获取默认值
                value = attributes.get("data-defaultValue");
            } else {
                JSONObject data1 = null;
                // 获取数据的值
                if (data instanceof JSONArray) {
                    if (jsonObject.getJSONArray(split[0]).size() == 0) {
                        value = attributes.get("data-defaultValue");
                    } else {
                        JSONArray jsonArray = jsonObject.getJSONArray(split[0]);
                        if ((split[0].equals("entryRecord")||split[0].equals("employmentRecord"))&&jsonArray.size()>0){
                            // 定义日期格式
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                            JSONArray sortedJsonArray = paixu(jsonArray, "entryDate");
                            System.out.println("排序后entryRecord/employmentRecord"+sortedJsonArray);
                            // （可选）将排序后的List转回JSONArray
                            data1 = sortedJsonArray.getJSONObject(0);
                        }else {
                            data1 = jsonArray.getJSONObject(0);
                        }

                    }
                } else {
                    data1 = jsonObject.getJSONObject(split[0]);
                }

                value = data1.get(split[1]);

                if (value == null) {
                    // 如果值为空，获取默认值
                    value = attributes.get("data-defaultValue");
                } else {
                    value = data1.get(split[1]);
                    if (value instanceof JSONObject) {
                        value = data1.getJSONObject(split[1]).get(split[2]);
                    } else if (value instanceof JSONArray) {
                        JSONArray jsonArray = data1.getJSONArray(split[1]);
                        if (jsonArray.size() > 0) {
                            Object o = jsonArray.get(0);
                            if (o instanceof JSONObject) {
                                Object string = jsonArray.getJSONObject(0).get(split[2]);
                                if (string instanceof Integer) {
                                    value = jsonArray.getJSONObject(0).getInteger(split[2]);
                                } else if (o instanceof String) {
                                    value = jsonArray.getJSONObject(0).getString(split[2]);
                                }
                            }
                        }
                    } else {
                        value = data1.getString(split[1]);
                    }
                    // 获取自定义映射值
                    String s = attributes.get("data-mappingValue");
                    if (s != null && !s.equals("")) {
                        // 解析自定义映射值的 JSON 对象
                        JSONObject jsonObject1 = JSONObject.parseObject(s);
                        if (jsonObject1 != null && value != null) {
                            // 根据值获取映射后的值
                            String string = jsonObject1.getString(value.toString());
                            if (string != null) {
                                value = string;
                            }

                        }
                    }
                    if (value == null || value.equals("")) {
                        value = attributes.get("data-defaultValue");
                    }

                }

            }
            System.out.println("=========attributes.get(\"data-defaultValue\")" + attributes.get("data-defaultValue"));
            if (value == null || value.equals("")) {
                // 如果值为空，打印日志并跳过处理
                System.out.println("+++++++++" + value);
                continue;
            }
            if (dataType != null && dataType.getName().equals("ObjectValue")) {
                if (property instanceof LinkPropertyInfo) {
                    // 获取关联对象的全名称
                    String businessImplName = ((LinkPropertyInfo) property).getRelationship().getSupplierObject().getFullName();
                    // 根据全名称获取对应的对象值类
                    Class objectValueClass1 = MetaDataUtil.getObjectValueClass(businessImplName);
                    // 创建对应的实体对象
                    CoreBaseInfo coreBaseInfo1 = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass1, businessImplName);

                    // 创建对应的业务对象
                    ICoreBase bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, coreBaseInfo1.getBOSType()));
                    String where = "where name like '%" + value + "%' or number = '" + value + "'";
                    if (coreBaseInfo1 instanceof PersonInfo) {
                        where += " or bsUserId = '" + value + "'";
                    } else if (coreBaseInfo1 instanceof AdminOrgUnitInfo) {
                        where += " or reserveFieldFirst = '" + value + "'";
                    } else if (coreBaseInfo1 instanceof PositionInfo) {
                        where += " or OriginalId = '" + value + "'";
                    }
                    // 根据名称或编号查询实体对象集合
                    CoreBaseCollection dataBaseCollection = bosObject.getCollection(where);
                    if (dataBaseCollection.size() <= 0) {
                        // 如果值为空，获取默认值
                        value = attributes.get("data-defaultValue");
                        System.out.println("=========默认值重新查询===" + value);
                        // 如果集合为空，将字段的值设置为 null
                        // coreBaseInfo.put(name, null);
                        bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, coreBaseInfo1.getBOSType()));
                        where = "where name like '%" + value + "%' or number = '" + value + "'";
                        if (coreBaseInfo1 instanceof PersonInfo) {
                            where += " or bsUserId = '" + value + "'";
                        } else if (coreBaseInfo1 instanceof AdminOrgUnitInfo) {
                            where += " or reserveFieldFirst = '" + value + "'";
                        } else if (coreBaseInfo1 instanceof PositionInfo) {
                            where += " or OriginalId = '" + value + "'";
                        }
                        dataBaseCollection = bosObject.getCollection(where);
                        if (dataBaseCollection.size() > 0) {
                            setCoreBaseInfo(coreBaseInfo, name, dataBaseCollection.get(0));
                        }
                    } else {
                        // 将查询到的第一个实体对象设置到当前实体对象中
                        //coreBaseInfo.put(name, dataBaseCollection.get(0));
                        setCoreBaseInfo(coreBaseInfo, name, dataBaseCollection.get(0));
                    }

                }
            } else if (dataType != null && dataType.getName().equals("Enum")) {
                // 如果数据类型为枚举，将值设置到当前实体对象中
                //coreBaseInfo.put(name, value);
                setCoreBaseInfo(coreBaseInfo, name, value);
            } else if (dataType != null && dataType.getName().equals("Date")) {
                // 创建日期格式化对象
                SimpleDateFormat f = new SimpleDateFormat(attributes.get("dateFormat"));
                if (!value.equals("") || !value.equals("未知") || !value.equals("9999/12")) {
                    // 将日期字符串解析为日期对象并设置到当前实体对象中
                    //coreBaseInfo.put(name, f.parse(value));
                    setCoreBaseInfo(coreBaseInfo, name, f.parse(value.toString()));
                }
            } else {
                if (name.equals("entrys.IDCardNo")) {
                    // 获取证件类型的值
                    String string1 = jsonObject.getJSONObject("staffInfos").getString("idCardType");
                    if ("1".equals(string1)) {
                        // 如果证件类型为 1，将值设置到身份证号码字段中
                        //coreBaseInfo.put(name, value);
                        setCoreBaseInfo(coreBaseInfo, name, value);
                    } else {
                        // 否则，将值设置到护照号码字段中
                        //coreBaseInfo.put("passportNO", value);
                        setCoreBaseInfo(coreBaseInfo, "entrys.passportNO", value);
                    }
                    String where = "where IDCardNo = '"+value+"' or passportNO='"+value+"'";
                    System.out.println("====判断是否再入职=="+where);
                    EmpEnrollBizBillEntryCollection empEnrollBizBills = EmpEnrollBizBillEntryFactory
                            .getLocalInstance(context).getEmpEnrollBizBillEntryCollection(where);
                    HRBizDefineInfo hrBizDefineInfo = new HRBizDefineInfo();
                    System.out.println("====empEnrollBizBills=="+empEnrollBizBills.size());
                    if (empEnrollBizBills.size()>0){
                        System.out.println("====empEnrollBizBills= DawAAAApC9TmaL7Z= 是");
                        hrBizDefineInfo.setId(BOSUuid.read("DawAAAApC9TmaL7Z"));
                        setCoreBaseInfo(coreBaseInfo, "entrys.hrBizDefine", hrBizDefineInfo);
                    }else {

                        PersonCollection personCollection = PersonFactory.getLocalInstance(context)
                                .getPersonCollection("where PassportNO='" + value + "' or IDCardNO='" + value + "'");
                        if (personCollection.size()>0){
                            System.out.println("====empEnrollBizBills= DawAAAApC9TmaL7Z= 是");
                            hrBizDefineInfo.setId(BOSUuid.read("DawAAAApC9TmaL7Z"));
                            setCoreBaseInfo(coreBaseInfo, "entrys.hrBizDefine", hrBizDefineInfo);
                        }else {
                            System.out.println("====empEnrollBizBills= DawAAAApC9DmaL7Z= 否");
                            hrBizDefineInfo.setId(BOSUuid.read("DawAAAApC9DmaL7Z"));
                            setCoreBaseInfo(coreBaseInfo, "entrys.hrBizDefine", hrBizDefineInfo);
                        }

                    }
                } else {
                    if (name.equals("nCell")){
                        String s = extractContent((String) value);
                        System.out.println(s +"''''''''"+value );
                        if (s!=null&&!s.equals("")){
                            System.out.println("setCoreBaseInfo(coreBaseInfo, \"globalRoaming\", s);\n");
                            setCoreBaseInfo(coreBaseInfo, "globalRoaming", s);
                            value = ((String) value).replace("("+s+")","");
                            setCoreBaseInfo(coreBaseInfo, name, value);
                        }else {
                            System.out.println("setCoreBaseInfo(coreBaseInfo, \"globalRoaming\", +86);\n");
                            setCoreBaseInfo(coreBaseInfo, "globalRoaming", "+86");
                        }
                    }else if (name.equals("entrys.nCell")||name.equals("entrys.telNum")){
                        String s = extractContent((String) value);
                        System.out.println(s +"''''''''"+value );
                        if (s!=null&&!s.equals("")) {
                            System.out.println("setCoreBaseInfo(coreBaseInfo, \"entrys.globalRoaming\", s));\n");
                            setCoreBaseInfo(coreBaseInfo, "entrys.globalRoaming", s);
                            value = ((String) value).replace("("+s+")","");
                            setCoreBaseInfo(coreBaseInfo, name, value);
                        }else {
                            System.out.println("setCoreBaseInfo(coreBaseInfo, \"entrys.globalRoaming\", +86));\n");
                            setCoreBaseInfo(coreBaseInfo, "entrys.globalRoaming", "+86");
                        }
                    }else {
                        setCoreBaseInfo(coreBaseInfo, name, value);
                    }
                    // 将值设置到当前实体对象中
                    //coreBaseInfo.put(name, value);
                }


            }
        }
        // 返回处理后的文件信息的 JSON 数组
        return files;
    }
    /**
     * 提取字符串中括号内的内容
     * @param input 包含括号的原始字符串
     * @return 括号内的内容，若格式不合法则返回空字符串
     */
    public  String extractContent(String input) {
        // 检查输入是否为空
        if (input == null || input.isEmpty()) {
            return "";
        }

        // 定位左括号'('和右括号')'的位置
        int leftIndex = input.indexOf('(');
        int rightIndex = input.indexOf(')');

        // 校验括号位置合法性（左括号存在、右括号存在、左括号在右括号之前）
        if (leftIndex == -1 || rightIndex == -1 || leftIndex >= rightIndex) {
            return "";
        }

        // 截取括号之间的内容（左括号后一位到右括号前一位）
        return input.substring(leftIndex + 1, rightIndex);
    }

    public void setCoreBaseInfo(CoreBaseInfo coreBaseInfo, String name, Object value) {
        System.out.println("+++++++++++++++" + name + ":" + value);
        if (name.indexOf(".") >= 0) {
            String[] split = name.split("\\.");
            Object o = coreBaseInfo.get(split[0]);
            if (o instanceof EmpEnrollBizBillEntryInfo) {
                ((CoreBaseInfo) o).put(split[1], value);
            } else if (o instanceof EmpEnrollBizBillEntryCollection) {
                EmpEnrollBizBillEntryCollection collection = ((EmpEnrollBizBillEntryCollection) o);
                EmpEnrollBizBillEntryInfo objectValue = null;
                if (collection.size() == 0) {
                    objectValue = new EmpEnrollBizBillEntryInfo();
                    //objectValue.setBizDate(new Date());
                    collection.add(objectValue);
                } else {
                    objectValue = collection.get(0);
                    Date bizDate = objectValue.getBizDate();
                    if (bizDate == null) {
                        //objectValue.setBizDate(new Date());
                    }
                    String empNumber = objectValue.getEmpNumber();
                    if (empNumber == null || empNumber.equals("")) {
                        try {
                            String billNumber = readCodeRuleNumber(context, new PersonInfo(), getMainOrgByCu(context));
                            System.out.println("billNumber：" + billNumber);
                            objectValue.setEmpNumber(billNumber);
                        } catch (SHRWebException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
                objectValue.put(split[1], value);
                if (split[1].equals("position")) {
                    if (value instanceof PositionInfo) {
                        objectValue.put("job", ((PositionInfo) value).getJob());
                        objectValue.put("adminOrg", ((PositionInfo) value).getAdminOrgUnit());
                    }
                }
            }
        } else {
            coreBaseInfo.put(name, value);
        }


    }

    public static String getMainOrgByCu(Context ctx) {
        OrgUnitInfo mainOrg = (OrgUnitInfo) ctx.get(OrgType.HRO);
        String orgId = mainOrg == null ? "" : mainOrg.getString("id");
        if (orgId == null || orgId.trim().length() == 0) {
            orgId = "00000000-0000-0000-0000-000000000000CCE7AED4";
        }

        return orgId;
    }


    public static String readCodeRuleNumber(Context ctx, IObjectValue model, String mainOrgID) throws SHRWebException {
        boolean hasCodingRule = hasCodingRule(ctx, model, mainOrgID);
        if (hasCodingRule) {
            try {
                ICodingRuleManager iCodingRuleManager = CodingRuleManagerFactory.getLocalInstance(ctx);
                return iCodingRuleManager.readNumber(model, mainOrgID);
            } catch (BOSException var5) {
                throw new SHRWebException(var5);
            } catch (EASBizException var6) {
                throw new SHRWebException(var6);
            }
        } else {
            return null;
        }
    }

    public static boolean hasCodingRule(Context ctx, IObjectValue model, String orgId) {
        try {
            ICodingRuleManager iCodingRuleManager = CodingRuleManagerFactory.getLocalInstance(ctx);
            if (orgId != null && orgId.trim().length() > 0 && iCodingRuleManager.isExist(model, orgId)) {
                return true;
            } else {
                String companyId = getNextCompanyId(ctx);
                return companyId != null && companyId.trim().length() > 0 && iCodingRuleManager.isExist(model, companyId);
            }
        } catch (Exception var5) {
            var5.printStackTrace();
            return false;
        }
    }

    public static String getNextCompanyId(Context ctx) throws Exception {
        ICtrlUnit iCtrlUnit = CtrlUnitFactory.getRemoteInstance();
        IObjectPK pk = new ObjectUuidPK("00000000-0000-0000-0000-000000000000CCE7AED4");
        OrgUnitInfo rootCU = iCtrlUnit.getCtrlUnitInfo(pk);
        return rootCU != null ? rootCU.getId().toString() : null;
    }

    public String headProcessing(UIViewInfo uiViewInfo, JSONObject jsonObject
            , CoreBaseInfo coreBaseInfo, JSONArray fileJSON, String fileName) throws BOSException, SHRWebException,
            EASBizException, JSONException, ParseException, IOException {
        // 根据 UI 视图的主键生成动态 UI 视图信息
        com.kingdee.shr.base.syssetting.web.dynamic.model.UIViewInfo uiViewInfo1 =
                generateUIView(context, uiViewInfo.getUipk());
        // 获取实体名称
        String entityName = uiViewInfo1.getEntityName();
        // 获取字段列表
        List<FieldInfo> fields = uiViewInfo1.getFields();
        // 处理字段信息
        JSONArray jsonArray = this.fieldProcessing(fields, coreBaseInfo, jsonObject, fileName);
        // 创建对应的业务对象
        ICoreBase bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, coreBaseInfo.getBOSType()));
        IObjectPK save = null;
        // 保存实体对象
        if (coreBaseInfo instanceof EmpEnrollBizBillInfo) {
            System.out.println("===========submit==============");
            coreBaseInfo.put("billState", HRBillStateEnum.SUBMITED);
            coreBaseInfo.put("approveType", ApproveTypeEnum.WORKFLOW);
            coreBaseInfo.setExtendedProperty("isAddNew", "isAddNew");
            boolean isOpen = WfEventListenerStateManager.getInstance().isEnable();//开启工作流事务
            System.out.println("工作流事务：" + isOpen);
            if (!isOpen) {
                WfEventListenerStateManager.getInstance().enableEventListener();
            }
            save = bosObject.submit(coreBaseInfo); //如果本来工作流服务状态不是关的，将它关掉
            if (!isOpen) {
                WfEventListenerStateManager.getInstance().disableEventListener();
            }
            System.out.println("工作流事务：" + isOpen);
        } else {
            System.out.println("===========save==============");
            save = bosObject.save(coreBaseInfo);

        }
        // 处理文件信息
        fileProcessor(save.toString(), jsonArray);

        // 获取文件信息的第一个 JSON 对象
        if (fileJSON != null) {
            JSONObject jsonObject1 = fileJSON.getJSONObject(0);
            if (!save.toString().equals("")) {
                // 遍历字段列表
                for (int i = 0; i < fields.size(); i++) {
                    // 获取单个字段信息
                    FieldInfo fieldInfo = fields.get(i);
                    // 获取字段的别名
                    String alias = fieldInfo.getAlias();//CertificateNu
                    // 获取字段的名称
                    String name = fieldInfo.getName();//idCardNO
                    if (!name.equals(fileName)) {
                        continue;
                    }
                    // 分割字段别名
                    String[] split = alias.split("#");
                    // 获取字段的属性
                    Map<String, String> attributes = fieldInfo.getAttributes();
                    // 获取数据的 UI 主键
                    String uipk = attributes.get("data-uipk");
                    // 获取文件信息
                    JSONObject data = jsonObject1.getJSONObject(split[1]);

                    if (data != null) {
                        // 获取下载链接
                        JSONArray downloadUrl = data.getJSONArray("downloadUrls");
                        // 分割下载链接
                        // 获取文件名
                        //String text = data.getString("text");
                        // 分割文件名
                        //String[] split2 = text.split(",");
                        for (int k = 0; k < downloadUrl.size(); k++) {
                            byte[] dataImg = new byte[0];
                            // 拼接完整的下载链接
                            String URL = "http:" + downloadUrl.get(k);
                            System.out.println("===========" + URL + "==========");
                            // 从网络下载文件数据
                            dataImg = helper.getBytesByNetURL(URL);
                            // 插入人员附件信息
                            //insertPersonAttachment(split2[k], uipk, save.toString(), dataImg);
                        }
                    }


                }
            }
        }


        // 返回保存后的人员信息实体对象的主键
        return save.toString();
    }


    /**
     * 处理头部信息
     *
     * @param uiViewInfo 头部 UI 视图信息
     * @param jsonObject 人员信息的 JSON 对象
     * @param fileJSON   文件信息的 JSON 数组
     * @return 保存后的对象主键
     * @throws BOSException    BOS 异常
     * @throws SHRWebException SHR 网页异常
     * @throws EASBizException EAS 业务异常
     * @throws JSONException   JSON 处理异常
     * @throws ParseException  解析异常
     * @throws IOException     输入输出异常
     */
    public String headProcessing(UIViewInfo uiViewInfo, JSONObject jsonObject
            , JSONArray fileJSON, String fileName) throws BOSException, SHRWebException,
            EASBizException, JSONException, ParseException, IOException {
        // 根据 UI 视图的主键生成动态 UI 视图信息
        com.kingdee.shr.base.syssetting.web.dynamic.model.UIViewInfo uiViewInfo1 =
                generateUIView(context, uiViewInfo.getUipk());
        // 获取实体名称
        String entityName = uiViewInfo1.getEntityName();
        // 获取字段列表
        List<FieldInfo> fields = uiViewInfo1.getFields();
        // 根据实体名称获取对应的对象值类
        Class objectValueClass = MetaDataUtil.getObjectValueClass(entityName);
        // 创建对应的实体对象
        CoreBaseInfo coreBaseInfo = (CoreBaseInfo) MetaDataUtil.newInstance(objectValueClass, entityName);
        coreBaseInfo.getBOSType();
        // 处理字段信息
        JSONArray jsonArray = this.fieldProcessing(fields, coreBaseInfo, jsonObject, fileName);
        // 创建对应的业务对象
        ICoreBase bosObject = (ICoreBase) (BOSObjectFactory.createBOSObject(context, coreBaseInfo.getBOSType()));

        IObjectPK save = null;
        // 保存实体对象
        if (coreBaseInfo instanceof EmpEnrollBizBillInfo) {
            System.out.println("=====submit=========");
            coreBaseInfo.put("billState", HRBillStateEnum.SUBMITED);
            coreBaseInfo.put("approveType", ApproveTypeEnum.WORKFLOW);
            coreBaseInfo.setExtendedProperty("isAddNew", "isAddNew");
            boolean isOpen = WfEventListenerStateManager.getInstance().isEnable();//开启工作流事务
            System.out.println("工作流事务：" + isOpen);
            if (!isOpen) {
                WfEventListenerStateManager.getInstance().enableEventListener();
            }
            save = bosObject.submit(coreBaseInfo); //如果本来工作流服务状态不是关的，将它关掉
            if (!isOpen) {
                WfEventListenerStateManager.getInstance().disableEventListener();
            }
            System.out.println("工作流事务：" + isOpen);
        } else {
            System.out.println("=====save=========");
            save = bosObject.save(coreBaseInfo);

        }
        // 处理文件信息
        fileProcessor(save.toString(), jsonArray);

        // 获取文件信息的第一个 JSON 对象
        if (fileJSON != null) {
            JSONObject jsonObject1 = fileJSON.getJSONObject(0);
            if (!save.toString().equals("")) {
                // 遍历字段列表
                for (int i = 0; i < fields.size(); i++) {
                    // 获取单个字段信息
                    FieldInfo fieldInfo = fields.get(i);
                    // 获取字段的别名
                    String alias = fieldInfo.getAlias();//CertificateNu
                    // 获取字段的名称
                    String name = fieldInfo.getName();//idCardNO
                    if (!name.equals(fileName)) {
                        continue;
                    }
                    // 分割字段别名
                    String[] split = alias.split("#");
                    // 获取字段的属性
                    Map<String, String> attributes = fieldInfo.getAttributes();
                    // 获取数据的 UI 主键
                    String uipk = attributes.get("data-uipk");
                    // 获取文件信息
                    JSONObject data = jsonObject1.getJSONObject(split[1]);

                    if (data != null) {
                        // 获取下载链接
                        JSONArray downloadUrl = data.getJSONArray("downloadUrls");
                        // 分割下载链接
                        // 获取文件名
                        //String text = data.getString("text");
                        // 分割文件名
                        //String[] split2 = text.split(",");
                        for (int k = 0; k < downloadUrl.size(); k++) {
                            byte[] dataImg = new byte[0];
                            // 拼接完整的下载链接
                            String URL = "http:" + downloadUrl.get(k);
                            System.out.println("===========" + URL + "==========");
                            // 从网络下载文件数据
                            dataImg = helper.getBytesByNetURL(URL);
                            // 插入人员附件信息
                            //insertPersonAttachment(split2[k], uipk, save.toString(), dataImg);
                        }
                    }


                }
            }
        }


        // 返回保存后的人员信息实体对象的主键
        return save.toString();
    }

    /**
     * 处理文件信息
     *
     * @param id         关联的 ID
     * @param jsonArray  文件信息的 JSON 数组
     * @throws JSONException JSON 处理异常
     */
    public void fileProcessor(String id, JSONArray jsonArray) throws JSONException {
        // 遍历文件信息的 JSON 数组
        for (int i = 0; i < jsonArray.size(); i++) {
            // 获取单个文件信息
            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
            // 获取数据的 UI 主键
            String uipk = jsonObject1.getString("uipk");
            // 获取文件的下载链接
            String url = jsonObject1.getString("url");
            // 获取文件的名称
            String name = jsonObject1.getString("name");
            if (url == null || url.toString().equals("") || url.toString().equals("[]")) {
                continue;
            }
            if (uipk.equals("PersonPhoto")) {
                System.out.println("头像处理");
                try {
                    PersonInfo personInfo = getPerson(id);
                    if (personInfo != null) {
                        System.out.println("========personInfo 获取到的员工id===="+personInfo.getId());
                        // 保存人员照片信息
                        savePersonPhoto(personInfo, url);
                    }else {
                        System.out.println("========personInfo 获取到的员工id==== null");

                    }

                } catch (IOException e) {
                    // 抛出运行时异常，表示保存人员照片信息失败
                    throw new RuntimeException(e+"抛出运行时异常，表示保存人员照片信息失败");
                } catch (BOSException e) {
                    throw new RuntimeException(e+"查询入制单失败！或者查询临时员工失败！"+id);
                } catch (EASBizException e) {
                    throw new RuntimeException(e+"查询入制单失败！或者查询临时员工失败！"+id);
                }
            } else {
                try {
                    // 从网络下载文件数据
                    byte[] dataImg = null;
                    if (url.indexOf("http:") >= 0 || url.indexOf("https:") >= 0) {
                        dataImg = helper.getBytesByNetURL(url);
                    } else {
                        dataImg = helper.getBytesByNetURL("http:" + url);
                    }
                    // 插入人员附件信息
                    if (name != null&&!name.equals("")) {
                        String s = extractFileNameFromUrl(url);
                        String[] split = s.split("\\.");
                        System.out.println("+++++split+++++++++"+split[1]);
                        name = name + "." +split[1];
                    }else {
                        name = extractFileNameFromUrl(url);
                    }
                    insertPersonAttachment(name, uipk, id, dataImg);
                } catch (IOException e) {
                    // 抛出运行时异常，表示下载文件数据失败
                    throw new RuntimeException(e+"抛出运行时异常，表示下载文件数据失败");
                } catch (BOSException e) {
                    // 抛出运行时异常，表示插入人员附件信息失败
                    throw new RuntimeException(e+"抛出运行时异常，表示插入人员附件信息失败");
                } catch (EASBizException e) {
                    // 抛出运行时异常，表示插入人员附件信息失败
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public PersonInfo getPerson(String id) throws BOSException, EASBizException {
        PersonInfo personInfo = null;
        BOSUuid read = BOSUuid.read(id);
        BOSObjectType type = read.getType();
        String bosType = type.toString();
        if (bosType.equals("80EF7DED")){
            System.out.println("传入的ID："+id+" 为员工，personInfo bosType：80EF7DED");
            personInfo = new PersonInfo();
            personInfo.setId(read);
        }else if (bosType.equals("B41CAA3F")){
            System.out.println("传入的ID："+id+" 入职单, EmpEnrollBizBill bosType：B41CAA3F");
            System.out.println("查询入职单："+id+"");
            EmpEnrollBizBillInfo empEnrollBizBillInfo = EmpEnrollBizBillFactory
                    .getLocalInstance(context).getEmpEnrollBizBillInfo("where id = '" + id + "'");
            EmpEnrollBizBillEntryCollection entrys = empEnrollBizBillInfo.getEntrys();
            if (entrys.size()<=0){
                throw new RuntimeException("入职单没有对应的分录："+id);
            }
            EmpEnrollBizBillEntryInfo empEnrollBizBillEntryInfo = entrys.get(0);
            BOSUuid entryId = empEnrollBizBillEntryInfo.getId();
            System.out.println("查询入职单分录/查询临时人员："+entryId+"");
            TempPersonPhotoCollection tempPersonPhotoCollection = TempPersonPhotoFactory.getLocalInstance(context).
                    getTempPersonPhotoCollection("where EmpEnrollBillEntryId = '" + entryId + "'");
            if (tempPersonPhotoCollection.size()<=0){
                System.out.println("创建临时员工");
                TempPersonPhotoInfo tempPersonPhotoInfo = new TempPersonPhotoInfo();
                BOSUuid bosUuid = BOSUuid.create("80EF7DED");
                System.out.println("创建临时员工id"+bosUuid.toString());
                tempPersonPhotoInfo.setTempPersonId(bosUuid.toString());
                tempPersonPhotoInfo.setEmpEnrollBillEntryId(empEnrollBizBillEntryInfo);
                IObjectPK save = TempPersonPhotoFactory.getLocalInstance(context).save(tempPersonPhotoInfo);
                System.out.println("=========save====保持临时员工信息==="+save);
                personInfo = new PersonInfo();
                personInfo.setId(bosUuid);
            }else {
                System.out.println("查询到了临时员工");
                TempPersonPhotoInfo tempPersonPhotoInfo = tempPersonPhotoCollection.get(0);
                String tempPersonId = tempPersonPhotoInfo.getTempPersonId();
                personInfo = new PersonInfo();
                personInfo.setId(BOSUuid.read(tempPersonId));
            }

        }
        return personInfo;
    }

    public static void main(String[] args) {
//        String name = extractFileNameFromUrl("https://dfiles.italent.cn/download/recruitonboardingfile/433107/1753067254/3/66304e3e5cb7431f9fb1900ba675cee3.jpg?sig_t=1753070295&sig_exp=2592000&sig_a=recruitonboarding&sig_pm=8&sig_npm=2&sig_v=1&sig=41d7e3c49cef36421ff8c4c4bd4ff6b145810ca3");

        String s = new SynchronousEmpBillControllerBean().extractContent("18xxxx1111");
        System.out.println(s);
    }

    // 从URL中提取文件名
    private static String extractFileNameFromUrl(String url) {
        if (url == null || url.isEmpty()) {
            return null;
        }

        int lastSlash = url.lastIndexOf('/');
        if (lastSlash != -1 && lastSlash < url.length() - 1) {
            String fileName = url.substring(lastSlash + 1);

            // 去除查询参数
            int queryIndex = fileName.indexOf('?');
            if (queryIndex != -1) {
                fileName = fileName.substring(0, queryIndex);
            }

            return fileName;
        }

        return null;
    }

    /**
     * 保存人员照片信息
     *
     * @param personInfo         人员信息对象
     * @param iDPhotoDownloadUrl 照片下载链接
     * @throws IOException 输入输出异常
     */
    private void savePersonPhoto(PersonInfo personInfo, String iDPhotoDownloadUrl) throws IOException {
        if (!StringUtils.isEmpty(iDPhotoDownloadUrl)) {
            // 打印照片下载链接
            System.out.println("iDPhotoDownloadUrl" + iDPhotoDownloadUrl);
            // 从网络下载照片数据
            byte[] dataImg = helper.getBytesByNetURL("http:" + iDPhotoDownloadUrl);
            // 创建人员照片信息对象
            PersonPhotoInfo personPhotoInfo = new PersonPhotoInfo();
            // 设置照片数据
            personPhotoInfo.setImageData(dataImg);
            // 设置关联的人员信息对象
            personPhotoInfo.setPerson(personInfo);
            try {
                // 保存人员照片信息
                PersonPhotoFactory.getLocalInstance(context)
                        .save(personPhotoInfo);
            } catch (EASBizException e) {
                e.printStackTrace();
            } catch (BOSException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 插入人员附件信息
     *
     * @param filename 文件名
     * @param uipk     数据的 UI 主键
     * @param boId     业务对象的 ID
     * @param data     文件数据
     * @return 附件的 ID
     * @throws BOSException    BOS 异常
     * @throws EASBizException EAS 业务异常
     */
    public String insertPersonAttachment(String filename, String uipk, String boId, byte[] data) throws BOSException, EASBizException {
        if (data.length > 20971520) {
            // 如果文件大小超过 20MB，抛出 BOS 异常
            throw new BOSException("文件上传失败，文件大小超过20MB！");
        } else if (!org.apache.commons.lang3.StringUtils.isBlank(filename) && !org.apache.commons.lang3.StringUtils.isBlank(boId) && data.length > 0) {
            // 创建 SHR 附件扩展信息对象
            SHRAttachmentExtInfo attchExt = new SHRAttachmentExtInfo();
            // 创建附件信息对象
            AttachmentInfo ai = new AttachmentInfo();
            // 获取管理员用户信息
            UserInfo userInfo = UserFactory.getLocalInstance(context).getUserInfo("where number = 'administrator'");
            // 获取用户 ID
            String userId = userInfo.getId().toString();
            // 设置附件名称
            System.out.println("+++filename+++"+filename);
            ai.setName(filename.substring(0, filename.lastIndexOf(".")));
            // 设置附件简单名称
            ai.setSimpleName(filename.substring(filename.lastIndexOf(".") + 1));
            // 设置附件描述
            ai.setDescription("");
            // 设置附件文件数据
            ai.setFile(data);
            // 设置附件是否共享
            ai.setIsShared(false);
            // 设置附件共享描述
            ai.setSharedDesc("否");
            // 设置附件 ID
            ai.setAttachID("" + System.currentTimeMillis());
            // 设置附件类型
            ai.setType(this.getFileType(filename));
            // 将附件信息对象设置到 SHR 附件扩展信息对象中
            attchExt.setAttachment(ai);
            // 设置 SHR 附件扩展信息对象的名称
            attchExt.setName(filename);
            // 设置 SHR 附件扩展信息对象的属性名称
            attchExt.setPropertyName("null0");
            // 设置 SHR 附件扩展信息对象的类型
            attchExt.setType(AttachmentTypeEnum.FORM);
            // 设置 SHR 附件扩展信息对象的状态
            attchExt.setState(AttachmentState.UNSAVE);
            // 设置 SHR 附件扩展信息对象的绑定信息
            attchExt.setBunding(userId + "#" + uipk);
            // 设置 SHR 附件扩展信息对象关联的业务对象 ID
            attchExt.setBoID(boId);
            // 设置 SHR 附件扩展信息对象的状态
            attchExt.setState(AttachmentState.SAVE);
            // 保存附件信息对象
            AttachmentFactory.getLocalInstance(context).save(ai);
            // 设置 SHR 附件扩展信息对象的状态
            attchExt.setState(AttachmentState.SAVE);
            // 创建业务对象与附件关联信息对象
            BoAttchAssoInfo boAttchAssoInfo = new BoAttchAssoInfo();
            // 设置业务对象与附件关联信息对象关联的业务对象 ID
            boAttchAssoInfo.setBoID(boId);
            // 设置业务对象与附件关联信息对象关联的业务对象类型
            boAttchAssoInfo.setAssoBusObjType(String.valueOf(BOSUuid.getBOSObjectType(boId, true)));
            // 设置业务对象与附件关联信息对象的关联类型
            boAttchAssoInfo.setAssoType("Added Accessories");
            // 将附件信息对象设置到业务对象与附件关联信息对象中
            boAttchAssoInfo.setAttachment(ai);
            // 保存业务对象与附件关联信息对象
            BoAttchAssoFactory.getLocalInstance(context).save(boAttchAssoInfo);
            // 保存 SHR 附件扩展信息对象
            SHRAttachmentExtFactory.getLocalInstance(context).save(attchExt);
            // 返回附件的 ID
            return ai.getId().toString();
        } else {
            // 如果文件名、业务对象 ID 或文件数据为空，抛出 BOS 异常
            throw new BOSException("文件上传失败，请确认信息无误！");
        }
    }

    /**
     * 根据文件名获取文件类型
     *
     * @param fullname 文件名
     * @return 文件类型
     */
    private String getFileType(String fullname) {
        // 获取文件扩展名
        String extname = fullname.substring(fullname.lastIndexOf(".") + 1, fullname.length());
        if (!"doc".equalsIgnoreCase(extname) && !"docx".equalsIgnoreCase(extname)) {
            if (!"xls".equalsIgnoreCase(extname) && !"xlsx".equalsIgnoreCase(extname) && !"xlsm".equalsIgnoreCase(extname) && !"xlsb".equalsIgnoreCase(extname)) {
                if (!"ppt".equalsIgnoreCase(extname) && !"pptx".equalsIgnoreCase(extname) && !"pptm".equalsIgnoreCase(extname)) {
                    return "txt".equalsIgnoreCase(extname) ? "TEXT 文本文件" : "未知文件类型(." + extname + ")";
                } else {
                    return "Microsoft PowerPoint 幻灯片";
                }
            } else {
                return "Microsoft Excel 表格";
            }
        } else {
            return "Microsoft Word 文档";
        }
    }

    /**
     * 根据 UI 视图的主键生成动态 UI 视图信息
     *
     * @param ctx  上下文对象
     * @param uipk UI 视图的主键
     * @return 动态 UI 视图信息
     * @throws SHRWebException SHR 网页异常
     */
    private com.kingdee.shr.base.syssetting.web.dynamic.model.UIViewInfo generateUIView(Context ctx, String uipk) throws SHRWebException {
        // 从数据库中获取 UI 视图信息
        com.kingdee.shr.base.syssetting.UIViewInfo dbUIViewInfo = getUIViewFromDB(ctx, uipk);
        if (dbUIViewInfo == null) {
            if (uipk.contains(" ")) {
                // 如果 UI 视图主键包含空格，抛出 SHR 网页业务异常
                throw new ShrWebBizException(MessageFormat.format(SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "view_contain_blank"), uipk));
            } else {
                // 如果 UI 视图信息为空，抛出 SHR 网页业务异常
                throw new ShrWebBizException(SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "view_not_found"));
            }
        } else {
            // 处理树导航元素
            dealTreeNavigationElement(dbUIViewInfo);
            // 获取 UI 视图转换器
            IUIViewConverter converter = UIViewConverterFactory.getUIViewConverter(dbUIViewInfo, ctx);
            // 执行转换操作
            return converter.exec();
        }
    }

    /**
     * 处理树导航元素
     *
     * @param dbUIViewInfo UI 视图信息
     */
    private void dealTreeNavigationElement(com.kingdee.shr.base.syssetting.UIViewInfo dbUIViewInfo) {
        // 处理配置信息
        String content = dealConfig(dbUIViewInfo.getContent());
        // 处理扩展配置信息
        String extend = dealConfig(dbUIViewInfo.getExtend());
        if (!StringUtils.isEmpty(content)) {
            // 如果处理后的配置信息不为空，设置到 UI 视图信息中
            dbUIViewInfo.setContent(content);
        }

        if (!StringUtils.isEmpty(extend)) {
            // 如果处理后的扩展配置信息不为空，设置到 UI 视图信息中
            dbUIViewInfo.setExtend(extend);
        }

    }

    /**
     * 从数据库中获取 UI 视图信息
     *
     * @param ctx  上下文对象
     * @param uipk UI 视图的主键
     * @return UI 视图信息
     * @throws SHRWebException SHR 网页异常
     */
    public com.kingdee.shr.base.syssetting.UIViewInfo getUIViewFromDB(Context ctx, String uipk) throws SHRWebException {
        try {
            if (LocaleUtils.locale_zh_CN.toString().equals(LocaleUtils.getLocaleString(LocaleUtils.getFirstOriginLocale(ctx.getLocale())))) {
                // 如果是中文环境，根据 UI 视图主键和选择器从数据库中获取 UI 视图信息
                return UIViewFactory.getLocalInstance(ctx).getValueByUipk(uipk, SysSettingUIViewUtil.getUIViewSelector());
            } else {
                // 如果不是中文环境，使用多语言服务进行转换
                Map<String, Object> params = new HashMap();
                params.put("uipks", uipk);
                params.put("isConvert", true);
                Object obj = MLServiceFactory.getLocalInstance(ctx).convert(ResourceType.UIView, params);
                return null == obj ? null : (com.kingdee.shr.base.syssetting.UIViewInfo) obj;
            }
        } catch (BOSException var4) {
            // 抛出 SHR 网页业务异常
            throw new ShrWebBizException(var4.getMessage(), var4);
        } catch (EASBizException var5) {
            // 抛出 SHR 网页业务异常
            throw new ShrWebBizException(var5.getMessage(), var5);
        }
    }

    /**
     * 处理配置信息
     *
     * @param text 配置信息文本
     * @return 处理后的配置信息
     */
    private String dealConfig(String text) {
        if (StringUtils.isEmpty(text)) {
            return null;
        } else {
            try {
                // 获取 XML 输出器
                XMLOutputter output = XMLUtil.getXMLOutputter();
                // 解析 XML 文本
                Document doc = XMLUtil.parseXML(text);
                // 获取根元素
                Element rootElement = doc.getRootElement();
                // 创建树导航 XPath 对象
                XPath xPathTreeNavigation = XPath.newInstance("//treeNavigation");
                // 创建过滤器项 XPath 对象
                XPath xPathFilterItem = XPath.newInstance("//filterItem[@isAdminOrg='true']");
                // 获取树导航元素列表
                List<Element> treeNavigations = xPathTreeNavigation.selectNodes(rootElement);
                // 获取过滤器项元素列表
                List<Element> filterItems = xPathFilterItem.selectNodes(rootElement);
                if (null != treeNavigations && treeNavigations.size() > 0) {
                    if (null != filterItems && filterItems.size() > 0) {
                        // 遍历树导航元素列表
                        Iterator i$ = treeNavigations.iterator();

                        while (i$.hasNext()) {
                            // 获取单个树导航元素
                            Element e = (Element) i$.next();
                            // 获取父元素
                            Element parent = e.getParent();
                            // 从父元素中移除树导航元素
                            parent.removeContent(e);
                        }

                        // 输出处理后的 XML 文本
                        String r = output.outputString(doc);
                        return r;
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } catch (Exception var11) {
                return null;
            }
        }
    }
    JSONArray paixu (JSONArray jsonArray,final String entryDate){
        List<JSONObject> list = jsonArray.toJavaList(JSONObject.class);
        // 定义日期格式
        final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        // 排序
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                try {
                    // 获取entryDate字段
                    String dateStr1 = o1.getString(entryDate);
                    String dateStr2 = o2.getString(entryDate);

                    // 解析为Date对象
                    Date date1 = sdf.parse(dateStr1);
                    Date date2 = sdf.parse(dateStr2);

                    // 比较日期
                    return date2.compareTo(date1);
                } catch (Exception e) {
                    // 处理日期解析异常
                    e.printStackTrace();
                    return 0;
                }
            }
        });
        // （可选）将排序后的List转回JSONArray
        return JSONArray.parseArray(JSONArray.toJSONString(list));
    }

}