package com.hzya.frame.grpU8.nxproof.oerdjml.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.grpU8.nxproof.attachment.dao.IAttachmentFileDao;
import com.hzya.frame.grpU8.nxproof.attachment.entity.AttachmentFileEntity;
import com.hzya.frame.grpU8.nxproof.gbizbsyrec.dao.IGbiZbsyrecDao;
import com.hzya.frame.grpU8.nxproof.gbizbsyrec.entity.GbiZbsyrecEntity;
import com.hzya.frame.grpU8.nxproof.oerannex.dao.IOerAnnexDao;
import com.hzya.frame.grpU8.nxproof.oerannex.entity.OerAnnexEntity;
import com.hzya.frame.grpU8.nxproof.oerannex.service.IOerAnnexService;
import com.hzya.frame.grpU8.nxproof.oerdjjsfs.dao.IOerDjjsfsDao;
import com.hzya.frame.grpU8.nxproof.oerdjjsfs.entity.OerDjjsfsEntity;
import com.hzya.frame.grpU8.nxproof.oerdjml.dao.IOerDjmlDao;
import com.hzya.frame.grpU8.nxproof.oerdjml.dto.FileInfoDTO;
import com.hzya.frame.grpU8.nxproof.oerdjml.entity.GbiZbsyrecAllEntity;
import com.hzya.frame.grpU8.nxproof.oerdjml.entity.OerDjmlEntity;
import com.hzya.frame.grpU8.nxproof.oerdjml.service.IOerDjmlService;
import com.hzya.frame.grpU8.nxproof.oerdjnr.dao.IOerDjnrDao;
import com.hzya.frame.grpU8.nxproof.oerdjnr.entity.OerDjnrEntity;
import com.hzya.frame.grpU8.nxproof.oeryszb.dao.IOerYszbDao;
import com.hzya.frame.grpU8.nxproof.oeryszb.entity.OerYszbEntity;
import com.hzya.frame.grpU8.nxproof.pubauditlog.dao.IPubAuditLogDao;
import com.hzya.frame.grpU8.nxproof.pubauditlog.entity.PubAuditLogEntity;
import com.hzya.frame.grpU8.nxproof.pubobjflow.dao.IPubObjFlowDao;
import com.hzya.frame.grpU8.nxproof.pubobjflow.entity.PubObjFlowEntity;
import com.hzya.frame.mdm.entity.MdmDto;
import com.hzya.frame.seeyon.enums.ColEventTypeEnum;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:hecan
 * @Description:费用报销报销明细总
 * @params:
 * @return:
 * @Date: 2023/6/19 14:31
 */
@Service(value = "oerDjmlService")
public class OerDjmlServiceImpl implements IOerDjmlService {
    private static Logger logger= LogManager.getLogger(OerDjmlServiceImpl.class);

    @Autowired
    private IGbiZbsyrecDao iGbiZbsyrecDao;
    @Autowired
    private IOerDjjsfsDao iOerDjjsfsDao;
    @Autowired
    private IOerDjmlDao iOerDjmlDao;
    @Autowired
    private IOerAnnexDao oerAnnexDao;
    @Autowired
    private IAttachmentFileDao attachmentFileDao;
    @Autowired
    private IOerDjnrDao iOerDjnrDao;
    @Autowired
    private IOerYszbDao iOerYszbDao;
    @Autowired
    private IPubAuditLogDao iPubAuditLogDao;
    @Autowired
    private IPubObjFlowDao iPubObjFlowDao;

    @Override
    public String saveExpenseDocuments(JSONObject jsonObject) {

        //jsonObject =  createTestData();
        logger.info("费用报销单开始保存,接收三方系统参数:------>"+jsonObject.toJSONString());
        //获取主表数据
        logger.info("开始处理数据:------>");
        String gsdm = jsonObject.getString("gsdm");
        logger.info("根据公司代码查询最大单据编号,公司代码:------>"+gsdm);
        if(StrUtil.isEmpty(gsdm)){
            throw new BaseSystemException("公司代码不能为空！请排查参数gsdm");
        }
        if(StrUtil.isEmpty(jsonObject.getString("djdate"))){
            throw new BaseSystemException("单据日期不能为空！请排查参数djdate");
        }
   /*     logger.info("国子系统传递过来的发票号为:------>"+jsonObject.getString("fph"));
        if(StrUtil.isEmpty(jsonObject.getString("fph")) || "".equals(jsonObject.getString("fph"))){
            jsonObject.put("fph","");
        }else{
            jsonObject.put("fph",jsonObject.getString("fph")+"-");
        }
        logger.info("调整之后的发票号为:------>"+jsonObject.getString("fph"));
        if(StrUtil.isEmpty(jsonObject.getString("zy")) || "".equals(jsonObject.getString("zy"))){
            StringBuffer stringBuffer=new StringBuffer();
            if(StrUtil.isNotEmpty(jsonObject.getString("fph")) || !"".equals(jsonObject.getString("fph"))){
                stringBuffer.append(jsonObject.getString("fph"));
            }
            if(StrUtil.isNotEmpty(jsonObject.getString("bmmc")) || !"".equals(jsonObject.getString("bmmc"))){
                stringBuffer.append(jsonObject.getString("bmmc")+"-");
            }
            if(StrUtil.isNotEmpty(jsonObject.getString("zcmc")) || !"".equals(jsonObject.getString("zcmc"))){
                stringBuffer.append(jsonObject.getString("zcmc"));
            }
            jsonObject.put("zy",stringBuffer);
        }*/
        logger.info("主表摘要为:{}",jsonObject.getString("zy"));
        OerDjmlEntity oerDjmlEntity=new OerDjmlEntity();
        oerDjmlEntity.setGsdm(gsdm);
        oerDjmlEntity.setDjdate(jsonObject.getString("djdate"));
        oerDjmlEntity.setFph(nullConvert(jsonObject.getString("fph")));
        String maxDjbh = iOerDjmlDao.getMaxDjbgByGsdm(oerDjmlEntity);
        logger.info("获取到最大单据编号:------>"+maxDjbh);
        //查询最大单据ID mlid
        String maxMlId = iOerDjmlDao.getMaxMlIdByGsdm(oerDjmlEntity);
        logger.info("获取到最大单据ID MLID:------>"+maxMlId);
        logger.info("组装单据主表数据开始:------>");

        OerDjmlEntity oerdjml = createMainData(jsonObject,maxDjbh,maxMlId);
        logger.info("保存主表信息:------>");
        iOerDjmlDao.save("OerDjmlEntity_insert",oerdjml);
        logger.info("保存完主表信息后，更新主表摘要:------>");
        OerDjmlEntity oerDjml = updateOerDjmlZy(jsonObject, maxMlId);
        logger.info("更新主表摘要开始----->");
        iOerDjmlDao.update("OerDjmlEntity_update",oerDjml);
        logger.info("组装单据报销明细开始:------>");
        List<OerDjnrEntity> oerDjnrEntityList = creatOerDjnrEntity(jsonObject,maxDjbh,maxMlId);
        logger.info("保存报销明细开始:------>");
        for(OerDjnrEntity djnrEntity : oerDjnrEntityList){
            if(djnrEntity.getZy()==null||("").equals(djnrEntity.getZy())){
                StringBuffer stringBuffer=new StringBuffer();
                if(StrUtil.isNotEmpty(jsonObject.getString("fph")) || !"".equals(jsonObject.getString("fph"))){
                    stringBuffer.append(jsonObject.getString("fph"));
                }
                if(StrUtil.isNotEmpty(jsonObject.getString("bmmc")) || !"".equals(jsonObject.getString("bmmc"))){
                    stringBuffer.append(jsonObject.getString("bmmc")+"-");
                }
                if(StrUtil.isNotEmpty(jsonObject.getString("zcmc")) || !"".equals(jsonObject.getString("zcmc"))){
                    stringBuffer.append(jsonObject.getString("zcmc"));
                }
                djnrEntity.setZy(stringBuffer.toString());
            }
            logger.info("明细表摘要为:{}",djnrEntity.getZy());
            iOerDjnrDao.save("OerDjnrEntity_insert",djnrEntity);
            logger.info("保存完报销明细后，根据明细数据生成预算指标数据:------>");
            OerYszbEntity yszbEntity = createOerYszbEntity(djnrEntity,maxMlId);
            logger.info("保存预算指标开始:------>");
            iOerYszbDao.save("OerYszbEntity_insert",yszbEntity);
            logger.info("保存预算指标记录:------>");
            GbiZbsyrecEntity oeryszb= creteOerYszbEntity(jsonObject,djnrEntity);
            iGbiZbsyrecDao.save("GbiZbsyrecEntity_insert",oeryszb);
        }
        logger.info("组装单据结算方式明细开始:------>");
        List<OerDjjsfsEntity> oerDjjsfsEntityList = creatOerDjjsfsEntityList(jsonObject,maxDjbh,maxMlId);
        logger.info("保存结算方式明细开始:------>");
        for(OerDjjsfsEntity oerdjjsfs :oerDjjsfsEntityList){
            iOerDjjsfsDao.save("OerDjjsfsEntity_insert",oerdjjsfs);
        }
        //保存日志表PubAuditLog
        List<PubAuditLogEntity> pubAuditLogEntityList = createPubAuditLog(jsonObject, maxMlId);
        for (PubAuditLogEntity pubAuditLog : pubAuditLogEntityList) {
            iPubAuditLogDao.save("PubAuditLogEntity_insert",pubAuditLog);
        }
        //保存节点PUB_OBJ_FLOW
        PubObjFlowEntity pubObjFlowEntity = createPubObjFlow(jsonObject, maxMlId);
        iPubObjFlowDao.save("PubObjFlowEntity_insert",pubObjFlowEntity);
        return maxDjbh;
    }

    @Override
    public OerDjmlEntity queryOerDjmlEntity(OerDjmlEntity oerDjmlEntity) {
        OerDjmlEntity oerDjmlEntity1 = iOerDjmlDao.queryOerDjmlEntity(oerDjmlEntity);
        return oerDjmlEntity1;
    }



    /**
     * 保存节点PUB_OBJ_FLOW
     * @param jsonObject
     * @param maxMlId
     */
    public PubObjFlowEntity createPubObjFlow(JSONObject jsonObject, String maxMlId){
        PubObjFlowEntity pubObjFlowEntity = jsonObject.toJavaObject(PubObjFlowEntity.class);
        PubObjFlowEntity pubObjFlowEntityPofid=iPubObjFlowDao.query(pubObjFlowEntity, "PubObjFlowEntity_list_base");
        pubObjFlowEntity.setDjh(maxMlId);
        pubObjFlowEntity.setPofId(pubObjFlowEntityPofid.getPofId());
        pubObjFlowEntity.setModCode("OER");
        pubObjFlowEntity.setDjlx(jsonObject.getString("djlxId"));
        pubObjFlowEntity.setShrs(jsonObject.getString("crerdm"));
        pubObjFlowEntity.setShrmc(jsonObject.getString("crermc"));
        pubObjFlowEntity.setFlowcode("000006");
        pubObjFlowEntity.setAuditFlag("999");
        pubObjFlowEntity.setAuditAftFlag("-1");
        pubObjFlowEntity.setIsaudit("1");
        return pubObjFlowEntity;
    }

    /**
     * 保存节点PUB_OBJ_FLOW
     * @param entity
     * @param maxMlId
     */
    public PubObjFlowEntity setPubObjFlow(OerDjmlEntity entity, String maxMlId){
        PubObjFlowEntity pubObjFlowEntity = new PubObjFlowEntity();
        pubObjFlowEntity.setDataSourceCode(entity.getDataSourceCode());
        PubObjFlowEntity pubObjFlowEntityPofid=iPubObjFlowDao.query(pubObjFlowEntity, "PubObjFlowEntity_list_base");
        pubObjFlowEntity.setDjh(maxMlId);
        pubObjFlowEntity.setPofId(pubObjFlowEntityPofid.getPofId());
        pubObjFlowEntity.setModCode("OER");
        pubObjFlowEntity.setDjlx(entity.getDjlxId());
        pubObjFlowEntity.setShrs(entity.getCrerdm());
        pubObjFlowEntity.setShrmc(entity.getCrermc());
        pubObjFlowEntity.setFlowcode(entity.getFlowcode());
        pubObjFlowEntity.setAuditFlag("999");
        pubObjFlowEntity.setAuditAftFlag("-1");
        pubObjFlowEntity.setIsaudit("1");
        return pubObjFlowEntity;
    }

    /**
     * 新增日志表PubAuditLog
     * @param jsonObject
     * @param maxMlId
     */
    public List<PubAuditLogEntity> createPubAuditLog(JSONObject jsonObject,String maxMlId){
        List<PubAuditLogEntity> pubAuditLogEntityList=new ArrayList<>();
        //拼接送审参数
        PubAuditLogEntity pubAuditLogEntity = new PubAuditLogEntity();
        pubAuditLogEntity.setBillname("费用报销[向导式]");
        pubAuditLogEntity.setFlowname("暂时费用报销审批流");
        pubAuditLogEntity.setNodeseq("-9");
        pubAuditLogEntity.setNodename("送审");
        pubAuditLogEntity.setAuditorId("1");
        pubAuditLogEntity.setAuditor("系统管理员");
        pubAuditLogEntity.setAmt(jsonObject.getString("je"));
        pubAuditLogEntity.setRemark("国子系统送审成功");
        pubAuditLogEntity.setAtype("国子系统通过");
        pubAuditLogEntity.setBillId(maxMlId);
        pubAuditLogEntity.setModname("OER");
        pubAuditLogEntity.setFlowcode("000006");
        pubAuditLogEntity.setGsdm(jsonObject.getString("gsdm"));
        pubAuditLogEntity.setKjnd(jsonObject.getString("kjnd"));
        pubAuditLogEntity.setServdatetime("1");
        pubAuditLogEntity.setAdatetime("1");
        //获取最大值logid
        PubAuditLogEntity pubAuditLogEntityLogid = iPubAuditLogDao.query(pubAuditLogEntity, "PubAuditLogEntity_list_base_max");
        pubAuditLogEntity.setLogId(pubAuditLogEntityLogid.getLogId());
        //获取最大值logseq
        PubAuditLogEntity pubAuditLogEntityLogseq=iPubAuditLogDao.query(pubAuditLogEntity,"PubAuditLogEntity_list_base_logseq");
        pubAuditLogEntity.setLogseq(pubAuditLogEntityLogseq.getLogseq());

       /* //拼接审核参数
        PubAuditLogEntity pubAuditLogEntityTwo = new PubAuditLogEntity();
        pubAuditLogEntityTwo.setBillname("费用报销[向导式]");
        pubAuditLogEntityTwo.setFlowname("暂时费用报销审批流");
        pubAuditLogEntityTwo.setBizname("费用报销[向导式]");
        pubAuditLogEntityTwo.setNodeseq("999");
        pubAuditLogEntityTwo.setNodename("财务稽核");
        pubAuditLogEntityTwo.setAuditorId("1");
        pubAuditLogEntityTwo.setAuditor("系统管理员");
        pubAuditLogEntityTwo.setAmt(jsonObject.getString("je"));
        pubAuditLogEntityTwo.setRemark("国子系统审核通过");
        pubAuditLogEntityTwo.setAtype("通过");
        pubAuditLogEntityTwo.setBillId(maxMlId);
        pubAuditLogEntityTwo.setModname("OER");
        pubAuditLogEntityTwo.setFlowcode(jsonObject.getString("flowcode"));
        pubAuditLogEntityTwo.setGsdm(jsonObject.getString("gsdm"));
        pubAuditLogEntityTwo.setKjnd(jsonObject.getString("kjnd"));
        pubAuditLogEntityTwo.setServdatetime("1");
        pubAuditLogEntityTwo.setAdatetime("1");
        //获取最大值logid
        PubAuditLogEntity pubAuditLogEntityLogids = iPubAuditLogDao.query(pubAuditLogEntityTwo, "PubAuditLogEntity_list_base_max");
        pubAuditLogEntityTwo.setLogId(pubAuditLogEntityLogids.getLogId());
        //获取最大值logseq
        PubAuditLogEntity pubAuditLogEntityLogseqs=iPubAuditLogDao.query(pubAuditLogEntityTwo,"PubAuditLogEntity_list_base_logseq");
        pubAuditLogEntityTwo.setLogseq(pubAuditLogEntityLogseqs.getLogseq());
        pubAuditLogEntityList.add(pubAuditLogEntity);
        pubAuditLogEntityList.add(pubAuditLogEntityTwo);*/

        pubAuditLogEntityList.add(pubAuditLogEntity);
        return pubAuditLogEntityList;
    }
    /**
     * 新增日志表PubAuditLog
     * @param entity
     * @param maxMlId
     */
    public List<PubAuditLogEntity> setPubAuditLog(OerDjmlEntity entity,String maxMlId){
        List<PubAuditLogEntity> pubAuditLogEntityList=new ArrayList<>();
        //拼接送审参数
        PubAuditLogEntity pubAuditLogEntity = new PubAuditLogEntity();
        pubAuditLogEntity.setBillname("费用报销[向导式]");
        pubAuditLogEntity.setFlowname("暂时费用报销审批流");
        pubAuditLogEntity.setNodeseq("-9");
        pubAuditLogEntity.setNodename("送审");
        pubAuditLogEntity.setAuditorId("1");
        pubAuditLogEntity.setAuditor("系统管理员");
        pubAuditLogEntity.setAmt(entity.getJe());
        pubAuditLogEntity.setRemark("国子系统送审成功");
        pubAuditLogEntity.setAtype("国子系统通过");
        pubAuditLogEntity.setBillId(maxMlId);
        pubAuditLogEntity.setModname("OER");
        pubAuditLogEntity.setFlowcode(entity.getFlowcode());
        pubAuditLogEntity.setGsdm(entity.getGsdm());
        pubAuditLogEntity.setKjnd(entity.getKjnd());
        pubAuditLogEntity.setServdatetime("1");
        pubAuditLogEntity.setAdatetime("1");
        //获取最大值logid
        pubAuditLogEntity.setDataSourceCode(entity.getDataSourceCode());
        PubAuditLogEntity pubAuditLogEntityLogid = iPubAuditLogDao.query(pubAuditLogEntity, "PubAuditLogEntity_list_base_max");
        pubAuditLogEntity.setLogId(pubAuditLogEntityLogid.getLogId());
        //获取最大值logseq
        PubAuditLogEntity pubAuditLogEntityLogseq=iPubAuditLogDao.query(pubAuditLogEntity,"PubAuditLogEntity_list_base_logseq");
        pubAuditLogEntity.setLogseq(pubAuditLogEntityLogseq.getLogseq());



        pubAuditLogEntityList.add(pubAuditLogEntity);
        return pubAuditLogEntityList;
    }

    /**
     * 更新主表摘要内容
     * @param jsonObject
     * @return
     */
    private OerDjmlEntity updateOerDjmlZy(JSONObject jsonObject,String maxMlId){
        OerDjmlEntity oerDjml=new OerDjmlEntity();
        oerDjml.setZy(jsonObject.getString("zy"));
        oerDjml.setGsdm(jsonObject.getString("gsdm"));
        oerDjml.setKjnd(jsonObject.getString("kjnd"));
        oerDjml.setDjlxId(jsonObject.getString("djlxId"));
        oerDjml.setMlId(maxMlId);
        return oerDjml;
    }

    /*****
     * 根据预算指标，生成指标生成指标使用记录
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 16:43
     * @Param [djnrEntity]
     * @return com.hzya.frame.online.expense.insert.oerYszb.entity.oerYszbEntity
     **/
    private GbiZbsyrecEntity creteOerYszbEntity(JSONObject jsonObject,OerDjnrEntity djnrEntity) {
        GbiZbsyrecEntity   yszbEntity = new GbiZbsyrecEntity();
        BeanUtil.copyProperties(djnrEntity,yszbEntity);
        yszbEntity.setModule(djnrEntity.getModule());
        yszbEntity.setDjlx(djnrEntity.getDjlxId());
        yszbEntity.setDjId(djnrEntity.getMlId());
        yszbEntity.setDjflh(djnrEntity.getDjflh());
        yszbEntity.setDjflmx(djnrEntity.getMlId());
        yszbEntity.setDjywrq(jsonObject.getString("djdate"));
        //yszbEntity.setDjzt("1");//审核中
        yszbEntity.setDjzt("2");//已审核
        yszbEntity.setJhId(djnrEntity.getZbId());
        yszbEntity.setDjje(djnrEntity.getJe());
        yszbEntity.setSl("0");
        yszbEntity.setDjzy(djnrEntity.getZy());
        yszbEntity.setSzfx("1");
        yszbEntity.setZblb("MXZB");
        yszbEntity.setJdzb("0");
        yszbEntity.setCzlx("0");
        yszbEntity.setZzbz("0");
        return yszbEntity;
    }

    /*****
     * 根据预算指标，生成指标生成指标使用记录
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 16:43
     * @Param [djnrEntity]
     * @return com.hzya.frame.online.expense.insert.oerYszb.entity.oerYszbEntity
     **/
    private GbiZbsyrecEntity setOerYszbEntity(OerDjmlEntity entity,OerDjnrEntity djnrEntity) {
        GbiZbsyrecEntity   yszbEntity = new GbiZbsyrecEntity();
        BeanUtil.copyProperties(djnrEntity,yszbEntity);
        yszbEntity.setModule("OER");
        yszbEntity.setDjlx(djnrEntity.getDjlxId());
        yszbEntity.setDjId(djnrEntity.getMlId());
        yszbEntity.setDjflh(djnrEntity.getXh());
        yszbEntity.setDjflmx(djnrEntity.getMlId());
        yszbEntity.setDjywrq(entity.getDjdate());
        yszbEntity.setDjzt(entity.getZt());
        yszbEntity.setJhId(djnrEntity.getZbId());
        yszbEntity.setDjje(djnrEntity.getJe());
        yszbEntity.setSl("0");
        yszbEntity.setDjzy(djnrEntity.getZy());
        yszbEntity.setSzfx("1");
        yszbEntity.setZblb("MXZB");
        yszbEntity.setJdzb("0");
        yszbEntity.setCzlx("0");
        yszbEntity.setZzbz("0");
        return yszbEntity;
    }


    /****
     * 组装结算方式集合
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 16:08
     * @param  jsonObject 三方json数据, maxDjbh, maxMlId]
     * @return java.util.List<com.hzya.frame.online.expense.insert.oerDjjsfs.entity.oerDjjsfsEntity>
     **/
    private List<OerDjjsfsEntity> creatOerDjjsfsEntityList(JSONObject jsonObject, String maxDjbh, String maxMlId) {
        List<OerDjjsfsEntity> oerDjjsfsEntityList = null;
        JSONArray jsonArray = jsonObject.getJSONArray("oer_djjsfs_array");
        if(jsonArray.size() == 0){
            throw new BaseSystemException("报销单结算明细数据为空！请检查参数：oer_djjsfs_array");
        }else{
            oerDjjsfsEntityList = new ArrayList<>();
            for(Object object :jsonArray){
                String detailsStr = JSON.toJSONString(object);
                logger.info("当前明细行json数据："+detailsStr);
                JSONObject details = JSON.parseObject(detailsStr);
                OerDjjsfsEntity djjsfsEntity = details.toJavaObject(OerDjjsfsEntity.class);
                djjsfsEntity.setMlId(maxMlId);
                djjsfsEntity.setGsdm(jsonObject.getString("gsdm"));
                oerDjjsfsEntityList.add(djjsfsEntity);
            }

            return oerDjjsfsEntityList;
        }
    }
    /****
     * 组装结算方式集合
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 16:08
     * @param  entity 三方json数据, maxDjbh, maxMlId]
     * @return java.util.List<com.hzya.frame.online.expense.insert.oerDjjsfs.entity.oerDjjsfsEntity>
     **/
    private List<OerDjjsfsEntity> setOerDjjsfsEntityList(OerDjmlEntity entity, String maxDjbh, String maxMlId) {
        List<OerDjjsfsEntity> oerDjjsfsEntityList = entity.getOerDjjsfsEntityList();
        for (int i = 0; i < oerDjjsfsEntityList.size(); i++) {
            oerDjjsfsEntityList.get(i).setMlId(maxMlId);
            oerDjjsfsEntityList.get(i).setGsdm(entity.getGsdm());
        }
        return oerDjjsfsEntityList;

}

    /****
     * 根据报销明细生成预算指标数据
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 16:00
     * @param djnrEntity 报销明细数据, maxMlId 最大id
     * @return com.hzya.frame.online.expense.insert.oerYszb.entity.oerYszbEntity
     **/
    private OerYszbEntity createOerYszbEntity(OerDjnrEntity djnrEntity, String maxMlId) {
        OerYszbEntity oerYszbEntity = new OerYszbEntity();
        BeanUtil.copyProperties(djnrEntity,oerYszbEntity);
        oerYszbEntity.setDataId("0");
        oerYszbEntity.setZbdm("00000295");
        oerYszbEntity.setJhId("0");
        oerYszbEntity.setMlId(maxMlId);
        return oerYszbEntity;
    }

    /*****
     * 组装报销明细数据
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 15:40
     * @param jsonObject 三方json对象, maxDjbh 主表最大编号, maxMlId 组表最大ID]
     * @return java.util.List<com.hzya.frame.online.expense.insert.oerDjnr.entity.oerDjnrEntity>
     **/
    private List<OerDjnrEntity> creatOerDjnrEntity(JSONObject jsonObject, String maxDjbh, String maxMlId) {
        List<OerDjnrEntity> djnrEntityList = null;
        JSONArray jsonArray = jsonObject.getJSONArray("oer_djnr_array");
        if(jsonArray.size() == 0){
            throw new BaseSystemException("报销单明细数据为空！请检查参数：oer_djnr_array");
        }else{
            djnrEntityList = new ArrayList<>();
            for(Object object :jsonArray){
                String detailsStr = JSON.toJSONString(object);
                logger.info("当前明细行json数据："+detailsStr);
                JSONObject details = JSON.parseObject(detailsStr);
               /* //根据指标id查询指标信息
                GbiZbxmbEntity gbiZbxmbEntity=new GbiZbxmbEntity();
                gbiZbxmbEntity.setZbid(details.getString("zbid"));
                GbiZbxmbEntity gbiZbxmbEntitie = iGbiZbxmbDao.selectGbiZbxmb(gbiZbxmbEntity);
                    details.put("fzx7dm",gbiZbxmbEntitie.getFz7dm());
                    details.put("xmdm",gbiZbxmbEntitie.getXmdm());
                    details.put("fzx6dm",gbiZbxmbEntitie.getFz6dm());
                    details.put("bmmc",gbiZbxmbEntitie.getBmmc());
                    details.put("xmmc",gbiZbxmbEntitie.getXmmc());
                    details.put("fzx6mc",gbiZbxmbEntitie.getFz6mc());
                    details.put("fzx7mc",gbiZbxmbEntitie.getFz7mc());
                    details.put("bmdm",gbiZbxmbEntitie.getBmdm());*/
                OerDjnrEntity djnrEntity = details.toJavaObject(OerDjnrEntity.class);
                djnrEntity.setMlId(maxMlId);
                djnrEntity.setGsdm(jsonObject.getString("gsdm"));
                djnrEntityList.add(djnrEntity);
            }

            return djnrEntityList;
        }

    }

    /****
     * 组装主表数据
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 15:34
     * @param jsonObject 三方JSON对象, maxDjbh 最大单据号, maxMlId 最大id
     * @return com.hzya.frame.online.expense.insert.oerDjml.entity.oerDjmlEntity
     **/
    private OerDjmlEntity createMainData(JSONObject jsonObject, String maxDjbh, String maxMlId) {
        OerDjmlEntity oerDjmlEntity = jsonObject.toJavaObject(OerDjmlEntity.class);
        //审核中
        /*oerDjmlEntity.setDjbh(maxDjbh);
        oerDjmlEntity.setMlId(maxMlId);
        oerDjmlEntity.setZt("2");
        oerDjmlEntity.setFlowcode("000006");
        oerDjmlEntity.setCurshjd("-9");
        oerDjmlEntity.setNextshjd("999");
        oerDjmlEntity.setShrId("-1");*/
        //已审核
        oerDjmlEntity.setDjbh(maxDjbh);
        oerDjmlEntity.setMlId(maxMlId);
        oerDjmlEntity.setZt("3");
        oerDjmlEntity.setFlowcode("000006");
        oerDjmlEntity.setCurshjd("999");
        oerDjmlEntity.setNextshjd("-1");
        logger.info("主表数据组装完成："+JSON.toJSONString(oerDjmlEntity));
        return oerDjmlEntity;
    }

    public static String nullConvert(String str){
        if (null == str){
            return "";
        }
        return str;
    }

    /*****
     * @Content:测试data数据
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date  2023-06-29 15:09
     * @Param []
     * @return com.alibaba.fastjson.JSONObject
     **/
    private JSONObject createTestData( ) {
        JSONObject main = new JSONObject();
        //公司代码
        main.put("gsdm","001");
        //会计年度
        main.put("kjnd","2023");
        //单据类型ID默认 102
        main.put("djlxid","102");
        //zt 默认 1
        main.put("zt","1");
        //制单人代码
        main.put("crerdm","1");
        //制单人名称
        main.put("crermc","系统管理员");
        //制单日期 crerdate
        main.put("crerdate","20230616");
        //流程编码 flowcode 流程编码，默认空
        main.put("flowcode","");

        //默认空
        main.put("curshjd","");
        //默认 -9
        main.put("nextshjd","-9");
        //默认 -1
        main.put("shrid","-1");
        //默认空
        main.put("shr","-1");
        //默认空
        main.put("shrq","-1");
        //结算方式默认空
        main.put("jsfs","");
        //单据编号 系统生成
        main.put("djbh","bxd202306160003");
        //单据日期
        main.put("djdate","20230616");
        //附件数 默认0
        main.put("fjs",0);
        //部门代码
        main.put("bmdm",30);
        //部门名称
        main.put("bmmc","学生处");
        //报销人代码
        main.put("grdm","2006001019");
        //报销人名称
        main.put("grmc","方烨枫");
        //联系电话
        main.put("tel","12345678910");
        //预借金额
        main.put("yjje",0);
        //退还金额
        main.put("thje",0);
        //补领金额
        main.put("blje",0);
        //报销金额
        main.put("je",0);
        //补领金额
        main.put("whje",0);
        //金额大写
        main.put("jedx","肆元壹角贰分");
        //摘要
        main.put("zy","测试单据");

        //报销明细
        //oer_djnr
        //结算方式
        //oer_djjsfs
        //报销明细集合
        JSONArray oer_djnrArray = new JSONArray();

        //报销明细行
        JSONObject djnr = new JSONObject();
        //序号
        djnr.put("xh","1");
        //主表ID，默认主表
        djnr.put("mlid","");
        //公司代码，默认主表
        djnr.put("gsdm","");
        //会计年度，默认主表
        djnr.put("kjnd","2023");
        //单据类型，默认主表
        djnr.put("djlxid","102");
        //待确认
        djnr.put("bnxid","148");
        //指标ID
        djnr.put("zbid","89");
        //摘要
        djnr.put("zy","测试使用，不做处理");
        //附件数，应该是不用的
        djnr.put("fjs","0");
        //金额
        djnr.put("je","4.12");
        //辅助项6代码
        djnr.put("fzx6dm","509040101");
        //辅助项6名称
        djnr.put("fzx6mc","行政）办公耗材");
        //经费部门代码
        djnr.put("bmdm","30");
        //经费部门名称
        djnr.put("bmmc","学生处");
        //项目代码
        djnr.put("xmdm","00");
        //项目名称
        djnr.put("xmmc","部门日常经费");
        //经费类型代码
        djnr.put("fzx7dm","702");
        //经费名称名称
        djnr.put("fzx7mc","自筹资金");
        //科目代码
        djnr.put("kmdm","10101");
        //科目名称
        djnr.put("kmmc","人民币");
        //待确认
        djnr.put("kzzbid","");


        oer_djnrArray.add(djnr);
        //添加报销明细到集合
        main.put("oer_djnr_array",oer_djnrArray);

        //结算方式对象
        JSONObject jsfs = new JSONObject();

        //序号
        jsfs.put("xh","1");
        //主表ID，默认主表
        jsfs.put("mlid","2023060163");
        //公司代码，默认主表
        jsfs.put("gsdm","2023060163");
        //会计年度，默认主表
        jsfs.put("kjnd","2023");
        //单据类型，默认主表
        jsfs.put("djlxid","102");
        //结算方式代码
        jsfs.put("jsfsdm","01");
        //结算方式名称
        jsfs.put("jsfsdm","现金");
        //科目代码
        jsfs.put("kmdm","10101");
        //科目名称
        jsfs.put("kmmc","人民币");
        //收款人
        jsfs.put("skr","001[中石化公司]");
        //开户银行
        jsfs.put("khyh","中国人民银行长沙中心支行营业部");
        //银行账户
        jsfs.put("yhzh","");
        //公务卡号
        jsfs.put("gwkh","");
        //公务卡支付时间
        jsfs.put("gwkxfsj","");
        //支票号
        jsfs.put("zph","");
        //金额
        jsfs.put("je","4.12");
        //省份
        jsfs.put("province","43[湖南省]");
        //城市
        jsfs.put("city","5510[长沙市]");
        //银行
        jsfs.put("yh","001[中国人民银行]");
        //银行行号
        jsfs.put("yhhh","001551068617[中国人民银行长沙中心支行营业部]");
        //负责人
        jsfs.put("rytype","");

        //报销人代码
        jsfs.put("grdm","");
        //用途
        jsfs.put("yt","用途");
        //收款人编制
        jsfs.put("skrbz","");
        //结算方式集合
        JSONArray oer_djjsfs_array = new JSONArray();
        oer_djjsfs_array.add(jsfs);
        main.put("oer_djjsfs_array",oer_djjsfs_array);
        return main;
    }


    /**
     * @param jsonObject
     * @return java.lang.Object
     * @Author lvleigang
     * @Description 费用报销单处理
     * @Date 9:54 上午 2024/8/14
     **/
    @Override
    public Object handleOerDjml(JSONObject jsonObject) {
        OerDjmlEntity entity = getData("jsonStr", jsonObject, OerDjmlEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getDataSourceCode() == null || "".equals(entity.getDataSourceCode())) {
            return BaseResult.getFailureMessageEntity("数据源编码不允许为空");
        }
        String dataSourceCode = entity.getDataSourceCode();
        if (entity.getLclb() == null || "".equals(entity.getLclb())) {
            return BaseResult.getFailureMessageEntity("流程类别不允许为空");
        }
        if (entity.getZt() == null || "".equals(entity.getZt())) {
            return BaseResult.getFailureMessageEntity("状态不允许为空");
        }

        if(ColEventTypeEnum.ONSTART.getType().equals(entity.getLclb())){//流程发起
            return saveOrUpdateData(dataSourceCode,entity);
        }else if(ColEventTypeEnum.ONCANCEL.getType().equals(entity.getLclb())){//流程撤销
            if (entity.getDjbh() == null || "".equals(entity.getDjbh())) {
                return BaseResult.getFailureMessageEntity("单据编号不允许为空");
            }
            OerDjmlEntity oerDjmlAllEntity = new OerDjmlEntity();
            oerDjmlAllEntity.setDataSourceCode(dataSourceCode);
            oerDjmlAllEntity.setDjbh(entity.getDjbh());
            List<OerDjmlEntity> oerDjmlAllEntities = iOerDjmlDao.queryOerDjml(oerDjmlAllEntity);
            if(oerDjmlAllEntities != null && oerDjmlAllEntities.size() == 1){
                //修改状态
                oerDjmlAllEntity.setMlId(oerDjmlAllEntities.get(0).getMlId());
                oerDjmlAllEntity.setZt(entity.getZt());
                oerDjmlAllEntity.setCurshjd(entity.getCurshjd());
                oerDjmlAllEntity.setNextshjd(entity.getNextshjd());
                oerDjmlAllEntity.setSsrid(entity.getSsrid());
                oerDjmlAllEntity.setSsr(entity.getSsr());
                oerDjmlAllEntity.setSsrq(entity.getSsrq());
                oerDjmlAllEntity.setShrId(entity.getShrId());
                oerDjmlAllEntity.setShrq(entity.getShrq());
                iOerDjmlDao.updateOerDjml(oerDjmlAllEntity);
                //释放指标
                GbiZbsyrecAllEntity gbiZbsyrecAllEntity = new GbiZbsyrecAllEntity();
                gbiZbsyrecAllEntity.setDjlx(oerDjmlAllEntities.get(0).getDjlxId());
                gbiZbsyrecAllEntity.setDjid(oerDjmlAllEntities.get(0).getMlId());
                gbiZbsyrecAllEntity.setGsdm(oerDjmlAllEntities.get(0).getGsdm());
                gbiZbsyrecAllEntity.setKjnd(oerDjmlAllEntities.get(0).getKjnd());
                gbiZbsyrecAllEntity.setDjflmx(Integer.valueOf(oerDjmlAllEntities.get(0).getMlId()));
                gbiZbsyrecAllEntity.setModule("'OER'");
                gbiZbsyrecAllEntity.setDjzt("0");
                gbiZbsyrecAllEntity.setDataSourceCode(dataSourceCode);
                iOerDjmlDao.updateGbiZbsyrecByDjid(gbiZbsyrecAllEntity);
            }else {
                return BaseResult.getFailureMessageEntity("根据单据编号存在多条报销单");
            }
        }else if(ColEventTypeEnum.ONSTOP.getType().equals(entity.getLclb())){//流程终止
            if (entity.getDjbh() == null || "".equals(entity.getDjbh())) {
                return BaseResult.getFailureMessageEntity("单据编号不允许为空");
            }
            OerDjmlEntity oerDjmlAllEntity = new OerDjmlEntity();
            oerDjmlAllEntity.setDataSourceCode(dataSourceCode);
            oerDjmlAllEntity.setDjbh(entity.getDjbh());
            List<OerDjmlEntity> oerDjmlAllEntities = iOerDjmlDao.queryOerDjml(oerDjmlAllEntity);
            if(oerDjmlAllEntities != null && oerDjmlAllEntities.size() == 1){
                //修改状态
                oerDjmlAllEntity.setMlId(oerDjmlAllEntities.get(0).getMlId());
                oerDjmlAllEntity.setZt(entity.getZt());
                iOerDjmlDao.updateOerDjml(oerDjmlAllEntity);
                //释放指标
                GbiZbsyrecAllEntity gbiZbsyrecAllEntity = new GbiZbsyrecAllEntity();
                gbiZbsyrecAllEntity.setDjlx(oerDjmlAllEntities.get(0).getDjlxId());
                gbiZbsyrecAllEntity.setDjid(oerDjmlAllEntities.get(0).getMlId());
                gbiZbsyrecAllEntity.setGsdm(oerDjmlAllEntities.get(0).getGsdm());
                gbiZbsyrecAllEntity.setKjnd(oerDjmlAllEntities.get(0).getKjnd());
                gbiZbsyrecAllEntity.setDjflmx(Integer.valueOf(oerDjmlAllEntities.get(0).getMlId()));
                gbiZbsyrecAllEntity.setModule("'OER'");
                gbiZbsyrecAllEntity.setDjzt("0");
                gbiZbsyrecAllEntity.setDataSourceCode(dataSourceCode);
                iOerDjmlDao.updateGbiZbsyrecByDjid(gbiZbsyrecAllEntity);
            }else {
                return BaseResult.getFailureMessageEntity("根据单据编号存在多条报销单");
            }
        }else if(ColEventTypeEnum.ONPROCESSFINISHED.getType().equals(entity.getLclb())){//流程结束
            if (entity.getDjbh() == null || "".equals(entity.getDjbh())) {
                return BaseResult.getFailureMessageEntity("单据编号不允许为空");
            }
            OerDjmlEntity oerDjmlAllEntity = new OerDjmlEntity();
            oerDjmlAllEntity.setDataSourceCode(dataSourceCode);
            oerDjmlAllEntity.setDjbh(entity.getDjbh());
            List<OerDjmlEntity> oerDjmlAllEntities = iOerDjmlDao.queryOerDjml(oerDjmlAllEntity);
            if(oerDjmlAllEntities != null && oerDjmlAllEntities.size() == 1){
                //修改状态
                oerDjmlAllEntity.setMlId(oerDjmlAllEntities.get(0).getMlId());
                oerDjmlAllEntity.setZt(entity.getZt());
                oerDjmlAllEntity.setCurshjd(entity.getCurshjd());
                oerDjmlAllEntity.setNextshjd(entity.getNextshjd());
                iOerDjmlDao.updateOerDjml(oerDjmlAllEntity);
                //保存附件
                if(entity.getFileInfoList() != null && entity.getFileInfoList().size() > 0){
                    OerAnnexEntity delete = new OerAnnexEntity();
                    delete.setKjnd(oerDjmlAllEntities.get(0).getKjnd());
                    delete.setMlid(oerDjmlAllEntities.get(0).getMlId());
                    delete.setGsdm(oerDjmlAllEntities.get(0).getGsdm());
                    delete.setDataSourceCode(entity.getDataSourceCode());
                    oerAnnexDao.deleteAnnex(delete);
                    int no = 1;
                    for (FileInfoDTO fileInfo : entity.getFileInfoList()) {
                        try {
                            AttachmentFileEntity fileEntity = new AttachmentFileEntity();
                            fileEntity.setDataSourceCode(entity.getDataSourceCode());
                            String fileName = URLDecoder.decode(fileInfo.getFile_name(), "UTF-8");
                            fileEntity.setaTFileName(fileName);
                            fileEntity.setaTFile(fileInfo.getData());
                            saveAttachment(fileEntity);
                            //保存附件关系
                            OerAnnexEntity annexEntity = new OerAnnexEntity();
                            annexEntity.setDataSourceCode(entity.getDataSourceCode());
                            annexEntity.setMlid(oerDjmlAllEntities.get(0).getMlId());
                            annexEntity.setKjnd(oerDjmlAllEntities.get(0).getKjnd());
                            annexEntity.setGsdm(oerDjmlAllEntities.get(0).getGsdm());
                            annexEntity.setAnnexName(fileName);
                            annexEntity.setAnnexSize(Convert.toLong(fileInfo.getFile_size()));
                            annexEntity.setOnlyid(fileEntity.getaTGuid());
                            annexEntity.setXh(String.valueOf(no));
                            annexEntity.setAnnexid(queryMaxId(annexEntity));
                            if (null != annexEntity.getAnnexSize()){
                                int fileSize = annexEntity.getAnnexSize().intValue();
                                String showSize = "";
                                if (fileSize < 1000) {
                                    showSize = fileSize + "b";
                                } else if (1000 < fileSize && fileSize < 1000000) {
                                    showSize = (fileSize / 1000) + " KB";
                                } else {
                                    showSize = (fileSize / 1000000) + " MB";
                                }
                                annexEntity.setShowSize(showSize);
                            }

                            annexEntity.setFjType("其它");
                            oerAnnexDao.saveData(annexEntity);
                            no++;
                        }catch (Exception e){
                            logger.error("保存附件到grp出错:{}",e);
                        }
                    }
                }
            }else {
                return BaseResult.getFailureMessageEntity("根据单据编号存在多条报销单");
            }
        }else {
            return BaseResult.getFailureMessageEntity("流程类别错误");
        }
        return BaseResult.getSuccessMessageEntity("处理成功");
    }

    public String queryMaxId(OerAnnexEntity entity)  {
        if (null == entity){
            entity = new OerAnnexEntity();
        }
        if (StrUtil.isEmpty(entity.getKjnd())){
            entity.setKjnd(String.valueOf(DateUtil.year(new Date())));
        }
        OerAnnexEntity max = oerAnnexDao.queryMaxId(entity);
        if (null != max){
            Long max_value = Long.valueOf(max.getMaxAnnexid());
            return String.valueOf(max_value+1);
        }
        return null;
    }
    public void saveAttachment(AttachmentFileEntity entity) {
        entity.setaTGuid("A1:"+ IdUtil.fastUUID());
        String date = DateUtil.format(new Date(), "yyyyMMdd HH:mm:ss");
        entity.setCreateDate(date);
        entity.setUpdateDate(date);
        String fileName = entity.getaTFileName();
        if (StrUtil.isNotEmpty(fileName)){
            int index = fileName.lastIndexOf(".");
            if (index > 0){
                String suffix = fileName.substring(index);
                entity.setaTExtName(suffix);
                String prefix = fileName.substring(0,index);
                entity.setaTFileName(prefix);
            }
        }
        attachmentFileDao.saveData(entity);
    }
    /**
     * 保存方法前，先调这个方法 组装参数
     *
     * @param entity
     * @return
     */
    public SysExtensionApiEntity saveExpensePre(SysExtensionApiEntity entity) {
        try {
            String bodys = entity.getBodys();
            Map<String, String> headers = entity.getHeaders();
            String eventType = headers.get("eventType");
            String formmainTableName = headers.get("formmainTableName");
            String forsonTableName = headers.get("forsonTableName");
            String djlxid = headers.get("djlxid");
            String flowcode = headers.get("flowcode");
            JSONObject bodyObj =  JSONObject.parseObject(bodys);
            JSONObject seeyonData = bodyObj.getJSONObject("businessDataStr");
            if (null != seeyonData){
                /**
                 * 流程发起 保存/更新单据 要全部数据
                 * 流程撤销 只更新状态，传单号和状态就好了
                 * 流程终止 只更新状态，传单号和状态就好了
                 * 流程结束 更新状态 并上传附件
                 */
                JSONObject formmainData = seeyonData.getJSONObject(formmainTableName);
                JSONArray forsonData = seeyonData.getJSONArray(forsonTableName);
                JSONObject forjsonData0 = forsonData.getJSONObject(0);
                OerDjmlEntity djml = new OerDjmlEntity();
                djml.setDjbh(formmainData.getString("field0001"));
                //流程发起
                if (ColEventTypeEnum.ONSTART.getType().equals(eventType)){
                    djml.setGsdm(forjsonData0.getString("field0084"));
                    djml.setKjnd(forjsonData0.getString("field0082"));
                    djml.setDjlxId(djlxid);
                    djml.setZt("2");
                    djml.setCrerdm(formmainData.getString("field0107"));
                    djml.setCrermc("");
                    djml.setCrerdate(formmainData.getString("startDate"));
                    djml.setDjdate(formmainData.getString("field0002"));
                    djml.setJe(formmainData.getString("field0080"));
                    djml.setJedx( Convert.numberToChinese(Double.valueOf(formmainData.getString("field0080")),true));
                    djml.setYjje("0.00");
                    djml.setThje("0.00");
                    djml.setBlje(formmainData.getString("field0080"));
                    djml.setFjs( formmainData.getString("field0004"));
                    djml.setZy( formmainData.getString("field0009"));
                    //部门代码
                    djml.setBmdm( formmainData.getString("field0006"));
                    djml.setBmmc( formmainData.getString("field0006"));
                    //项目代码
                    djml.setXmdm(forjsonData0.getString("field0074"));
                    djml.setXmmc(forjsonData0.getString("field0075"));
                    //个人代码
                    djml.setGrdm(formmainData.getString("field0108"));
                    djml.setGrmc("");
                    //经济代码
                    djml.setJjdm("");
                    djml.setJjmc("");
                    //银行帐号 开户银行
                    djml.setYhzh(forjsonData0.getString("field0079"));
                    djml.setKhyh(forjsonData0.getString("field0078"));
                    //当前审核节点、下个审核节点 ,不在grp审批，是不是不用填了
                    djml.setCurshjd("-9");
                    djml.setNextshjd("999");
                    djml.setFlowcode(flowcode);
                    djml.setJsfs(spliceStr(forjsonData0.getString("field0095"),forjsonData0.getString("field0094")));
                    //电话，oa上没有
                    djml.setTel(formmainData.getString("field0110"));
                    djml.setClf_ccr(formmainData.getString("field0010"));
                    //送审日期
                    djml.setSsrq( DateUtil.format(formmainData.getDate("startDate"),"yyyyMMddHHmmssSSS"));
                    djml.setSsrid("");
                    djml.setSsr("");

                    //报销明细
                    List<OerDjnrEntity> djnrList = new ArrayList<>();
                    //结算方式
                    List<OerDjjsfsEntity> jsfsList = new ArrayList<>();
                    //预算指标
                    List<OerYszbEntity> yszbList = new ArrayList<>();
                    //指标记录
                    int xh = 1;
                    for (int i=0; i<forsonData.size();i++) {
                        JSONObject forson = forsonData.getJSONObject(i);
                        String gsdm = forson.getString("field0084");
                        String kjnd = forson.getString("field0082");
                        String je = forson.getString("field0032");
                        //单据内容
                        OerDjnrEntity djnr = new OerDjnrEntity();
                        djnr.setXh(String.valueOf(xh));
                        djnr.setGsdm(gsdm);
                        djnr.setKjnd(kjnd);
                        djnr.setDjlxId(djlxid);
                        djnr.setBnxId(headers.get("bxmx_bnxid"));
                        djnr.setJe(je);
                        djnr.setBmdm(forson.getString("field0088"));
                        djnr.setBmmc(forson.getString("field0087"));
                        djnr.setXmdm(forson.getString("field0074"));
                        djnr.setXmmc(forson.getString("field0075"));
                        djnr.setJjdm("");
                        djnr.setJjmc("");
                        //grp库里有，不知道是什么 1001基本支出 2001项目支出（网银）
                        djnr.setFzx8dm("");
                        djnr.setFzx8mc("");
                        //指标id
                        djnr.setZbId(forson.getString("field0085"));
                        djnr.setJflxdm("");
                        djnr.setJflxmc("");
                        djnr.setZy(forson.getString("field0030"));
                        djnr.setClf_startdate(forson.getString("field0016"));
                        djnr.setClf_enddate(forson.getString("field0017"));
                        djnr.setClf_ccdd(forson.getString("field0019"));
                        djnr.setClf_ccksd(forson.getString("field0018"));
                        djnr.setClf_djzs(djml.getFjs());
                        djnr.setClf_ccts(forson.getString("field0023"));
                        djnr.setClf_ccrs(forson.getString("field0021"));
                        djnr.setClf_zw(forson.getString("field0092"));
                        djnr.setClf_jtgj(forson.getString("field0020"));
                        djnr.setClf_jtf(forson.getString("field0024"));
                        djnr.setClf_zsbz(forson.getString("field0077"));
                        djnr.setClf_zsf(forson.getString("field0025"));
                        //伙食补助是 标准金额
                        djnr.setClf_hsbz(forson.getString("field0026"));
                        //伙食费是 实际报销的金额
                        djnr.setClf_hsf(forson.getString("field0026"));
                        djnr.setClf_jtbz(forson.getString("field0024"));
                        djnr.setClf_qtf(forson.getString("field0028"));
                        djnr.setFjs(djml.getFjs());
                        djnrList.add(djnr);
                        //结算方式
                        OerDjjsfsEntity jsfs = new OerDjjsfsEntity();
                        jsfs.setGsdm(gsdm);
                        jsfs.setKjnd(kjnd);
                        jsfs.setDjlxId(djlxid);
                        jsfs.setBnxid(headers.get("jsfs_bnxid"));
                        jsfs.setXh(String.valueOf(xh));
                        jsfs.setJsfsdm(forson.getString("field0095"));
                        jsfs.setJsfsmc(forson.getString("field0094"));
                        jsfs.setKmdm(forson.getString("field0089"));
                        jsfs.setKmmc(forson.getString("field0066"));
                        jsfs.setSkr(forson.getString("field0096"));
                        jsfs.setKhyh(forson.getString("field0078"));
                        jsfs.setYhzh(forson.getString("field0079"));
                        jsfs.setJe(je);
                        jsfs.setYh("");
                        jsfs.setYhhh("");
                        jsfs.setProvince("");
                        jsfs.setCity("");
                        //支付方式为个人、公务卡时 可以选择 经办人、负责人、其他
                        jsfs.setRytype("");
                        //oa没有
                        jsfs.setYt(forson.getString("field0030"));
                        jsfsList.add(jsfs);
                        //预算指标
                        OerYszbEntity yszb = new OerYszbEntity();
                        BeanUtil.copyProperties(djnr,yszb);
                        yszb.setBnxId(headers.get("yszb_bnxid"));
                        yszb.setZbdm(forson.getString("field0085"));
                        yszb.setZy(forson.getString("field0111"));
                        yszb.setKmdm(forson.getString("field0089"));
                        yszb.setKmmc(forson.getString("field0066"));
                        yszbList.add(yszb);
                        xh++;
                    }
                    logger.info("报销单主表:{}",JSONObject.toJSONString(djml));
                    logger.info("报销单明细表:{}",JSONObject.toJSONString(djnrList));
                    logger.info("报销单结算方式:{}",JSONObject.toJSONString(jsfsList));
                    logger.info("报销单预算指标:{}",JSONObject.toJSONString(yszbList));
                    djml.setOerDjnrEntityList(djnrList);
                    djml.setOerYszbEntityList(yszbList);
                    String djmlStr = JSONObject.toJSONString(djml);
                    JSONObject param = new JSONObject(new LinkedHashMap<>());
                    param = JSONObject.parseObject(djmlStr);
                    param.put("lclb",eventType);
                    param.put("oerDjnrEntityList",djnrList);
                    param.put("oerYszbEntityList",yszbList);
                    param.put("oerDjjsfsEntityList",jsfsList);
                    //param.put("gbiZbsyrecEntitylist",null);
                    logger.info("差旅报销单报文：{}",param.toString());
                }
            }
        }catch (Exception ex ){
            logger.error("保存报销单之前组装参数出错",ex);
        }
        return null;
    }



    /**
     * @Author lvleigang
     * @Description  保存或修改主表以及指标
     * @Date 4:44 下午 2024/8/14
     * @param entity
     * @return java.lang.Object
     **/
    private Object saveOrUpdateData(String dataSourceCode,OerDjmlEntity entity) {
        //获取主表数据
        logger.info("开始处理数据:------>");
        String gsdm = entity.getGsdm();
        logger.info("根据公司代码查询最大单据编号,公司代码:------>"+gsdm);
        if(StrUtil.isEmpty(gsdm)){
            return BaseResult.getFailureMessageEntity("公司代码不能为空！请排查参数gsdm");
        }
        if(StrUtil.isEmpty(entity.getDjdate())){
            return BaseResult.getFailureMessageEntity("单据日期不能为空！请排查参数djdate");
        }
        if(entity.getOerDjnrEntityList() == null || entity.getOerDjnrEntityList().size() == 0 ){
            return BaseResult.getFailureMessageEntity("报销单明细数据为空！请检查参数");
        }
        if(entity.getOerDjjsfsEntityList() == null || entity.getOerDjjsfsEntityList().size() == 0 ){
            return BaseResult.getFailureMessageEntity("报销单结算明细数据为空！请检查参数");
        }
        boolean flag = false;
        String maxDjbh = null;
        String maxMlId = null;
        if (entity.getDjbh() == null || "".equals(entity.getDjbh())) {
            OerDjmlEntity oerDjmlEntity = new OerDjmlEntity();
            oerDjmlEntity.setDataSourceCode(dataSourceCode);
            oerDjmlEntity.setGsdm(gsdm);
            oerDjmlEntity.setDjdate(entity.getDjdate());
            oerDjmlEntity.setFph(nullConvert(entity.getFph()));
            maxDjbh = iOerDjmlDao.getMaxDjbgByGsdm(oerDjmlEntity);
            entity.setDjbh(maxDjbh);
        }else {
            OerDjmlEntity oerDjmlAllEntity = new OerDjmlEntity();
            oerDjmlAllEntity.setDataSourceCode(dataSourceCode);
            oerDjmlAllEntity.setDjbh(entity.getDjbh());
            List<OerDjmlEntity> oerDjmlAllEntities = iOerDjmlDao.queryOerDjml(oerDjmlAllEntity);
            if(oerDjmlAllEntities != null && oerDjmlAllEntities.size() == 1){
                flag = true;
                maxDjbh = oerDjmlAllEntities.get(0).getDjbh();
                maxMlId = oerDjmlAllEntities.get(0).getMlId();
            }
        }


        if(!flag){
            //logger.info("获取最大单据编号");
            OerDjmlEntity oerDjmlEntity = new OerDjmlEntity();
            oerDjmlEntity.setDataSourceCode(dataSourceCode);
            oerDjmlEntity.setGsdm(gsdm);
            oerDjmlEntity.setDjdate(entity.getDjdate());
            oerDjmlEntity.setFph(nullConvert(entity.getFph()));
            //maxDjbh = iOerDjmlDao.getMaxDjbgByGsdm(oerDjmlEntity);
            maxDjbh = entity.getDjbh();
            logger.info("获取到最大单据编号:------>"+maxDjbh);
            //查询最大单据ID mlid
            maxMlId = iOerDjmlDao.getMaxMlIdByGsdm(oerDjmlEntity);
            logger.info("获取到最大单据ID MLID:------>"+maxMlId);
        }

        logger.info("组装单据主表数据开始:------>");
        OerDjmlEntity oerdjml = setMainData(entity,maxDjbh,maxMlId);
        logger.info("保存主表信息:------>");
        if(flag){
            oerdjml.setDataSourceCode(dataSourceCode);
            iOerDjmlDao.updateData(oerdjml);
            //删除明细
            OerDjnrEntity oerDjnrEntity = new OerDjnrEntity();
            oerDjnrEntity.setMlId(maxMlId);
            oerDjnrEntity.setGsdm(entity.getGsdm());
            oerDjnrEntity.setKjnd(entity.getKjnd());
            oerDjnrEntity.setDjlxId(entity.getDjlxId());
            oerDjnrEntity.setDataSourceCode(dataSourceCode);
            iOerDjnrDao.deleteData(oerDjnrEntity);
            //删除预算指标
            OerYszbEntity oerYszbEntity = new OerYszbEntity();
            oerYszbEntity.setGsdm(entity.getGsdm());
            oerYszbEntity.setKjnd(entity.getKjnd());
            oerYszbEntity.setMlId(maxMlId);
            oerYszbEntity.setDataSourceCode(dataSourceCode);
            iOerYszbDao.deleteData(oerYszbEntity);
            //删除预算指标记录
            GbiZbsyrecEntity oeryszb= new GbiZbsyrecEntity();
            oeryszb.setGsdm(entity.getGsdm());
            oeryszb.setKjnd(entity.getKjnd());
            oeryszb.setDjId(maxMlId);
            oeryszb.setDataSourceCode(dataSourceCode);
            iGbiZbsyrecDao.deleteData(oeryszb);
            //删除单据结算方式
            OerDjjsfsEntity oerDjjsfsEntity = new OerDjjsfsEntity();
            oerDjjsfsEntity.setMlId(maxMlId);
            oerDjjsfsEntity.setGsdm(entity.getGsdm());
            oerDjjsfsEntity.setDataSourceCode(dataSourceCode);
            iOerDjjsfsDao.deleteData(oerDjjsfsEntity);
            //删除日志
            //删除节点
        }else {
            oerdjml.setDataSourceCode(dataSourceCode);
            iOerDjmlDao.saveData(oerdjml);
        }

        logger.info("组装单据报销明细开始:------>");
        List<OerDjnrEntity> oerDjnrEntityList = setOerDjnrEntity(entity,maxDjbh,maxMlId);
        logger.info("保存报销明细开始:------>");
        if(oerDjnrEntityList != null && oerDjnrEntityList.size() > 0){
            for(OerDjnrEntity djnrEntity : oerDjnrEntityList){
                djnrEntity.setDataSourceCode(dataSourceCode);
                iOerDjnrDao.saveData(djnrEntity);
                logger.info("保存完报销明细后，根据明细数据生成预算指标数据:------>");
                OerYszbEntity yszbEntity = createOerYszbEntity(djnrEntity,maxMlId);
                logger.info("保存预算指标开始:------>");
                yszbEntity.setDataSourceCode(dataSourceCode);
                iOerYszbDao.saveData(yszbEntity);
                logger.info("保存预算指标记录:------>");
                GbiZbsyrecEntity oeryszb= setOerYszbEntity(entity,djnrEntity);
                oeryszb.setDataSourceCode(dataSourceCode);
                iGbiZbsyrecDao.saveData(oeryszb);
            }
        }

        logger.info("组装单据结算方式明细开始:------>");
        List<OerDjjsfsEntity> oerDjjsfsEntityList = setOerDjjsfsEntityList(entity,maxDjbh,maxMlId);
        logger.info("保存结算方式明细开始:------>");
        if(oerDjjsfsEntityList != null && oerDjjsfsEntityList.size() > 0){
            for(OerDjjsfsEntity oerdjjsfs :oerDjjsfsEntityList){
                oerdjjsfs.setDataSourceCode(dataSourceCode);
                iOerDjjsfsDao.saveData(oerdjjsfs);
            }
        }

        //保存日志表PubAuditLog
        List<PubAuditLogEntity> pubAuditLogEntityList = setPubAuditLog(entity, maxMlId);
        if(pubAuditLogEntityList != null&& pubAuditLogEntityList.size() > 0){
            for (PubAuditLogEntity pubAuditLog : pubAuditLogEntityList) {
                pubAuditLog.setDataSourceCode(dataSourceCode);
                iPubAuditLogDao.saveData(pubAuditLog);
            }
        }
        if(!flag){
            //保存节点PUB_OBJ_FLOW
            PubObjFlowEntity pubObjFlowEntity = setPubObjFlow(entity, maxMlId);
            pubObjFlowEntity.setDataSourceCode(dataSourceCode);
            iPubObjFlowDao.saveData(pubObjFlowEntity);
        }
        return BaseResult.getSuccessMessageEntity("保存报销单成功",maxDjbh);
    }

    /**
     * @Author lvleigang
     * @Description  设置报销单明细
     * @Date 3:39 下午 2024/8/15
     * @param entity
     * @param maxDjbh
     * @param maxMlId
     * @return java.util.List<com.hzya.frame.grpU8.nxproof.oerdjnr.entity.OerDjnrEntity>
     **/
    private List<OerDjnrEntity> setOerDjnrEntity(OerDjmlEntity entity, String maxDjbh, String maxMlId) {
        List<OerDjnrEntity> djnrEntityList = entity.getOerDjnrEntityList();
        if(djnrEntityList != null && djnrEntityList.size() > 0){
            for (int i = 0; i < djnrEntityList.size(); i++) {
                djnrEntityList.get(i).setMlId(maxMlId);
                djnrEntityList.get(i).setGsdm(entity.getGsdm());
            }
        }
        return djnrEntityList;
    }

    /**
     * @Author lvleigang
     * @Description  设置值
     * @Date 3:30 下午 2024/8/15
     * @param oerDjmlEntity
     * @param maxDjbh
     * @param maxMlId
     * @return com.hzya.frame.grpU8.nxproof.oerdjml.entity.OerDjmlEntity
     **/
    private OerDjmlEntity setMainData(OerDjmlEntity oerDjmlEntity, String maxDjbh, String maxMlId) {
        oerDjmlEntity.setDjbh(maxDjbh);
        oerDjmlEntity.setMlId(maxMlId);
        //oerDjmlEntity.setZt("3");
        //oerDjmlEntity.setFlowcode("000006");
        //oerDjmlEntity.setCurshjd("999");
        //oerDjmlEntity.setNextshjd("-1");
        logger.info("主表数据组装完成："+JSON.toJSONString(oerDjmlEntity));
        return oerDjmlEntity;
    }

    protected <T> T getData(String key, JSONObject jsonObject, Class<T> clz) {
        if (checkStr(jsonObject.getString(key))) {
            return jsonObject.getJSONObject(key).toJavaObject(clz);
        }
        return null;
    }
    protected Boolean checkStr(String str) {
        Boolean flag = true;
        if (str == null || "".equals(str)) {
            flag = false;
        }
        return flag;
    }
    /**
     * code和name拼接[]
     * @param code
     * @param name
     * @return 格式：03[公务卡]
     */
    private String spliceStr(String code,String name){
        String template = "{}[{}]";
        return StrUtil.format(template,code,name);
    }
}
