package com.hzya.frame.plugin.mdmDistribute.plugin;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.mdm.mdmModule.dao.IMdmModuleDao;
import com.hzya.frame.mdm.mdmModule.entity.MdmModuleEntity;
import com.hzya.frame.mdm.mdmModuleDb.entity.MdmModuleDbEntity;
import com.hzya.frame.mdm.mdmModuleDbFileds.entity.MdmModuleDbFiledsEntity;
import com.hzya.frame.mdm.mdmModuleDbFiledsRule.dao.IMdmModuleDbFiledsRuleDao;
import com.hzya.frame.mdm.mdmModuleDbFiledsRule.entity.MdmModuleDbFiledsRuleEntity;
import com.hzya.frame.mdm.mdmModuleDistribute.dao.IMdmModuleDistributeDao;
import com.hzya.frame.mdm.mdmModuleDistribute.entity.MdmModuleDistributeEntity;
import com.hzya.frame.mdm.mdmModuleDistributeDetail.dao.IMdmModuleDistributeDetailDao;
import com.hzya.frame.mdm.mdmModuleDistributeDetail.entity.MdmModuleDistributeDetailEntity;
import com.hzya.frame.mdm.mdmModuleDistributeTripartite.dao.IMdmModuleDistributeTripartiteDao;
import com.hzya.frame.mdm.mdmModuleDistributeTripartite.entity.MdmModuleDistributeTripartiteEntity;
import com.hzya.frame.mdm.mdmModuleSendLog.dao.IMdmModuleSendLogDao;
import com.hzya.frame.mdm.mdmModuleSendLog.entity.MdmModuleSendLogEntity;
import com.hzya.frame.mdm.service.IMdmServiceCache;
import com.hzya.frame.sys.sysenum.SysEnum;
import com.hzya.frame.sysnew.application.api.dao.ISysApplicationApiDao;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiEntity;
import com.hzya.frame.sysnew.application.dao.ISysApplicationDao;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.application.script.dao.ISysApplicationScriptDao;
import com.hzya.frame.sysnew.application.script.entity.SysApplicationScriptEntity;
import com.hzya.frame.sysnew.grovy.service.IGroovyIntegrationService;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.entity.IntegrationTaskLivingDetailsEntity;
import com.hzya.frame.sysnew.integtationTaskLivingDetails.service.IIntegrationTaskLivingDetailsService;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 主数据模版(MdmModule)表服务接口
 *
 * @author makejava
 * @since 2024-06-18 10:33:32
 */
public class MdmModulePluginInitializer extends PluginBaseEntity {
    Logger logger = LoggerFactory.getLogger(MdmModulePluginInitializer.class);
    @Resource
    private IMdmModuleDistributeDetailDao mdmModuleDistributeDetailDao;
    @Resource
    private IIntegrationTaskLivingDetailsService taskLivingDetailsService;
    @Resource
    private ISysApplicationApiDao sysApplicationApiDao;
    @Resource
    private ISysApplicationDao sysApplicationDao;
    @Resource
    private ISysApplicationScriptDao sysApplicationScriptDao;
    @Resource
    private IMdmModuleDistributeDao mdmModuleDistributeDao;
    @Resource
    private IGroovyIntegrationService groovyIntegrationService;
    @Resource
    private IMdmModuleDbFiledsRuleDao mdmModuleDbFiledsRuleDao;
    @Resource
    private IMdmModuleDao mdmModuleDao;
    @Resource
    private IMdmServiceCache mdmServiceCache;
    @Resource
    private IMdmModuleSendLogDao mdmModuleSendLogDao;
    @Resource
    private IMdmModuleDistributeTripartiteDao mdmModuleDistributeTripartiteDao;
    @Value("${zt.url}")
    private String url ;

    //多线程请求加锁 HttpRequest 构造方法是静态的
    private final Object lock = new Object();
    @Override
    public void initialize() {
        logger.info(getPluginLabel() + "執行初始化方法initialize()");
    }

    @Override
    public void destroy() {
        logger.info(getPluginLabel() + "執行銷毀方法destroy()");
    }

    @Override
    public String getPluginId() {
        return "MdmModulePlugin";
    }

    @Override
    public String getPluginName() {
        return "主数据下发";
    }

    @Override
    public String getPluginLabel() {
        return "MdmModulePlugin";
    }

    @Override
    public String getPluginType() {
        return "1";
    }

    @Override
    public JsonResultEntity executeBusiness(JSONObject requestJson) {
        try{
            //重试方法
            if (null != requestJson) {
                //如果这个id不为空，说明是重试的
                String id = requestJson.getString("integration_task_living_details_id");
                //执行重新发送
                if (StrUtil.isNotEmpty(id)) {
                    //查询日志表
                    IntegrationTaskLivingDetailsEntity taskDetailEntity = taskLivingDetailsService.get(id);
                    if (null != taskDetailEntity && JSONUtil.isTypeJSON(taskDetailEntity.getRootAppPk())){
                        //拿到这张表的源系统ID
                        JSONObject jsonObject = JSONObject.parseObject(taskDetailEntity.getRootAppPk());
                        Long mdmCode = jsonObject.getLong("mdmCode");//主数据编码
                        String documentRule = jsonObject.getString("documentRule");//行数据的单据规则编码
                        String distributeId = jsonObject.getString("distributeId");//发送表id
                        String type = jsonObject.getString("type");//发送类型，1、新增2、修改3、删除
                        if(mdmCode == null || documentRule == null || distributeId == null || type == null
                                || "".equals(mdmCode) || "".equals(documentRule) || "".equals(distributeId) || "".equals(type)){
                            taskDetailEntity.setResult("系统保存参数错误");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("系统保存参数错误");
                        }
                        String apiId = null;
                        String scriptId = null;
                        //查找对应数据，组装数据发送

                        //获取主数据信息
                        MdmModuleEntity mdmModuleEntity = mdmServiceCache.getMdmModuleEntity(mdmCode);
                        if(mdmModuleEntity == null || mdmModuleEntity.getId() == null ){
                            taskDetailEntity.setResult("主数据不存在");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("主数据不存在");

                        }

                        //获取主数据db
                        MdmModuleDbEntity mdmModuleDbEntity = new MdmModuleDbEntity();
                        mdmModuleDbEntity.setMdmId(mdmModuleEntity.getId());
                        List<MdmModuleDbEntity> mdmModuleDbEntities = mdmServiceCache.queryMdmModuleDb(mdmModuleDbEntity);
                        if(mdmModuleDbEntities == null || mdmModuleDbEntities.size() == 0){
                            taskDetailEntity.setResult("主数据数据源不存在");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("主数据数据源不存在");

                        }

                        //获取分发表
                        //获取分发的接口
                        MdmModuleDistributeEntity mdmModuleDistributeEntity = mdmModuleDistributeDao.get(distributeId);
                        if(mdmModuleDistributeEntity == null || mdmModuleDistributeEntity.getId() == null ){
                            taskDetailEntity.setResult("分发不存在");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("分发不存在");

                        }
                        // 启用停用 0、停用
                        if("0".equals(mdmModuleDistributeEntity.getEnabledState())){
                            taskDetailEntity.setResult("分发已停用");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("分发已停用");

                        }
                        MdmModuleDistributeDetailEntity mdmModuleDistributeDetailEntity = new MdmModuleDistributeDetailEntity() ;
                        mdmModuleDistributeDetailEntity.setDistributeId(distributeId);
                        mdmModuleDistributeDetailEntity.setSts("Y");
                        List<MdmModuleDistributeDetailEntity> mdmModuleDistributeDetailEntities = mdmModuleDistributeDetailDao.queryBase(mdmModuleDistributeDetailEntity);

                        // 启用停用 0、停用
                        //if("1".equals(mdmModuleDistributeEntity.getEnabledType())){
                        //    taskDetailEntity.setResult("分发为手动下发");
                        //    taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                        //    return BaseResult.getFailureMessageEntity("分发为手动下发");
                        //}
                        //1、新增2、修改3、删除
                        if("1".equals(type)){
                            apiId = mdmModuleDistributeEntity.getAddApi();
                            scriptId = mdmModuleDistributeEntity.getAddScript();
                        }else if("2".equals(type)){
                            apiId = mdmModuleDistributeEntity.getUpdateApi();
                            scriptId = mdmModuleDistributeEntity.getUpdateScript();

                        }else if("3".equals(type)){
                            apiId = mdmModuleDistributeEntity.getDeleteApi();
                            scriptId = mdmModuleDistributeEntity.getDeleteScript();
                        }
                        if(apiId == null || "".equals(apiId)){
                            taskDetailEntity.setResult("分发接口未选择，请先选择");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("分发接口未选择，请先选择");

                        }
                        SysApplicationScriptEntity scriptEntity = null;
                        if(scriptId != null && !"".equals(scriptId)){
                            scriptEntity = sysApplicationScriptDao.get(scriptId);
                            if(scriptEntity == null || scriptEntity.getId() == null ){
                                taskDetailEntity.setResult("分发接口脚本不存在");
                                taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                return BaseResult.getFailureMessageEntity("分发接口脚本不存在");
                            }
                        }
                        SysApplicationApiEntity apiEntity = sysApplicationApiDao.get(apiId);
                        if(apiEntity == null || apiEntity.getId() == null ){
                            taskDetailEntity.setResult("分发接口不存在");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("分发接口不存在");

                        }
                        SysApplicationEntity sysApplicationEntity = sysApplicationDao.get(apiEntity.getAppId());
                        if(sysApplicationEntity == null || sysApplicationEntity.getId() == null ){
                            taskDetailEntity.setResult("应用不存在");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("应用不存在");
                        }

                        //获取主数据db字段，以及字段的规则
                        MdmModuleDbFiledsEntity queryFild = new MdmModuleDbFiledsEntity();
                        queryFild.setMdmId(mdmModuleEntity.getId());
                        List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities = mdmServiceCache.queryMdmModuleDbFileds(queryFild);
                        MdmModuleDbFiledsRuleEntity queryFildRule = new MdmModuleDbFiledsRuleEntity();
                        queryFildRule.setMdmId(mdmModuleEntity.getId());
                        queryFildRule.setRuleCode("service");
                        List<MdmModuleDbFiledsRuleEntity> mdmModuleDbFiledsRuleEntities = mdmModuleDbFiledsRuleDao.queryBase(queryFildRule);

                        //获取主数据db对应的实体表的数据
                        JSONObject object = new JSONObject();
                        for (int i = 0; i < mdmModuleDbEntities.size(); i++) {
                            if("1".equals(mdmModuleDbEntities.get(i).getDbType())){
                                Map<String,Object> map = new HashMap<>();
                                map.put("tableName",mdmModuleDbEntities.get(i).getDbName());
                                map.put("documentRule",documentRule);
                                object = mdmModuleDao.queryMdmST(map);
                                object = toLowerCaseKeys(object);
                                if(object.getString("id") == null || "".equals(object.getString("id")) ){
                                    taskDetailEntity.setResult("当前数据不存在");
                                    taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                    return BaseResult.getFailureMessageEntity("当前数据不存在");
                                }
                                if(mdmModuleDistributeDetailEntities != null && mdmModuleDistributeDetailEntities.size() > 0){
                                    Map<String,Object> checkData = new HashMap<>();
                                    checkData.put("tableName",mdmModuleDbEntities.get(i).getDbName());
                                    checkData.put("documentRule",documentRule);
                                    checkData.put("mdmModuleDistributeDetailEntities",mdmModuleDistributeDetailEntities);
                                    JSONObject object1 = mdmModuleDao.queryMdmST(checkData);
                                    object1 = toLowerCaseKeys(object1);

                                    if(object1.getString("id") == null || "".equals(object1.getString("id")) ){
                                        taskDetailEntity.setResult("当前数据不符合规则不发送");
                                        taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                        return BaseResult.getFailureMessageEntity("当前数据不符合规则不发送");
                                    }
                                }
                                //查看主表是否有字段是关联的
                                if(mdmModuleDbFiledsRuleEntities != null && mdmModuleDbFiledsRuleEntities.size() > 0){
                                    for (int i1 = 0; i1 < mdmModuleDbFiledsRuleEntities.size(); i1++) {
                                        if(mdmModuleDbFiledsRuleEntities.get(i1).getDbId().equals(mdmModuleDbEntities.get(i).getId())){
                                            if(mdmModuleDbFiledsEntities != null && mdmModuleDbFiledsEntities.size() > 0){
                                                for (int i2 = 0; i2 < mdmModuleDbFiledsEntities.size(); i2++) {
                                                    if(mdmModuleDbFiledsRuleEntities.get(i1).getFiledId().equals(mdmModuleDbFiledsEntities.get(i2).getId())){
                                                        if(object.getString(mdmModuleDbFiledsEntities.get(i2).getEnName()) != null){
                                                            Map<String,Object> mapDetail = new HashMap<>();
                                                            mapDetail.put("tableName",mdmModuleDbFiledsRuleEntities.get(i1).getRuleValue());
                                                            String ids =  object.getString(mdmModuleDbFiledsEntities.get(i2).getEnName());
                                                            String[] idss = ids.split(",");
                                                            mapDetail.put("id", idss[idss.length-1]);
                                                            JSONObject objectDetail = mdmModuleDao.queryMdmST(mapDetail);
                                                            objectDetail = toLowerCaseKeys(objectDetail);
                                                            object.put(mdmModuleDbFiledsEntities.get(i2).getEnName(),objectDetail);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        for (int i = 0; i < mdmModuleDbEntities.size(); i++) {
                            if("2".equals(mdmModuleDbEntities.get(i).getDbType())){
                                Map<String,Object> map = new HashMap<>();
                                map.put("tableName",mdmModuleDbEntities.get(i).getDbName());
                                map.put("formmainId",object.getString("id"));
                                List<JSONObject> detail = mdmModuleDao.queryMdmSTDetail(map);
                                detail = toLowerCaseKeys(detail);

                                //查看主表是否有字段是关联的
                                if(detail != null && detail.size() > 0){
                                    if(mdmModuleDbFiledsRuleEntities != null && mdmModuleDbFiledsRuleEntities.size() > 0){
                                        for (int i1 = 0; i1 < mdmModuleDbFiledsRuleEntities.size(); i1++) {
                                            if(mdmModuleDbFiledsRuleEntities.get(i1).getDbId().equals(mdmModuleDbEntities.get(i).getId())){
                                                if(mdmModuleDbFiledsEntities != null && mdmModuleDbFiledsEntities.size() > 0){
                                                    for (int i2 = 0; i2 < mdmModuleDbFiledsEntities.size(); i2++) {
                                                        if(mdmModuleDbFiledsRuleEntities.get(i1).getFiledId().equals(mdmModuleDbFiledsEntities.get(i2).getId())){
                                                            for (int i3 = 0; i3 < detail.size(); i3++) {
                                                                if(detail.get(i3).getString(mdmModuleDbFiledsEntities.get(i2).getEnName()) != null){
                                                                    Map<String,Object> mapDetail = new HashMap<>();
                                                                    mapDetail.put("tableName",mdmModuleDbFiledsRuleEntities.get(i1).getRuleValue());
                                                                    String ids = detail.get(i3).getString(mdmModuleDbFiledsEntities.get(i2).getEnName());
                                                                    String[] idss = ids.split(",");
                                                                    mapDetail.put("id", idss[idss.length-1]);

                                                                    JSONObject objectDetail = mdmModuleDao.queryMdmST(mapDetail);
                                                                    objectDetail = toLowerCaseKeys(objectDetail);

                                                                    detail.get(i3).put(mdmModuleDbFiledsEntities.get(i2).getEnName(),objectDetail);
                                                                }

                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                object.put(mdmModuleDbEntities.get(i).getDbName(),detail);
                            }
                        }
                        //执行脚本
                        JSONObject groovy = new JSONObject();
                        JSONObject parameterJson = new JSONObject();
                        parameterJson.put("header",apiEntity.getHeaderIn());
                        parameterJson.put("body",apiEntity.getBodyIn());
                        parameterJson.put("query",apiEntity.getQueryIn());
                        parameterJson.put("data",object);

                        if (!"1".equals(type)) {//删除或者修改情况,查询三方id，有就设置，没有就设置空
                            //1、根据主数据id、数据id、应用ID默认查询主数据应用下发三方id表，只查询最新的一条数据
                            MdmModuleDistributeTripartiteEntity mdmModuleDistributeTripartiteEntity = new MdmModuleDistributeTripartiteEntity();
                            mdmModuleDistributeTripartiteEntity.setSts("Y");
                            mdmModuleDistributeTripartiteEntity.setMdmId(mdmModuleEntity.getId());
                            mdmModuleDistributeTripartiteEntity.setDataId(object.getString("id"));
                            mdmModuleDistributeTripartiteEntity.setAppId(sysApplicationEntity.getId());
                            mdmModuleDistributeTripartiteEntity = mdmModuleDistributeTripartiteDao.queryOneTripartite(mdmModuleDistributeTripartiteEntity);
                            String tripartiteId = "";
                            if(mdmModuleDistributeTripartiteEntity != null && mdmModuleDistributeTripartiteEntity.getTripartiteId() != null  ){
                                tripartiteId = mdmModuleDistributeTripartiteEntity.getTripartiteId();
                            }
                            parameterJson.put("tripartiteId", tripartiteId);
                        }
                        /**  head */
                        Map<String, String> header = null;
                        /**  query */
                        String querys = null;
                        /**  body */
                        String bodys = object.toJSONString();
                        if(scriptEntity != null && scriptEntity.getId() != null ){
                            groovy.put("code",scriptEntity.getScriptCode());
                            groovy.put("className",scriptEntity.getClassName());
                            groovy.put("name",scriptEntity.getScriptName());
                            groovy.put("methodStr",scriptEntity.getScriptData());
                            groovy.put("parameterJson",parameterJson);
                            JSONObject groovyStr = new JSONObject();
                            groovyStr.put("jsonStr",groovy);
                            try {
                                Object str = groovyIntegrationService.groovyScriptExecution(groovyStr);
                                JSONObject jsonResultEntity = JSONObject.parseObject(str.toString());
                                header = (Map<String, String>) jsonResultEntity.get("header");
                                querys = jsonResultEntity.getString("querys");
                                bodys = jsonResultEntity.getString("bodys");
                            }catch (Exception e){
                                taskDetailEntity.setResult("分发脚本转换错误");
                                taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                return BaseResult.getFailureMessageEntity("分发脚本转换错误");
                            }
                        }
                        Map<String, String> headers = new HashMap<>();
                        headers.put("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                        headers.put("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                        headers.put("appId",sysApplicationEntity.getAppId().toString());
                        headers.put("apiCode",apiEntity.getApiCode().toString());
                        if(header != null){
                            headers.putAll(header);
                        }
                        if (SysEnum.NEED_LOGIN.getValue().equals(apiEntity.getNeedLogin())) {
                            //找到登陆接口
                            SysApplicationApiEntity loginApi = sysApplicationApiDao.get(apiEntity.getAuthenticationPort());
                            if (null == loginApi) {
                                taskDetailEntity.setResult("发送错误,认证接口不存在");
                                taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                return BaseResult.getFailureMessageEntity("发送错误，认证接口不存在");
                            }
                            String rzquerys = getQuery(loginApi,null,null);
                            Map<String, String> headersa = new HashMap<>();
                            headersa.put("publicKey", "ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                            headersa.put("secretKey", "fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                            headersa.put("appId", sysApplicationEntity.getAppId().toString());
                            headersa.put("apiCode", loginApi.getApiCode().toString());
                            Map<String, String> rzheaders = getHeaders(loginApi,headersa,null);
                            String rzbodys = getBodys(loginApi,null,null);
                            JsonResultEntity rzjsonResultEntity = sendData(loginApi,rzheaders,rzbodys,rzquerys);
                            if (!rzjsonResultEntity.isFlag()) {
                                taskDetailEntity.setResult("发送错误,认证接口错误");
                                taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                return BaseResult.getFailureMessageEntity("发送错误:"+rzjsonResultEntity.getMsg());
                            }
                            JSONObject attritube = JSONObject.parseObject(rzjsonResultEntity.getAttribute().toString());
                            logger.info("认证接口返回信息："+ attritube.toJSONString());
                            querys = getQuery(apiEntity,querys,attritube);
                            headers = getHeaders(apiEntity,headers,attritube);

                            bodys = getBodys(apiEntity,bodys,attritube);
                        }
                        //组装数据发送
                        JsonResultEntity jsonResultEntity = sendData(apiEntity,headers,bodys,querys);
                        if(jsonResultEntity.isFlag()){
                            if ("1".equals(type)) {//保存三方返回id
                                if (scriptEntity != null && scriptEntity.getId() != null && scriptEntity.getBackScriptData() != null ) {
                                    JSONObject backScriptJson = new JSONObject();
                                    backScriptJson.put("data", jsonResultEntity.getAttribute());
                                    groovy.put("code", scriptEntity.getScriptCode()+"back");
                                    groovy.put("className", scriptEntity.getClassName()+"back");
                                    groovy.put("name", scriptEntity.getScriptName()+"back");
                                    groovy.put("methodStr", scriptEntity.getBackScriptData());
                                    groovy.put("parameterJson", backScriptJson);
                                    JSONObject groovyStr = new JSONObject();
                                    groovyStr.put("jsonStr", groovy);
                                    try {
                                        Object str = groovyIntegrationService.groovyScriptExecution(groovyStr);
                                        if(str != null){
                                            JSONObject backJsonResultEntity = JSONObject.parseObject(str.toString());
                                            if(backJsonResultEntity != null && backJsonResultEntity.getString("success") != null && "true".equals(backJsonResultEntity.getString("success"))){
                                                MdmModuleDistributeTripartiteEntity mdmModuleDistributeTripartiteEntity = new MdmModuleDistributeTripartiteEntity();
                                                mdmModuleDistributeTripartiteEntity.setCreate();
                                                mdmModuleDistributeTripartiteEntity.setMdmId(mdmModuleEntity.getId());
                                                mdmModuleDistributeTripartiteEntity.setDataId(object.getString("id"));
                                                mdmModuleDistributeTripartiteEntity.setAppId(sysApplicationEntity.getId());
                                                mdmModuleDistributeTripartiteEntity.setTripartiteId(backJsonResultEntity.getString("tripartiteId"));
                                                mdmModuleDistributeTripartiteDao.save(mdmModuleDistributeTripartiteEntity);
                                            }
                                        }
                                    } catch (Exception e) {
                                        logger.info("执行异常错误原因："+e);
                                        logger.error("新增返回脚本解析保存三方id错误"+jsonResultEntity.getAttribute());
                                        taskDetailEntity.setResult("新增返回脚本解析保存三方id错误");
                                        taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                                        return BaseResult.getFailureMessageEntity("发送错误");
                                    }
                                }
                            }
                            taskDetailEntity.setResult("发送成功");
                            taskLivingDetailsService.saveLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("发送成功");
                        }else {
                            taskDetailEntity.setResult("发送错误");
                            taskLivingDetailsService.updateLogFailToSuccess(taskDetailEntity);
                            return BaseResult.getFailureMessageEntity("发送错误");
                        }
                    }
                }else {//执行正常下发

                    //查询主数据
                    MdmModuleEntity queryMdmModuleEntity = new MdmModuleEntity();
                    queryMdmModuleEntity.setSts("Y");
                    List<MdmModuleEntity> mdmModuleEntities = mdmModuleDao.queryBase(queryMdmModuleEntity);
                    if(mdmModuleEntities == null || mdmModuleEntities.size() == 0){
                        return BaseResult.getSuccessMessageEntity("主数据未设置，不需要下发");
                    }
                    //查询下发的配置  没有直接跳过
                    for (int i = 0; i < mdmModuleEntities.size(); i++) {
                        Long mdmCode = mdmModuleEntities.get(i).getMdmCode();
                        MdmModuleDistributeEntity queryMdmModuleDistributeEntity = new MdmModuleDistributeEntity();
                        queryMdmModuleDistributeEntity.setMdmId(mdmModuleEntities.get(i).getId());
                        queryMdmModuleDistributeEntity.setEnabledType("1");
                        queryMdmModuleDistributeEntity.setEnabledState("1");
                        List<MdmModuleDistributeEntity> mdmModuleDistributeEntities = mdmModuleDistributeDao.queryBase(queryMdmModuleDistributeEntity);
                        if(mdmModuleDistributeEntities == null || mdmModuleDistributeEntities.size() == 0){
                            continue;
                        }
                        //查询主数据db
                        MdmModuleDbEntity queryMdmModuleDbEntity = new MdmModuleDbEntity();
                        queryMdmModuleDbEntity.setMdmId(mdmModuleEntities.get(i).getId());
                        List<MdmModuleDbEntity> mdmModuleDbEntities = mdmServiceCache.queryMdmModuleDb(queryMdmModuleDbEntity);
                        if(mdmModuleDbEntities == null || mdmModuleDbEntities.size() == 0){
                            continue;
                        }
                        //查询主数据字段
                        MdmModuleDbFiledsEntity queryFild = new MdmModuleDbFiledsEntity();
                        queryFild.setMdmId(mdmModuleEntities.get(i).getId());
                        List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities = mdmServiceCache.queryMdmModuleDbFileds(queryFild);
                        if(mdmModuleDbFiledsEntities == null || mdmModuleDbFiledsEntities.size() == 0){
                            continue;
                        }
                        //字段的规则
                        MdmModuleDbFiledsRuleEntity queryFildRule = new MdmModuleDbFiledsRuleEntity();
                        queryFildRule.setMdmId(mdmModuleEntities.get(i).getId());
                        queryFildRule.setRuleCode("service");
                        List<MdmModuleDbFiledsRuleEntity> mdmModuleDbFiledsRuleEntities = mdmModuleDbFiledsRuleDao.queryBase(queryFildRule);

                        //新增
                        doAdd(mdmModuleEntities.get(i).getId(),mdmCode,mdmModuleDbEntities,mdmModuleDistributeEntities,mdmModuleDbFiledsRuleEntities,mdmModuleDbFiledsEntities);
                        //修改
                        doUpdate(mdmModuleEntities.get(i).getId(),mdmCode,mdmModuleDbEntities,mdmModuleDistributeEntities,mdmModuleDbFiledsRuleEntities,mdmModuleDbFiledsEntities);
                        //删除
                        doDelete(mdmModuleEntities.get(i).getId(),mdmCode,mdmModuleDbEntities,mdmModuleDistributeEntities,mdmModuleDbFiledsRuleEntities,mdmModuleDbFiledsEntities);

                    }

                }
            }
            logger.info("执行成功");
            return BaseResult.getSuccessMessageEntity("执行成功");
        } catch (Exception e) {
            logger.error("执行失败{}",e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("执行成功");
    }

    private void doDelete(String mdmId,Long mainCode,List<MdmModuleDbEntity> mdmModuleDbEntities, List<MdmModuleDistributeEntity> mdmModuleDistributeEntities, List<MdmModuleDbFiledsRuleEntity> mdmModuleDbFiledsRuleEntities, List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities) throws Exception {
        //查询一千条数据
        String mainDb = null;
        List<JSONObject> objects = new ArrayList<>();
        for (int i2 = 0; i2 < mdmModuleDbEntities.size(); i2++) {
            if("1".equals(mdmModuleDbEntities.get(i2).getDbType())) {
                mainDb = mdmModuleDbEntities.get(i2).getDbName();
            }
        }
        if(mainDb == null){
            return;
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("tableName",mainDb);
        map1.put("dataStatus", "N");
        map1.put("deleteStatus", "0");
        map1.put("size", 50);
        objects = mdmModuleDao.queryMdmSTs(map1);
        objects = toLowerCaseKeys(objects);

        if(objects == null || objects.size() == 0){
            return;
        }
        for (int i1 = 0; i1 < mdmModuleDistributeEntities.size(); i1++) {
            //查询下发的配置
            MdmModuleDistributeDetailEntity mdmModuleDistributeDetailEntity = new MdmModuleDistributeDetailEntity() ;
            mdmModuleDistributeDetailEntity.setDistributeId(mdmModuleDistributeEntities.get(i1).getId());
            mdmModuleDistributeDetailEntity.setSts("Y");
            List<MdmModuleDistributeDetailEntity> mdmModuleDistributeDetailEntities = mdmModuleDistributeDetailDao.queryBase(mdmModuleDistributeDetailEntity);
            //查询这一千条数据是否符合规则
            Map<String, Object> map = new HashMap<>();
            map.put("tableName", mainDb);
            map.put("dataStatus", "N");
            map.put("deleteStatus", "0");
            map.put("mdmModuleDistributeDetailEntities", mdmModuleDistributeDetailEntities);
            map.put("ids", objects);
            List<JSONObject> doObjects = mdmModuleDao.queryMdmSTs(map);
            doObjects = toLowerCaseKeys(doObjects);

            if(doObjects == null || doObjects.size() == 0){
                continue;
            }
            if(mdmModuleDistributeEntities.get(i1).getDeleteApi() == null || "".equals(mdmModuleDistributeEntities.get(i1).getDeleteApi())){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","删除接口未设置",mainDb,objects.get(i).getString("id"),null,null,null,null,doObjects.get(i).toJSONString(),"3");
                }
                return ;
            }
            SysApplicationApiEntity apiEntity = sysApplicationApiDao.get(mdmModuleDistributeEntities.get(i1).getDeleteApi());
            if(apiEntity == null || apiEntity.getId() == null ){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","删除接口未找到",mainDb,objects.get(i).getString("id"),null,null,null,null,doObjects.get(i).toJSONString(),"3");
                }
                return ;
            }
            SysApplicationEntity sysApplicationEntity = sysApplicationDao.get(apiEntity.getAppId());
            if(sysApplicationEntity == null || sysApplicationEntity.getId() == null ){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","删除接口的应用未找到",mainDb,objects.get(i).getString("id"),null,null,apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"3");
                }
                return ;
            }

            SysApplicationScriptEntity scriptEntity = null;
            if(mdmModuleDistributeEntities.get(i1).getDeleteScript() != null && !"".equals(mdmModuleDistributeEntities.get(i1).getDeleteScript())){
                scriptEntity = sysApplicationScriptDao.get(mdmModuleDistributeEntities.get(i1).getDeleteScript());
                if(scriptEntity == null || scriptEntity.getId() == null ){
                    for (int i = 0; i < doObjects.size(); i++) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","删除接口脚本未找到",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"3");
                    }
                    return ;
                }
            }

            for (int i = 0; i < doObjects.size(); i++) {
                //查询发送日志是否已经有这条数据
                MdmModuleSendLogEntity mdmModuleSendLogEntity = new MdmModuleSendLogEntity();
                mdmModuleSendLogEntity.setTableName(mainDb+"_send_log");
                mdmModuleSendLogEntity.setFormmainId(doObjects.get(i).getString("id"));
                mdmModuleSendLogEntity.setSts("Y");
                mdmModuleSendLogEntity.setAppId(sysApplicationEntity.getId());
                mdmModuleSendLogEntity.setApiId(apiEntity.getId());
                //mdmModuleSendLogEntity.setDistributeId(mdmModuleDistributeEntities.get(i1).getId());
                mdmModuleSendLogEntity.setOptionType("3");
                Integer num = mdmModuleSendLogDao.getCount(mdmModuleSendLogEntity);
                if(num > 0){//已经过不发送
                    continue;
                }
                getDetailData(mdmModuleDbEntities,doObjects.get(i),mdmModuleDbFiledsRuleEntities,mdmModuleDbFiledsEntities);

                //执行脚本
                JSONObject groovy = new JSONObject();
                JSONObject parameterJson = new JSONObject();
                parameterJson.put("header",apiEntity.getHeaderIn());
                parameterJson.put("body",apiEntity.getBodyIn());
                parameterJson.put("query",apiEntity.getQueryIn());
                parameterJson.put("data",doObjects.get(i));

                //1、根据主数据id、数据id、应用ID默认查询主数据应用下发三方id表，只查询最新的一条数据
                MdmModuleDistributeTripartiteEntity mdmModuleDistributeTripartiteEntity = new MdmModuleDistributeTripartiteEntity();
                mdmModuleDistributeTripartiteEntity.setSts("Y");
                mdmModuleDistributeTripartiteEntity.setMdmId(mdmId);
                mdmModuleDistributeTripartiteEntity.setDataId(objects.get(i).getString("id"));
                mdmModuleDistributeTripartiteEntity.setAppId(sysApplicationEntity.getId());
                mdmModuleDistributeTripartiteEntity = mdmModuleDistributeTripartiteDao.queryOneTripartite(mdmModuleDistributeTripartiteEntity);
                String tripartiteId = "";
                if(mdmModuleDistributeTripartiteEntity != null && mdmModuleDistributeTripartiteEntity.getTripartiteId() != null  ){
                    tripartiteId = mdmModuleDistributeTripartiteEntity.getTripartiteId();
                }
                parameterJson.put("tripartiteId", tripartiteId);

                /**  head */
                Map<String, String> header = null;
                /**  query */
                String querys = null;
                /**  body */
                String bodys = doObjects.get(i).toJSONString();
                if(scriptEntity != null && scriptEntity.getId() != null ){
                    groovy.put("code",scriptEntity.getScriptCode());
                    groovy.put("className",scriptEntity.getClassName());
                    groovy.put("name",scriptEntity.getScriptName());
                    groovy.put("methodStr",scriptEntity.getScriptData());
                    groovy.put("parameterJson",parameterJson);
                    JSONObject groovyStr = new JSONObject();
                    groovyStr.put("jsonStr",groovy);
                    try {
                        Object str = groovyIntegrationService.groovyScriptExecution(groovyStr);
                        JSONObject jsonResultEntity = JSONObject.parseObject(str.toString());
                        header = (Map<String, String>) jsonResultEntity.get("header");
                        querys = jsonResultEntity.getString("querys");
                        bodys = jsonResultEntity.getString("bodys");
                    }catch (Exception e){
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","脚本处理失败",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"3");
                        continue;
                    }
                }
                Map<String, String> headers = new HashMap<>();
                headers.put("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                headers.put("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                headers.put("appId",sysApplicationEntity.getAppId().toString());
                headers.put("apiCode",apiEntity.getApiCode().toString());
                if(header != null){
                    headers.putAll(header);
                }
                if (SysEnum.NEED_LOGIN.getValue().equals(apiEntity.getNeedLogin())) {
                    //找到登陆接口
                    SysApplicationApiEntity loginApi = sysApplicationApiDao.get(apiEntity.getAuthenticationPort());
                    if (null == loginApi) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","发送错误,认证接口不存在",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                    String rzquerys = getQuery(loginApi,null,null);
                    Map<String, String> headersa = new HashMap<>();
                    headersa.put("publicKey", "ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                    headersa.put("secretKey", "fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                    headersa.put("appId", sysApplicationEntity.getAppId().toString());
                    headersa.put("apiCode", loginApi.getApiCode().toString());
                    Map<String, String> rzheaders = getHeaders(loginApi,headersa,null);
                    String rzbodys = getBodys(loginApi,null,null);
                    JsonResultEntity rzjsonResultEntity = sendData(loginApi,rzheaders,rzbodys,rzquerys);
                    if (!rzjsonResultEntity.isFlag()) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","发送错误,认证接口错误",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                    JSONObject attritube = JSONObject.parseObject(rzjsonResultEntity.getAttribute().toString());
                    querys = getQuery(apiEntity,querys,attritube);
                    headers = getHeaders(apiEntity,headers,attritube);
                    bodys = getBodys(apiEntity,bodys,attritube);
                }
                //组装数据发送
                JsonResultEntity jsonResultEntity = sendData(apiEntity,headers,bodys,querys);
                if(jsonResultEntity.isFlag()){
                    //保存日志
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"1","发送成功",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"3");
                    continue;
                }else {
                    //保存日志
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","转发失败:"+jsonResultEntity.getAttribute(),mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"3");
                    continue;
                }
            }

        }

        //所有下发发送完成，修改数据状态
        for (int i = 0; i < objects.size(); i++) {
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("tableName",mainDb);
            updateMap.put("dataStatus", "N");
            updateMap.put("deleteStatus", "1");
            updateMap.put("id", objects.get(i).getString("id"));
            mdmModuleDao.updateMdmSTs(updateMap);
        }
    }

    private void doUpdate(String mdmId,Long mainCode,List<MdmModuleDbEntity> mdmModuleDbEntities, List<MdmModuleDistributeEntity> mdmModuleDistributeEntities, List<MdmModuleDbFiledsRuleEntity> mdmModuleDbFiledsRuleEntities, List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities) throws Exception {
        //查询一千条数据
        String mainDb = null;
        List<JSONObject> objects = new ArrayList<>();
        for (int i2 = 0; i2 < mdmModuleDbEntities.size(); i2++) {
            if("1".equals(mdmModuleDbEntities.get(i2).getDbType())) {
                mainDb = mdmModuleDbEntities.get(i2).getDbName();
            }
        }
        if(mainDb == null){
            return;
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("tableName",mainDb);
        //map1.put("dataStatus", "F");
        map1.put("updateStatus", "0");
        map1.put("size", 50);
        objects = mdmModuleDao.queryMdmSTs(map1);
        objects = toLowerCaseKeys(objects);

        if(objects == null || objects.size() == 0){
            return;
        }
        for (int i1 = 0; i1 < mdmModuleDistributeEntities.size(); i1++) {
            //查询下发的配置
            MdmModuleDistributeDetailEntity mdmModuleDistributeDetailEntity = new MdmModuleDistributeDetailEntity() ;
            mdmModuleDistributeDetailEntity.setDistributeId(mdmModuleDistributeEntities.get(i1).getId());
            mdmModuleDistributeDetailEntity.setSts("Y");
            List<MdmModuleDistributeDetailEntity> mdmModuleDistributeDetailEntities = mdmModuleDistributeDetailDao.queryBase(mdmModuleDistributeDetailEntity);
            //查询这一千条数据是否符合规则
            Map<String, Object> map = new HashMap<>();
            map.put("tableName", mainDb);
            //map.put("dataStatus", "F");
            map.put("updateStatus", "0");
            map.put("mdmModuleDistributeDetailEntities", mdmModuleDistributeDetailEntities);
            map.put("ids", objects);
            List<JSONObject> doObjects = mdmModuleDao.queryMdmSTs(map);
            doObjects = toLowerCaseKeys(doObjects);

            if(doObjects == null || doObjects.size() == 0){
                continue;
            }
            if(mdmModuleDistributeEntities.get(i1).getUpdateApi() == null || "".equals(mdmModuleDistributeEntities.get(i1).getUpdateApi())){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","修改接口未设置",mainDb,objects.get(i).getString("id"),null,null,null,null,doObjects.get(i).toJSONString(),"2");
                }
                return ;
            }
            SysApplicationApiEntity apiEntity = sysApplicationApiDao.get(mdmModuleDistributeEntities.get(i1).getUpdateApi());
            if(apiEntity == null || apiEntity.getId() == null ){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","修改接口未查找到",mainDb,objects.get(i).getString("id"),null,null,null,null,doObjects.get(i).toJSONString(),"2");
                }
                return ;
            }
            SysApplicationEntity sysApplicationEntity = sysApplicationDao.get(apiEntity.getAppId());
            if(sysApplicationEntity == null || sysApplicationEntity.getId() == null ){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","应用未查找到",mainDb,objects.get(i).getString("id"),null,null,apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"2");
                }
                return ;
            }

            SysApplicationScriptEntity scriptEntity = null;
            if(mdmModuleDistributeEntities.get(i1).getUpdateScript() != null && !"".equals(mdmModuleDistributeEntities.get(i1).getUpdateScript())){
                scriptEntity = sysApplicationScriptDao.get(mdmModuleDistributeEntities.get(i1).getUpdateScript());
                if(scriptEntity == null || scriptEntity.getId() == null ){
                    for (int i = 0; i < doObjects.size(); i++) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","脚本未查找到",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"2");
                    }
                    return ;
                }
            }

            for (int i = 0; i < doObjects.size(); i++) {

                getDetailData(mdmModuleDbEntities,doObjects.get(i),mdmModuleDbFiledsRuleEntities,mdmModuleDbFiledsEntities);

                //执行脚本
                JSONObject groovy = new JSONObject();
                JSONObject parameterJson = new JSONObject();
                parameterJson.put("header",apiEntity.getHeaderIn());
                parameterJson.put("body",apiEntity.getBodyIn());
                parameterJson.put("query",apiEntity.getQueryIn());
                parameterJson.put("data",doObjects.get(i));
                //1、根据主数据id、数据id、应用ID默认查询主数据应用下发三方id表，只查询最新的一条数据
                MdmModuleDistributeTripartiteEntity mdmModuleDistributeTripartiteEntity = new MdmModuleDistributeTripartiteEntity();
                mdmModuleDistributeTripartiteEntity.setSts("Y");
                mdmModuleDistributeTripartiteEntity.setMdmId(mdmId);
                mdmModuleDistributeTripartiteEntity.setDataId(objects.get(i).getString("id"));
                mdmModuleDistributeTripartiteEntity.setAppId(sysApplicationEntity.getId());
                mdmModuleDistributeTripartiteEntity = mdmModuleDistributeTripartiteDao.queryOneTripartite(mdmModuleDistributeTripartiteEntity);
                String tripartiteId = "";
                if(mdmModuleDistributeTripartiteEntity != null && mdmModuleDistributeTripartiteEntity.getTripartiteId() != null  ){
                    tripartiteId = mdmModuleDistributeTripartiteEntity.getTripartiteId();
                }
                parameterJson.put("tripartiteId", tripartiteId);
                /**  head */
                Map<String, String> header = null;
                /**  query */
                String querys = null;
                /**  body */
                String bodys = doObjects.get(i).toJSONString();
                if(scriptEntity != null && scriptEntity.getId() != null ){
                    groovy.put("code",scriptEntity.getScriptCode());
                    groovy.put("className",scriptEntity.getClassName());
                    groovy.put("name",scriptEntity.getScriptName());
                    groovy.put("methodStr",scriptEntity.getScriptData());
                    groovy.put("parameterJson",parameterJson);
                    JSONObject groovyStr = new JSONObject();
                    groovyStr.put("jsonStr",groovy);
                    try {
                        Object str = groovyIntegrationService.groovyScriptExecution(groovyStr);
                        JSONObject jsonResultEntity = JSONObject.parseObject(str.toString());
                        header = (Map<String, String>) jsonResultEntity.get("header");
                        querys = jsonResultEntity.getString("querys");
                        bodys = jsonResultEntity.getString("bodys");
                    }catch (Exception e){
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","脚本处理失败",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"2");
                        continue;
                    }
                }
                Map<String, String> headers = new HashMap<>();
                headers.put("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                headers.put("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                headers.put("appId",sysApplicationEntity.getAppId().toString());
                headers.put("apiCode",apiEntity.getApiCode().toString());
                if(header != null){
                    headers.putAll(header);
                }
                if (SysEnum.NEED_LOGIN.getValue().equals(apiEntity.getNeedLogin())) {
                    //找到登陆接口
                    SysApplicationApiEntity loginApi = sysApplicationApiDao.get(apiEntity.getAuthenticationPort());
                    if (null == loginApi) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","发送错误,认证接口不存在",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                    String rzquerys = getQuery(loginApi,null,null);
                    Map<String, String> headersa = new HashMap<>();
                    headersa.put("publicKey", "ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                    headersa.put("secretKey", "fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                    headersa.put("appId", sysApplicationEntity.getAppId().toString());
                    headersa.put("apiCode", loginApi.getApiCode().toString());
                    Map<String, String> rzheaders = getHeaders(loginApi,headersa,null);
                    String rzbodys = getBodys(loginApi,null,null);
                    JsonResultEntity rzjsonResultEntity = sendData(loginApi,rzheaders,rzbodys,rzquerys);
                    if (!rzjsonResultEntity.isFlag()) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","发送错误,认证接口错误",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                    JSONObject attritube = JSONObject.parseObject(rzjsonResultEntity.getAttribute().toString());
                    querys = getQuery(apiEntity,querys,attritube);
                    headers = getHeaders(apiEntity,headers,attritube);
                    bodys = getBodys(apiEntity,bodys,attritube);
                }
                //组装数据发送
                JsonResultEntity jsonResultEntity = sendData(apiEntity,headers,bodys,querys);
                if(jsonResultEntity.isFlag()){
                    //保存日志
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"1","发送成功",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"2");
                    continue;
                }else {
                    //保存日志
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","转发失败:"+jsonResultEntity.getAttribute(),mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"2");
                    continue;
                }
            }
        }

        //所有下发发送完成，修改数据状态
        for (int i = 0; i < objects.size(); i++) {
            Map<String, Object> updateMap = new HashMap<>();
            updateMap.put("tableName",mainDb);
            //updateMap.put("dataStatus", "F");
            updateMap.put("updateStatus", "1");
            updateMap.put("id", objects.get(i).getString("id"));
            mdmModuleDao.updateMdmSTs(updateMap);
        }
    }

    /**
     * @Author lvleigang
     * @Description  处理新增数据
     * @Date 1:55 下午 2024/6/19
     * @param mdmModuleDbEntities
     * @param mdmModuleDistributeEntities
     * @return void
     **/
    private void doAdd(String mdmId,Long mainCode,List<MdmModuleDbEntity> mdmModuleDbEntities, List<MdmModuleDistributeEntity> mdmModuleDistributeEntities,List<MdmModuleDbFiledsRuleEntity> mdmModuleDbFiledsRuleEntities,List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities ) throws Exception {
        //查询一千条数据
        String mainDb = null;
        List<JSONObject> objects = new ArrayList<>();
        for (int i2 = 0; i2 < mdmModuleDbEntities.size(); i2++) {
            if("1".equals(mdmModuleDbEntities.get(i2).getDbType())) {
                mainDb = mdmModuleDbEntities.get(i2).getDbName();
            }
        }
        if(mainDb == null){
            return;
        }
        Map<String, Object> map1 = new HashMap<>();
        map1.put("tableName",mainDb);
        //map1.put("dataStatus", "Y");
        map1.put("addStatus", "0");
        map1.put("size", 50);
        objects = mdmModuleDao.queryMdmSTs(map1);
        objects = toLowerCaseKeys(objects);

        if(objects == null || objects.size() == 0){
            return;
        }
        for (int i1 = 0; i1 < mdmModuleDistributeEntities.size(); i1++) {
            //查询下发的配置
            MdmModuleDistributeDetailEntity mdmModuleDistributeDetailEntity = new MdmModuleDistributeDetailEntity() ;
            mdmModuleDistributeDetailEntity.setDistributeId(mdmModuleDistributeEntities.get(i1).getId());
            mdmModuleDistributeDetailEntity.setSts("Y");
            List<MdmModuleDistributeDetailEntity> mdmModuleDistributeDetailEntities = mdmModuleDistributeDetailDao.queryBase(mdmModuleDistributeDetailEntity);
            //查询这一千条数据是否符合规则
            Map<String, Object> map = new HashMap<>();
            map.put("tableName", mainDb);
            //map.put("dataStatus", "Y");
            map.put("addStatus", "0");
            map.put("mdmModuleDistributeDetailEntities", mdmModuleDistributeDetailEntities);
            map.put("ids", objects);
            List<JSONObject> doObjects = mdmModuleDao.queryMdmSTs(map);
            doObjects = toLowerCaseKeys(doObjects);

            if(doObjects == null || doObjects.size() == 0){
                continue;
            }
            if(mdmModuleDistributeEntities.get(i1).getAddApi() == null || "".equals(mdmModuleDistributeEntities.get(i1).getAddApi())){
                for (int i = 0; i < doObjects.size(); i++) {
                    //taskLivingDetailsService.saveLogToSuccess();
                    saveMdmModuleSendLogEntity( mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","新增接口未设置",mainDb,objects.get(i).getString("id"),null,null,null,null,doObjects.get(i).toJSONString(),"1");
                }
                return ;
            }
            SysApplicationApiEntity apiEntity = sysApplicationApiDao.get(mdmModuleDistributeEntities.get(i1).getAddApi());
            if(apiEntity == null || apiEntity.getId() == null ){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","新增接口未查找到",mainDb,objects.get(i).getString("id"),null,null,null,null,doObjects.get(i).toJSONString(),"1");
                }
                return ;
            }
            SysApplicationEntity sysApplicationEntity = sysApplicationDao.get(apiEntity.getAppId());
            if(sysApplicationEntity == null || sysApplicationEntity.getId() == null ){
                for (int i = 0; i < doObjects.size(); i++) {
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","应用未查找到",mainDb,objects.get(i).getString("id"),null,null,apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                }
                return ;
            }

            SysApplicationScriptEntity scriptEntity = null;
            if(mdmModuleDistributeEntities.get(i1).getAddScript() != null && !"".equals(mdmModuleDistributeEntities.get(i1).getAddScript())){
                scriptEntity = sysApplicationScriptDao.get(mdmModuleDistributeEntities.get(i1).getAddScript());
                if(scriptEntity == null || scriptEntity.getId() == null ){
                    for (int i = 0; i < doObjects.size(); i++) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","脚本未查找到",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                    }
                    return ;
                }
            }

            for (int i = 0; i < doObjects.size(); i++) {
                //查询是否已经手动发送过。只有新增校验，查询发送日志是否已经有这条数据
                MdmModuleSendLogEntity mdmModuleSendLogEntity = new MdmModuleSendLogEntity();
                mdmModuleSendLogEntity.setTableName(mainDb+"_send_log");
                mdmModuleSendLogEntity.setFormmainId(doObjects.get(i).getString("id"));
                mdmModuleSendLogEntity.setSts("Y");
                mdmModuleSendLogEntity.setDataType("1");
                mdmModuleSendLogEntity.setAppId(sysApplicationEntity.getId());
                mdmModuleSendLogEntity.setApiId(apiEntity.getId());
                //mdmModuleSendLogEntity.setDistributeId(mdmModuleDistributeEntities.get(i1).getId());
                mdmModuleSendLogEntity.setOptionType("1");
                Integer num = mdmModuleSendLogDao.getCount(mdmModuleSendLogEntity);
                if(num > 0){//已经新增过不发送
                    continue;
                }
                getDetailData(mdmModuleDbEntities,doObjects.get(i),mdmModuleDbFiledsRuleEntities,mdmModuleDbFiledsEntities);

                //执行脚本
                JSONObject groovy = new JSONObject();
                JSONObject parameterJson = new JSONObject();
                parameterJson.put("header",apiEntity.getHeaderIn());
                parameterJson.put("body",apiEntity.getBodyIn());
                parameterJson.put("query",apiEntity.getQueryIn());
                parameterJson.put("data",doObjects.get(i));
                //1、根据主数据id、数据id、应用ID默认查询主数据应用下发三方id表，只查询最新的一条数据
                MdmModuleDistributeTripartiteEntity mdmModuleDistributeTripartiteEntity1 = new MdmModuleDistributeTripartiteEntity();
                mdmModuleDistributeTripartiteEntity1.setSts("Y");
                mdmModuleDistributeTripartiteEntity1.setMdmId(mdmId);
                mdmModuleDistributeTripartiteEntity1.setDataId(objects.get(i).getString("id"));
                mdmModuleDistributeTripartiteEntity1.setAppId(sysApplicationEntity.getId());
                mdmModuleDistributeTripartiteEntity1 = mdmModuleDistributeTripartiteDao.queryOneTripartite(mdmModuleDistributeTripartiteEntity1);
                String tripartiteId = "";
                if(mdmModuleDistributeTripartiteEntity1 != null && mdmModuleDistributeTripartiteEntity1.getTripartiteId() != null  ){
                    tripartiteId = mdmModuleDistributeTripartiteEntity1.getTripartiteId();
                }
                parameterJson.put("tripartiteId", tripartiteId);
                /**  head */
                Map<String, String> header = null;
                /**  query */
                String querys = null;
                /**  body */
                String bodys = doObjects.get(i).toJSONString();
                if(scriptEntity != null && scriptEntity.getId() != null ){
                    groovy.put("code",scriptEntity.getScriptCode());
                    groovy.put("className",scriptEntity.getClassName());
                    groovy.put("name",scriptEntity.getScriptName());
                    groovy.put("methodStr",scriptEntity.getScriptData());
                    groovy.put("parameterJson",parameterJson);
                    JSONObject groovyStr = new JSONObject();
                    groovyStr.put("jsonStr",groovy);
                    try {
                        Object str = groovyIntegrationService.groovyScriptExecution(groovyStr);
                        JSONObject jsonResultEntity = JSONObject.parseObject(str.toString());
                        header = (Map<String, String>) jsonResultEntity.get("header");
                        querys = jsonResultEntity.getString("querys");
                        bodys = jsonResultEntity.getString("bodys");
                    }catch (Exception e){
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","脚本处理失败",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                }
                Map<String, String> headers = new HashMap<>();
                headers.put("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                headers.put("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                headers.put("appId",sysApplicationEntity.getAppId().toString());
                headers.put("apiCode",apiEntity.getApiCode().toString());
                if(header != null){
                    headers.putAll(header);
                }
                if (SysEnum.NEED_LOGIN.getValue().equals(apiEntity.getNeedLogin())) {
                    //找到登陆接口
                    SysApplicationApiEntity loginApi = sysApplicationApiDao.get(apiEntity.getAuthenticationPort());
                    if (null == loginApi) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","发送错误,认证接口不存在",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                    String rzquerys = getQuery(loginApi,null,null);
                    Map<String, String> headersa = new HashMap<>();
                    headersa.put("publicKey", "ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj");
                    headersa.put("secretKey", "fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=");
                    headersa.put("appId", sysApplicationEntity.getAppId().toString());
                    headersa.put("apiCode", loginApi.getApiCode().toString());
                    Map<String, String> rzheaders = getHeaders(loginApi,headersa,null);
                    String rzbodys = getBodys(loginApi,null,null);
                    JsonResultEntity rzjsonResultEntity = sendData(loginApi,rzheaders,rzbodys,rzquerys);
                    if (!rzjsonResultEntity.isFlag()) {
                        saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","发送错误,认证接口错误",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                        continue;
                    }
                    JSONObject attritube = JSONObject.parseObject(rzjsonResultEntity.getAttribute().toString());
                    querys = getQuery(apiEntity,querys,attritube);
                    headers = getHeaders(apiEntity,headers,attritube);
                    bodys = getBodys(apiEntity,bodys,attritube);
                }

                //组装数据发送
                JsonResultEntity jsonResultEntity = sendData(apiEntity,headers,bodys,querys);
                if(jsonResultEntity.isFlag()){
                    if (scriptEntity != null && scriptEntity.getId() != null && scriptEntity.getBackScriptData() != null ) {
                        JSONObject backScriptJson = new JSONObject();
                        backScriptJson.put("data", jsonResultEntity.getAttribute());
                        groovy.put("code", scriptEntity.getScriptCode()+"back");
                        groovy.put("className", scriptEntity.getClassName()+"back");
                        groovy.put("name", scriptEntity.getScriptName()+"back");
                        groovy.put("methodStr", scriptEntity.getBackScriptData());
                        groovy.put("parameterJson", backScriptJson);
                        JSONObject groovyStr = new JSONObject();
                        groovyStr.put("jsonStr", groovy);
                        try {
                            Object str = groovyIntegrationService.groovyScriptExecution(groovyStr);
                            if(str != null){
                                JSONObject backJsonResultEntity = JSONObject.parseObject(str.toString());
                                if(backJsonResultEntity != null && backJsonResultEntity.getString("success") != null && "true".equals(backJsonResultEntity.getString("success"))){
                                    MdmModuleDistributeTripartiteEntity mdmModuleDistributeTripartiteEntity = new MdmModuleDistributeTripartiteEntity();
                                    mdmModuleDistributeTripartiteEntity.setId(UUIDUtils.getUUID());
                                    mdmModuleDistributeTripartiteEntity.setSts("Y");
                                    mdmModuleDistributeTripartiteEntity.setCreate_user_id("1");
                                    mdmModuleDistributeTripartiteEntity.setModify_user_id("1");
                                    mdmModuleDistributeTripartiteEntity.setCreate_time(new Date());
                                    mdmModuleDistributeTripartiteEntity.setModify_time(new Date());
                                    mdmModuleDistributeTripartiteEntity.setOrg_id("0");
                                    mdmModuleDistributeTripartiteEntity.setCompanyId("0");
                                    mdmModuleDistributeTripartiteEntity.setMdmId(mdmId);
                                    mdmModuleDistributeTripartiteEntity.setDataId(objects.get(i).getString("id"));
                                    mdmModuleDistributeTripartiteEntity.setAppId(sysApplicationEntity.getId());
                                    mdmModuleDistributeTripartiteEntity.setTripartiteId(backJsonResultEntity.getString("tripartiteId"));
                                    mdmModuleDistributeTripartiteDao.save(mdmModuleDistributeTripartiteEntity);
                                }
                            }
                        } catch (Exception e) {
                            logger.error("新增返回脚本解析保存三方id错误"+jsonResultEntity.getAttribute());
                            saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","新增返回脚本解析保存三方id错误",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                            continue;
                        }
                    }
                    //保存日志
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"1","发送成功",mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                    objects.get(i).put("sendsanfzt123",true);
                    continue;
                }else {
                    //保存日志
                    saveMdmModuleSendLogEntity(mainCode,mdmModuleDistributeEntities.get(i1).getId(),"2","转发失败:"+jsonResultEntity.getAttribute(),mainDb,objects.get(i).getString("id"),sysApplicationEntity.getName(),sysApplicationEntity.getId(),apiEntity.getApiName(),apiEntity.getId(),doObjects.get(i).toJSONString(),"1");
                    objects.get(i).put("sendsanfzt123",false);
                    continue;
                }
            }
        }

        //所有下发发送完成，修改数据状态
        for (int i = 0; i < objects.size(); i++) {
            if(objects.get(i).getBoolean("sendsanfzt123")){
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("tableName",mainDb);
                //updateMap.put("dataStatus", "Y");
                updateMap.put("addStatus", "1");
                updateMap.put("id", objects.get(i).getString("id"));
                mdmModuleDao.updateMdmSTs(updateMap);
            }
        }
    }

    private void saveMdmModuleSendLogEntity(Long mdmCode,String distributeId,String dataType,String remark,String dbname,String formmain_id, String target_app, String appId, String target_api,String apiID, String source_data, String option_type) throws Exception {
        MdmModuleSendLogEntity mdmModuleSendLogEntity = new MdmModuleSendLogEntity();
        mdmModuleSendLogEntity.setTableName(dbname+"_send_log");
        mdmModuleSendLogEntity.setId(UUIDUtils.getUUID());
        mdmModuleSendLogEntity.setSts("Y");
        mdmModuleSendLogEntity.setDistributeId(distributeId);
        mdmModuleSendLogEntity.setAppId(appId);
        mdmModuleSendLogEntity.setApiId(apiID);
        mdmModuleSendLogEntity.setCreate_user_id("1");
        mdmModuleSendLogEntity.setModify_user_id("1");
        mdmModuleSendLogEntity.setCreate_time(new Date());
        mdmModuleSendLogEntity.setModify_time(new Date());
        mdmModuleSendLogEntity.setOrg_id("0");
        mdmModuleSendLogEntity.setCompanyId("0");
        mdmModuleSendLogEntity.setFormmainId(formmain_id);
        mdmModuleSendLogEntity.setTargetApp(target_app);
        mdmModuleSendLogEntity.setTargetApi(target_api);
        mdmModuleSendLogEntity.setSourceData(source_data);
        mdmModuleSendLogEntity.setOptionType(option_type);
        mdmModuleSendLogEntity.setDataType(dataType);
        mdmModuleSendLogEntity.setRemark(remark);
        mdmModuleSendLogDao.save(mdmModuleSendLogEntity);


        JSONObject jsonObject = JSONObject.parseObject(source_data);
        IntegrationTaskLivingDetailsEntity integrationTaskLivingDetailsEntity = new IntegrationTaskLivingDetailsEntity();
        integrationTaskLivingDetailsEntity.setId(UUIDUtils.getUUID());
        integrationTaskLivingDetailsEntity.setSts("Y");
        integrationTaskLivingDetailsEntity.setCreate_user_id("1");
        integrationTaskLivingDetailsEntity.setModify_user_id("1");
        integrationTaskLivingDetailsEntity.setCreate_time(new Date());
        integrationTaskLivingDetailsEntity.setModify_time(new Date());
        integrationTaskLivingDetailsEntity.setOrg_id("0");
        integrationTaskLivingDetailsEntity.setCompanyId("0");
        JSONObject aa = new JSONObject();
        aa.put("mdmCode",mdmCode);//主数据编码
        aa.put("documentRule",jsonObject.getString("document_rule"));//行数据的单据规则编码
        aa.put("distributeId",distributeId);//发送表id
        aa.put("type",option_type);//发送类型，1、新增2、修改3、删除
        integrationTaskLivingDetailsEntity.setRootAppPk(aa.toJSONString());
        integrationTaskLivingDetailsEntity.setRootAppBill(jsonObject.getString("document_rule"));
        integrationTaskLivingDetailsEntity.setPluginId("MdmModulePlugin");
        integrationTaskLivingDetailsEntity.setRootAppNewData(source_data);
        integrationTaskLivingDetailsEntity.setNewTransmitInfo(remark);
        if("1".equals(dataType)){
            taskLivingDetailsService.saveLogToSuccess(integrationTaskLivingDetailsEntity);
        }else {
            taskLivingDetailsService.saveLogToFail(integrationTaskLivingDetailsEntity);

        }

    }

    private JSONObject getDetailData(List<MdmModuleDbEntity> mdmModuleDbEntities, JSONObject object, List<MdmModuleDbFiledsRuleEntity> mdmModuleDbFiledsRuleEntities,List<MdmModuleDbFiledsEntity> mdmModuleDbFiledsEntities) {

        for (int i = 0; i < mdmModuleDbEntities.size(); i++) {
            if("2".equals(mdmModuleDbEntities.get(i).getDbType())){
                Map<String,Object> map = new HashMap<>();
                map.put("tableName",mdmModuleDbEntities.get(i).getDbName());
                map.put("formmainId",object.getString("id"));
                List<JSONObject> detail = mdmModuleDao.queryMdmSTDetail(map);
                detail = toLowerCaseKeys(detail);

                //查看主表是否有字段是关联的
                if(detail != null && detail.size() > 0){
                    if(mdmModuleDbFiledsRuleEntities != null && mdmModuleDbFiledsRuleEntities.size() > 0){
                        for (int i1 = 0; i1 < mdmModuleDbFiledsRuleEntities.size(); i1++) {
                            if(mdmModuleDbFiledsRuleEntities.get(i1).getDbId().equals(mdmModuleDbEntities.get(i).getId())){
                                if(mdmModuleDbFiledsEntities != null && mdmModuleDbFiledsEntities.size() > 0){
                                    for (int i2 = 0; i2 < mdmModuleDbFiledsEntities.size(); i2++) {
                                        if(mdmModuleDbFiledsRuleEntities.get(i1).getFiledId().equals(mdmModuleDbFiledsEntities.get(i2).getId())){
                                            for (int i3 = 0; i3 < detail.size(); i3++) {
                                                if(detail.get(i3).getString(mdmModuleDbFiledsEntities.get(i2).getEnName()) != null){
                                                    Map<String,Object> mapDetail = new HashMap<>();
                                                    mapDetail.put("tableName",mdmModuleDbFiledsRuleEntities.get(i1).getRuleValue());
                                                    String ids = detail.get(i3).getString(mdmModuleDbFiledsEntities.get(i2).getEnName());
                                                    String[] idss = ids.split(",");
                                                    mapDetail.put("id", idss[idss.length-1]);
                                                    JSONObject objectDetail = mdmModuleDao.queryMdmST(mapDetail);
                                                    objectDetail = toLowerCaseKeys(objectDetail);

                                                    detail.get(i3).put(mdmModuleDbFiledsEntities.get(i2).getEnName(),objectDetail);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                object.put(mdmModuleDbEntities.get(i).getDbName(),detail);
            }
        }

        return object;
    }


    private JsonResultEntity sendData(SysApplicationApiEntity applicationApiEntity, Map<String, String> headers ,String bodys ,String querys) {
        StringBuffer urls = new StringBuffer(url);
        if (querys != null) {
            urls.append("?");
            urls.append(querys);
        }
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
        HttpPost post = new HttpPost(urls.toString());
        CloseableHttpResponse response = null;

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(Integer.valueOf(applicationApiEntity.getTimeoutPeriod())).build();
        post.setConfig(requestConfig);//设置请求参数【超时时间】

        if (headers != null && headers.size() > 0) {
            for (String key : headers.keySet()) {
                post.setHeader(key, headers.get(key));
            }
        }
        StringBuilder body = new StringBuilder();
        boolean flag = true;
        try {
            if (bodys != null && !"".equals(bodys)) {
                ByteArrayEntity entity = new ByteArrayEntity(bodys.getBytes("UTF-8"));
                entity.setContentType("application/json");
                post.setEntity(entity);
            }
            response = closeableHttpClient.execute(post);

            HttpEntity entity = response.getEntity();
            synchronized (lock) {
                body.append(EntityUtils.toString(entity,"UTF-8"));
            }
            flag = true;
            logger.info("返回结果：" + body);
        } catch (Exception e) {
            logger.error("请求错误：" + e.getMessage());
            body.append(e.getMessage());
            flag = false;
        } finally {
            try {
                // 关闭响应对象
                if (response != null) {
                    response.close();
                }
                // 关闭响应对象
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if (flag) {
            if (JSONUtil.isTypeJSON(body.toString())) {
                JsonResultEntity jsonResultEntity = JSONObject.parseObject(body.toString(),JsonResultEntity.class);
                if(jsonResultEntity.isFlag()){
                    return BaseResult.getSuccessMessageEntity("转发成功", body);
                }else {
                    return BaseResult.getFailureMessageEntity("转发失败", body);
                }
            }else {
                return BaseResult.getFailureMessageEntity("转发失败", body);
            }
        } else {
            return BaseResult.getFailureMessageEntity("转发失败", body);
        }
    }


    private Map<String, String> getHeaders(SysApplicationApiEntity loginApi,Map<String, String> map,JSONObject loginData) {
        if(loginData == null){
            loginData = new JSONObject();
        }
        if (loginApi.getHeaderIn() != null && !"".equals(loginApi.getHeaderIn())) {
            if (JSONUtil.isTypeJSONArray(loginApi.getHeaderIn())) {
                JSONArray headerArray = JSON.parseArray(loginApi.getHeaderIn());
                for (int i = 0; i < headerArray.size(); i++) {
                    JSONObject querys = headerArray.getJSONObject(i);
                    //query 只有基本类型，不用循环判断下级
                    //判断参数是否有值
                    //获取对象下面的层级数据
                    if (SysEnum.AUTHPORT.getValue().equals(querys.getString(SysEnum.PARAMETERTYPE.getValue()))) {//认证类型
                        String query = querys.getString(SysEnum.EXAMPLE.getValue());
                        if (query != null && !"".equals(query)) {
                            JSONArray example = JSONArray.parseArray(query);
                            String logValue = getObjectValue(loginData, example);
                            map.put(querys.getString(SysEnum.PARAMETERNAME.getValue()), logValue);
                        }
                    } else {
                        if (querys.getString(SysEnum.EXAMPLE.getValue()) != null && !"".equals(querys.getString(SysEnum.EXAMPLE.getValue()))) {//入参没有值用实例值，如果没有不添加
                            if(map.get(querys.getString(SysEnum.PARAMETERNAME.getValue())) == null){
                                map.put(querys.getString(SysEnum.PARAMETERNAME.getValue()), querys.getString(SysEnum.EXAMPLE.getValue()));
                            }
                        } else {//没有值直接拼接
                            if(map.get(querys.getString(SysEnum.PARAMETERNAME.getValue())) == null){
                                map.put(querys.getString(SysEnum.PARAMETERNAME.getValue()), "");
                            }
                        }
                    }
                }
            }
        }
        return map;




    }


    private String getQuery(SysApplicationApiEntity loginApi,String sendDatastr,JSONObject loginData) {
        Map<String, String> map = new HashMap<>();
        if(sendDatastr != null){
            String[] parts = sendDatastr.split("&");
            if(parts != null && parts.length > 0){
                for (int i = 0; i < parts.length; i++) {
                    String[] part = parts[i].split("=");
                    if(part != null && part.length >=2 ){
                        for (int a = 0; a < part.length; a++) {
                            map.put(part[0],part[1]);
                        }
                    }
                }
            }
        }
        if(loginData == null){
            loginData = new JSONObject();
        }
        if (loginApi.getQueryIn() != null && !"".equals(loginApi.getQueryIn())) {
            if (JSONUtil.isTypeJSONArray(loginApi.getQueryIn())) {
                JSONArray headerArray = JSON.parseArray(loginApi.getQueryIn());
                for (int i = 0; i < headerArray.size(); i++) {
                    JSONObject querys = headerArray.getJSONObject(i);
                    //query 只有基本类型，不用循环判断下级
                    //判断参数是否有值
                    //获取对象下面的层级数据
                    if (SysEnum.AUTHPORT.getValue().equals(querys.getString(SysEnum.PARAMETERTYPE.getValue()))) {//认证类型
                        String query = querys.getString(SysEnum.EXAMPLE.getValue());
                        if (query != null && !"".equals(query)) {
                            JSONArray example = JSONArray.parseArray(query);
                            String logValue = getObjectValue(loginData, example);
                            map.put(querys.getString(SysEnum.PARAMETERNAME.getValue()), logValue);
                        }
                    } else {
                        //不是认证类型直接取值
                        if (querys.getString(SysEnum.EXAMPLE.getValue()) != null && !"".equals(querys.getString(SysEnum.EXAMPLE.getValue()))) {//入参没有值用实例值，如果没有不添加
                            if(map.get(querys.getString(SysEnum.PARAMETERNAME.getValue())) == null){
                                map.put(querys.getString(SysEnum.PARAMETERNAME.getValue()), querys.getString(SysEnum.EXAMPLE.getValue()));
                            }
                        } else {//没有值直接拼接
                            if(map.get(querys.getString(SysEnum.PARAMETERNAME.getValue())) == null){
                                map.put(querys.getString(SysEnum.PARAMETERNAME.getValue()), "");
                            }
                        }
                    }
                }
            }
        }
        StringBuffer returnStr = new StringBuffer();
        if(map != null && map.size() > 0){
            for (String key : map.keySet()) {
                if("".equals(returnStr)){
                    returnStr.append(key).append("=").append(map.get(key));
                }else {
                    returnStr.append("&").append(key).append("=").append(map.get(key));
                }
            }
        }
        return returnStr.toString();
    }
    /**
     * @param loginData
     * @param example
     * @return java.lang.String
     * @Author lvleigang
     * @Description 根据jsonArray 获取jsonobject中的值
     * @Date 11:47 上午 2023/8/31
     **/
    private String getObjectValue(JSONObject loginData, JSONArray example) {
        String values = "";
        if (example != null && example.size() > 0) {
            for (int i = 0; i < example.size(); i++) {
                if (loginData.getString(example.getString(i)) != null && !"".equals(loginData.getString(example.getString(i)))) {
                    if (i == (example.size() - 1)) {
                        values = loginData.getString(example.getString(i));
                    } else {
                        loginData = JSONObject.parseObject(loginData.getString(example.getString(i)));
                    }
                } else {
                    return values;
                }
            }
        }
        return values;
    }
    private String getBodys(SysApplicationApiEntity loginApi,String sendDatastr, JSONObject loginData) {
        JSONObject sendData = new JSONObject();
        if(sendDatastr != null ){
            sendData = JSONObject.parseObject(sendDatastr);
        }
        if(loginData == null){
            loginData = new JSONObject();
        }
        if (loginApi.getBodyIn() != null && !"".equals(loginApi.getBodyIn())) {
            if (JSONUtil.isTypeJSONArray(loginApi.getBodyIn())) {
                JSONArray headerArray = JSON.parseArray(loginApi.getBodyIn());
                for (int i = 0; i < headerArray.size(); i++) {
                    //获取到第一个数据
                    JSONObject querys = headerArray.getJSONObject(i);
                    if (SysEnum.AUTHPORT.getValue().equals(querys.getString(SysEnum.PARAMETERTYPE.getValue()))) {//认证类型
                        String query = querys.getString(SysEnum.EXAMPLE.getValue());
                        if (query != null && !"".equals(query)) {
                            JSONArray example = JSONArray.parseArray(query);
                            String logValue = getObjectValue(loginData, example);
                            sendData.put(querys.getString(SysEnum.PARAMETERNAME.getValue()),logValue);
                        }
                    }
                }
            }
        }
        return sendData.toString();
    }
    public JSONObject toLowerCaseKeys(JSONObject jsonObject) {
        JSONObject lowerCaseJson = new JSONObject();
        if (jsonObject != null) {
            for (String key : jsonObject.keySet()) {
                Object value = jsonObject.get(key);
                lowerCaseJson.put(key.toLowerCase(), value);
            }
        }
        return lowerCaseJson;
    }
    public List<JSONObject> toLowerCaseKeys(List<JSONObject> list) {
        List<JSONObject> jsonObjects = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                jsonObjects.add(toLowerCaseKeys(list.get(i)));
            }
        }
        return jsonObjects;
    }
}
