package com.hzya.frame.sysnew.application.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.mdm.mdmModuleDistribute.dao.IMdmModuleDistributeDao;
import com.hzya.frame.mdm.mdmModuleDistribute.entity.MdmModuleDistributeEntity;
import com.hzya.frame.serviceUtil.DsDataSourceUtil;
import com.hzya.frame.sysnew.application.api.dao.ISysApplicationApiDao;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiDto;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiEntity;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiVo;
import com.hzya.frame.sysnew.application.apiAuth.dao.ISysApplicationApiAuthDao;
import com.hzya.frame.sysnew.application.apiAuth.entity.SysApplicationApiAuthDto;
import com.hzya.frame.sysnew.application.apiAuth.entity.SysApplicationApiAuthEntity;
import com.hzya.frame.sysnew.application.apiAythDetail.dao.ISysApplicationApiAuthDetailDao;
import com.hzya.frame.sysnew.application.apiAythDetail.entity.SysApplicationApiAuthDetailEntity;
import com.hzya.frame.sysnew.application.apiPara.dao.ISysApplicationApiParaDao;
import com.hzya.frame.sysnew.application.apiPara.entity.SysApplicationApiParaEntity;
import com.hzya.frame.sysnew.application.apiType.dao.ISysApplicationApiTypeDao;
import com.hzya.frame.sysnew.application.apiType.entity.SysApplicationApiTypeEntity;
import com.hzya.frame.sysnew.application.dao.ISysApplicationDao;
import com.hzya.frame.sysnew.application.database.dao.ISysApplicationDatabaseDao;
import com.hzya.frame.sysnew.application.database.entity.SysApplicationDatabaseEntity;
import com.hzya.frame.sysnew.application.entity.*;
import com.hzya.frame.sysnew.application.plugin.dao.ISysApplicationPluginDao;
import com.hzya.frame.sysnew.application.plugin.entity.SysApplicationPluginDto;
import com.hzya.frame.sysnew.application.plugin.entity.SysApplicationPluginEntity;
import com.hzya.frame.sysnew.application.script.dao.ISysApplicationScriptDao;
import com.hzya.frame.sysnew.application.script.entity.SysApplicationScriptEntity;
import com.hzya.frame.sysnew.application.service.ISysApplicationService;
import com.hzya.frame.sysnew.integtationTask.IIntegrationTaskCacheableService;
import com.hzya.frame.sysnew.messageManage.dao.ISysMessageManageDao;
import com.hzya.frame.sysnew.messageManage.entity.SysMessageManageEntity;
import com.hzya.frame.sysnew.messageManageDetail.dao.ISysMessageManageDetailDao;
import com.hzya.frame.sysnew.messageManageDetail.entity.SysMessageManageDetailEntity;
import com.hzya.frame.sysnew.messageManageLog.dao.ISysMessageManageLogDao;
import com.hzya.frame.sysnew.messageManageLog.entity.SysMessageManageLogEntity;
import com.hzya.frame.sysnew.messageManageLog.entity.SysMessageManageLogPageVo;
import com.hzya.frame.sysnew.pushMessage.entity.SysPushMessageEntity;
import com.hzya.frame.sysnew.sendMessageLog.service.ISysSendMessageLogService;
import com.hzya.frame.util.AESUtil;
import com.hzya.frame.util.IPHelper;
import com.hzya.frame.uuid.UUIDUtils;
import com.hzya.frame.web.action.ApplicationContextUtil;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustAllStrategy;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.net.ssl.SSLContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 应用表(SysApplication)表服务实现类
 *
 * @author makejava
 * @since 2023-09-22 16:22:24
 */
@Service(value = "sysApplicationService")
public class SysApplicationServiceImpl extends BaseService<SysApplicationEntity, String> implements ISysApplicationService {

    private ISysApplicationDao sysApplicationDao;
    @Resource
    private ISysApplicationApiDao sysApplicationApiDao;
    @Resource
    private ISysSendMessageLogService sysSendMessageLogService;
    @Resource
    private ISysMessageManageLogDao sysMessageManageLogDao;
    @Resource
    private DsDataSourceUtil dsDataSourceUtil;
    @Resource
    private ISysApplicationApiAuthDao sysApplicationApiAuthDao;
    @Resource
    private ISysApplicationApiAuthDetailDao sysApplicationApiAuthDetailDao;
    @Resource
    private ISysApplicationApiParaDao sysApplicationApiParaDao;
    @Resource
    private ISysApplicationApiTypeDao sysApplicationApiTypeDao;
    @Resource
    private ISysApplicationDatabaseDao sysApplicationDatabaseDao;
    @Resource
    private ISysApplicationPluginDao sysApplicationPluginDao;
    @Resource
    private ISysApplicationScriptDao sysApplicationScriptDao;
    @Resource
    private ISysMessageManageDao sysMessageManageDao;
    @Resource
    private ISysMessageManageDetailDao sysMessageManageDetailDao; //明细表
    @Resource
    private IMdmModuleDistributeDao mdmModuleDistributeDao;
    @Resource
    private IIntegrationTaskCacheableService iIntegrationTaskCacheableService;
    @Resource
    private TaskExecutor taskExecutor;
    //
    @Resource
    private ApplicationCache applicationCache;

    @Value("${savefile.tomcatpath:}")
    public String TOMCATPATH;
    //多线程请求加锁 HttpRequest 构造方法是静态的
    private final Object lock = new Object();

    @Autowired
    public void setSysApplicationDao(ISysApplicationDao dao) {
        this.sysApplicationDao = dao;
        this.dao = dao;
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用列表查询接口 多字段模糊查询，枚举类型字段转换
     * @Date 2:06 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryApp(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<SysApplicationVo> sysApplicationVos = sysApplicationDao.queryApp(entity);
        PageInfo pageInfo = new PageInfo(sysApplicationVos);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 创建应用保存接口 应用名称唯一校验，生成公钥密钥
     * @Date 2:07 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveApp(JSONObject object) {
        SysApplicationEntity entity = getData("jsonStr", object, SysApplicationEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getName() == null || "".equals(entity.getName())) {
            return BaseResult.getFailureMessageEntity("请先输入应用名称");
        }
        SysApplicationEntity checkEntity = new SysApplicationEntity();
        checkEntity.setSts("Y");
        checkEntity.setName(entity.getName());
        int checkCount = sysApplicationDao.getCount(checkEntity);
        if (checkCount > 0) {
            return BaseResult.getFailureMessageEntity("应用名称已存在");
        }
        setCreate(entity);
        //设置key 密钥
        entity.setPublicKey("ZJYA" + AESUtil.encipher(entity.getId()));
        entity.setSecretKey(AESUtil.encipher(entity.getPublicKey()));
        entity.setInterfaceStatus("2");
        entity.setDbStatus("2");
        sysApplicationDao.save(entity);
        applicationCache.reloadData("1");
        return BaseResult.getSuccessMessageEntity("保存应用成功", entity.getId());
    }

    private void setCreate(SysApplicationEntity entity) {
        entity.setId(UUIDUtils.getUUID());
        entity.setSts("Y");
        entity.setCreate_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setCreate_time(new Date());
        entity.setModify_time(new Date());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用复制接口保存接口 应用名称校验唯一，其余表，同步保存新增，api接口要关联对应的认证接口id
     * @Date 2:07 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity copyApp(JSONObject object) {
        SysApplicationEntity entity = getData("jsonStr", object, SysApplicationEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getName() == null || "".equals(entity.getName())) {
            return BaseResult.getFailureMessageEntity("请先输入应用名称");
        }

        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        String olderAppId = entity.getId();
        SysApplicationEntity checkEntity = new SysApplicationEntity();
        checkEntity.setSts("Y");
        checkEntity.setName(entity.getName());
        int checkCount = sysApplicationDao.getCount(checkEntity);
        if (checkCount > 0) {
            return BaseResult.getFailureMessageEntity("应用名称已存在");
        }
        setCreate(entity);
        //设置key 密钥
        entity.setPublicKey("ZJYA" + AESUtil.encipher(entity.getId()));
        entity.setSecretKey(AESUtil.encipher(entity.getPublicKey()));
        entity.setAppId(null);
        sysApplicationDao.save(entity);
        //接口环境参数表  sys_application_api_para
        saveApiPara(entity, olderAppId);

        //数据源表不保存，可能出现数据源编号重复问题 sys_application_database
        //saveDatabase(entity, olderAppId);

        //插件表 sys_application_plugin
        savePlugin(entity, olderAppId);

        //目录表 sys_application_api_type
        Map<String, String> apiType = saveCopyApiType(entity, olderAppId);

        //三方调用系统表		sys_application_api_auth
        Map<String, String> apiAuth = saveCopyApiAuth(entity, olderAppId);
        //应用api表	sys_application_api
        Map<String, String> api = saveCopyApi(entity, olderAppId, apiType, apiAuth);

        //应用api关联三方调用系统表 sys_application_api_auth_detail
        Map<String, String> apiAuthDetail = saveCopyApiAuthDetail(entity, olderAppId, apiType, apiAuth, api);
        applicationCache.reloadData("1");
        applicationCache.reloadData("2");
        applicationCache.reloadData("3");
        applicationCache.reloadData("4");

        return BaseResult.getSuccessMessageEntity("复制应用成功", entity.getId());
    }

    //应用api关联三方调用系统表 sys_application_api_auth_detail
    private Map<String, String> saveCopyApiAuthDetail(SysApplicationEntity entity, String olderAppId, Map<String, String> apiType, Map<String, String> apiAuth, Map<String, String> api) {
        Map<String, String> ids = new HashMap<>();
        if (api == null || api.size() == 0) {
            return ids;
        }
        SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = new SysApplicationApiAuthDetailEntity();
        sysApplicationApiAuthDetailEntity.setAppId(olderAppId);
        sysApplicationApiAuthDetailEntity.setSts("Y");
        List<SysApplicationApiAuthDetailEntity> list = sysApplicationApiAuthDetailDao.queryBase(sysApplicationApiAuthDetailEntity);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String newId = UUIDUtils.getUUID();
                ids.put(list.get(i).getId(), newId);
                list.get(i).setId(newId);
                list.get(i).setSts("Y");
                list.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setCreate_time(new Date());
                list.get(i).setModify_time(new Date());
                list.get(i).setAppId(entity.getId());//转换应用id
                list.get(i).setCatalogueId(apiType.get(list.get(i).getCatalogueId()));//转换目录
                list.get(i).setApiId(api.get(list.get(i).getApiId()));//转换接口id
                list.get(i).setTripartiteSystemId(apiAuth.get(list.get(i).getTripartiteSystemId()));//转换三方调用系统表id
                sysApplicationApiAuthDetailDao.save(list.get(i));
            }
        }
        applicationCache.reloadData("4");
        return ids;
    }

    //api相关
    private Map<String, String> saveCopyApi(SysApplicationEntity entity, String olderAppId, Map<String, String> apiType, Map<String, String> apiAuth) {

        Map<String, String> apiIds = new HashMap<>();
        if (apiType == null || apiType.size() == 0) {
            return apiIds;
        }
        SysApplicationApiEntity sysApplicationApiEntity = new SysApplicationApiEntity();
        sysApplicationApiEntity.setAppId(olderAppId);
        sysApplicationApiEntity.setSts("Y");
        List<SysApplicationApiEntity> apilist = sysApplicationApiDao.queryBase(sysApplicationApiEntity);
        if (apilist != null && apilist.size() > 0) {
            for (int i = 0; i < apilist.size(); i++) {
                String newId = UUIDUtils.getUUID();
                apiIds.put(apilist.get(i).getId(), newId);
                apilist.get(i).setId(newId);
                apilist.get(i).setSts("Y");
                apilist.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                apilist.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                apilist.get(i).setCreate_time(new Date());
                apilist.get(i).setModify_time(new Date());

                apilist.get(i).setAppId(entity.getId());
                apilist.get(i).setApiCode(null);
                apilist.get(i).setCatalogueId(apiType.get(apilist.get(i).getCatalogueId()));//转换目录
                sysApplicationApiDao.save(apilist.get(i));
            }
        }
        applicationCache.reloadData("2");
        return apiIds;
    }

    //三方调用系统表		sys_application_api_auth
    private Map<String, String> saveCopyApiAuth(SysApplicationEntity entity, String olderAppId) {
        Map<String, String> ids = new HashMap<>();
        SysApplicationApiAuthEntity sysApplicationApiAuthEntity = new SysApplicationApiAuthEntity();
        sysApplicationApiAuthEntity.setAppId(olderAppId);
        sysApplicationApiAuthEntity.setSts("Y");
        List<SysApplicationApiAuthEntity> list = sysApplicationApiAuthDao.queryBase(sysApplicationApiAuthEntity);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String newId = UUIDUtils.getUUID();
                ids.put(list.get(i).getId(), newId);
                list.get(i).setId(newId);
                list.get(i).setSts("Y");
                list.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setCreate_time(new Date());
                list.get(i).setModify_time(new Date());
                list.get(i).setAppId(entity.getId());
                sysApplicationApiAuthDao.save(list.get(i));
            }
        }
        applicationCache.reloadData("3");
        return ids;
    }

    //目录表 sys_application_api_type
    private Map<String, String> saveCopyApiType(SysApplicationEntity entity, String olderAppId) {
        Map<String, String> ids = new HashMap<>();
        SysApplicationApiTypeEntity sysApplicationApiTypeEntity = new SysApplicationApiTypeEntity();
        sysApplicationApiTypeEntity.setAppId(olderAppId);
        sysApplicationApiTypeEntity.setSts("Y");
        List<SysApplicationApiTypeEntity> list = sysApplicationApiTypeDao.queryBase(sysApplicationApiTypeEntity);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                String newId = UUIDUtils.getUUID();
                ids.put(list.get(i).getId(), newId);
                list.get(i).setId(newId);
                list.get(i).setSts("Y");
                list.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setCreate_time(new Date());
                list.get(i).setModify_time(new Date());
                list.get(i).setAppId(entity.getId());
                sysApplicationApiTypeDao.save(list.get(i));
            }
        }
        return ids;
    }


    //插件表 sys_application_plugin
    private void savePlugin(SysApplicationEntity entity, String olderAppId) {
        SysApplicationPluginEntity sysApplicationPluginEntity = new SysApplicationPluginEntity();
        sysApplicationPluginEntity.setAppId(olderAppId);
        sysApplicationPluginEntity.setSts("Y");
        List<SysApplicationPluginEntity> list = sysApplicationPluginDao.queryBase(sysApplicationPluginEntity);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setId(UUIDUtils.getUUID());
                list.get(i).setSts("Y");
                list.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setCreate_time(new Date());
                list.get(i).setModify_time(new Date());
                list.get(i).setAppId(entity.getId());
                sysApplicationPluginDao.save(list.get(i));
            }
        }
    }

    //数据源表 sys_application_database
    private void saveDatabase(SysApplicationEntity entity, String olderAppId) {
        SysApplicationDatabaseEntity sysApplicationDatabaseEntity = new SysApplicationDatabaseEntity();
        sysApplicationDatabaseEntity.setAppId(olderAppId);
        sysApplicationDatabaseEntity.setSts("Y");
        List<SysApplicationDatabaseEntity> list = sysApplicationDatabaseDao.queryBase(sysApplicationDatabaseEntity);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setId(UUIDUtils.getUUID());
                list.get(i).setSts("Y");
                list.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setCreate_time(new Date());
                list.get(i).setModify_time(new Date());
                list.get(i).setAppId(entity.getId());
                sysApplicationDatabaseDao.save(list.get(i));
            }
        }
    }

    //接口环境参数表  sys_application_api_para
    private void saveApiPara(SysApplicationEntity entity, String olderAppId) {
        SysApplicationApiParaEntity sysApplicationApiParaEntity = new SysApplicationApiParaEntity();
        sysApplicationApiParaEntity.setAppId(olderAppId);
        sysApplicationApiParaEntity.setSts("Y");
        List<SysApplicationApiParaEntity> list = sysApplicationApiParaDao.queryBase(sysApplicationApiParaEntity);
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                list.get(i).setId(UUIDUtils.getUUID());
                list.get(i).setSts("Y");
                list.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                list.get(i).setCreate_time(new Date());
                list.get(i).setModify_time(new Date());
                list.get(i).setAppId(entity.getId());
                sysApplicationApiParaDao.save(list.get(i));
            }
        }
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用复制接口查询接口
     * @Date 2:07 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity getCopyApp(JSONObject object) {
        SysApplicationEntity entity = getData("jsonStr", object, SysApplicationEntity.class);
        //判断主键
        if (entity == null || entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("请先传递请求主键");
        }
        entity = sysApplicationDao.queryOne(entity);
        entity.setName(null);
        entity.setPublicKey(null);
        entity.setSecretKey(null);
        entity.setAppId(null);
        return BaseResult.getSuccessMessageEntity("查询数据成功", entity);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用根据ID查询接口 只需要应用表数据的地方都调用这一个接口
     * @Date 2:07 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity getApp(JSONObject object) {
        SysApplicationEntity entity = getData("jsonStr", object, SysApplicationEntity.class);
        //判断主键
        if (entity == null || entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("请先传递请求主键");
        }
        entity = sysApplicationDao.queryOne(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", entity);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用启用停用接口
     * @Date 2:07 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity enableOrDisableApp(JSONObject object) {
        SysApplicationEntity entity = getData("jsonStr", object, SysApplicationEntity.class);
        //判断编码是否重复
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getAppStatus() == null || "".equals(entity.getAppStatus())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationEntity saveEntity = new SysApplicationEntity();
        saveEntity.setSts("Y");
        saveEntity.setId(entity.getId());
        saveEntity.setAppStatus(entity.getAppStatus());
        saveEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        saveEntity.setModify_time(new Date());
        sysApplicationDao.update(saveEntity);
        applicationCache.reloadData("1");
        if ("1".equals(entity.getAppStatus())) {
            return BaseResult.getSuccessMessageEntity("启用成功");
        } else {
            return BaseResult.getSuccessMessageEntity("停用成功");
        }
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用修改接口 应用、应用接口环境参数、数据源一个接口修改。注接口参数和数据源可能修改、新增或者删除情况，要逻辑判断
     * @Date 2:07 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity updateApp(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        //判断编码是否重复
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getUpdateType() == null || "".equals(entity.getUpdateType())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //查看数据源编码是否存在
        SysApplicationDatabaseEntity detailEntity =  entity.getDatabaseEntity();
        if(detailEntity != null && detailEntity.getSourceCode() != null && !"".equals(detailEntity.getSourceCode())){
            SysApplicationDatabaseEntity checkData =  new SysApplicationDatabaseEntity();
            checkData.setSourceCode(detailEntity.getSourceCode());
            checkData.setSts("Y");
            List<SysApplicationDatabaseEntity> sysApplicationDatabaseEntities = sysApplicationDatabaseDao.queryBase(checkData);
            if(detailEntity.getId() != null && !"".equals(detailEntity.getId())){
                if(sysApplicationDatabaseEntities != null && sysApplicationDatabaseEntities.size() > 0){
                    for (int i = 0; i < sysApplicationDatabaseEntities.size(); i++) {
                        if(!detailEntity.getId().equals(sysApplicationDatabaseEntities.get(i).getId())){
                            return BaseResult.getFailureMessageEntity("数据源编码已经存在，请修改");
                        }
                    }
                }
            }else {
                if(sysApplicationDatabaseEntities != null && sysApplicationDatabaseEntities.size() > 0){
                    return BaseResult.getFailureMessageEntity("数据源编码已经存在，请修改");
                }
            }
        }
        //修改应用基本信息
        SysApplicationEntity sysApplicationEntity = doUpdateApp(entity);
        if ("2".equals(entity.getUpdateType())) {//开发管理界面，需要保存 接口参数，和数据源
            doUpdateApiPara(entity);//api接口参数
            doUpdateDatabase(entity);//数据源
        }
        applicationCache.reloadData("1");
        applicationCache.reloadData("2");
        applicationCache.reloadData("3");
        applicationCache.reloadData("4");
        return BaseResult.getSuccessMessageEntity("修改应用成功");
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 数据源测试接口 测试当前页面数据源是否配置正确
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity testDatabase(JSONObject object) {
        SysApplicationDatabaseEntity entity = getData("jsonStr", object, SysApplicationDatabaseEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationDatasourceDto sysApplicationDatasourceDto = new SysApplicationDatasourceDto();
        sysApplicationDatasourceDto.setSourceType(entity.getSourceType());
        sysApplicationDatasourceDto.setSourceUrl(entity.getSourceUrl());
        sysApplicationDatasourceDto.setLoginName(entity.getLoginName());
        sysApplicationDatasourceDto.setPassword(entity.getPassword());
        if (dsDataSourceUtil.testConnection(sysApplicationDatasourceDto)) {
            return BaseResult.getSuccessMessageEntity("测试连接数据源成功",true);
        } else {
            return BaseResult.getSuccessMessageEntity("测试连接数据源失败",false);
        }
    }

    //修改数据源
    private void doUpdateDatabase(SysApplicationDto entity) {
        //先删除明细再修改
        SysApplicationDatabaseEntity detailEntity = new SysApplicationDatabaseEntity();
        detailEntity.setSts("Y");
        detailEntity.setAppId(entity.getId());
        detailEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        detailEntity.setModify_time(new Date());
        sysApplicationDatabaseDao.logicRemoveMultiCondition(detailEntity);
        SysApplicationDatabaseEntity databaseEntity = entity.getDatabaseEntity();
        if (databaseEntity != null) {
            databaseEntity.setAppId(entity.getId());
            databaseEntity.setPassword(AESUtil.encrypt(databaseEntity.getPassword()));
            databaseEntity.setSts("Y");
            databaseEntity.setSts("Y");
            databaseEntity.setDbStatus(entity.getDbStatus());
            databaseEntity.setModify_user_id(StpUtil.getLoginIdAsString());
            databaseEntity.setModify_time(new Date());
            if (databaseEntity.getId() != null && !"".equals(databaseEntity.getId())) {
                //修改
                sysApplicationDatabaseDao.update(databaseEntity);
                if("1".equals(databaseEntity.getDbStatus())){
                    try {
                        dsDataSourceUtil.editDataSource(databaseEntity);
                    } catch (Exception e) {
                        //return BaseResult.getSuccessMessageEntity("修改数据源失败，请检查数据源配置是否正确");
                    }
                }else {
                    try {
                        dsDataSourceUtil.removeDataSource(databaseEntity.getSourceCode());
                    } catch (Exception e) {
                        //return BaseResult.getSuccessMessageEntity("修改数据源失败");
                    }
                }
            } else {
                //新增
                databaseEntity.setId(UUIDUtils.getUUID());
                databaseEntity.setCreate_user_id(StpUtil.getLoginIdAsString());
                databaseEntity.setCreate_time(new Date());
                sysApplicationDatabaseDao.save(databaseEntity);
            }
        }
    }

    //修改api接口参数信息
    private void doUpdateApiPara(SysApplicationDto entity) {
        //先删除明细再修改
        SysApplicationApiParaEntity detailEntity = new SysApplicationApiParaEntity();
        detailEntity.setSts("Y");
        detailEntity.setAppId(entity.getId());
        detailEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        detailEntity.setModify_time(new Date());
        sysApplicationApiParaDao.logicRemoveMultiCondition(detailEntity);

        List<SysApplicationApiParaEntity> apiParas = entity.getApiParas();
        if (apiParas != null && apiParas.size() > 0) {
            for (int i = 0; i < apiParas.size(); i++) {
                apiParas.get(i).setAppId(entity.getId());
                apiParas.get(i).setSts("Y");
                apiParas.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                apiParas.get(i).setModify_time(new Date());
                if (apiParas.get(i).getId() != null && !"".equals(apiParas.get(i).getId())) {
                    //修改
                    sysApplicationApiParaDao.update(apiParas.get(i));
                } else {
                    //新增
                    apiParas.get(i).setId(UUIDUtils.getUUID());
                    apiParas.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                    apiParas.get(i).setCreate_time(new Date());
                    sysApplicationApiParaDao.save(apiParas.get(i));
                }
            }
        }
    }

    //修改app信息
    private SysApplicationEntity doUpdateApp(SysApplicationDto entity) {
        SysApplicationEntity sysApplicationEntity = new SysApplicationEntity();
        sysApplicationEntity.setId(entity.getId());
        /**  应用logo（地址或者id） */
        sysApplicationEntity.setAppType(entity.getAppType());
        /**  应用logo（地址或者id） */
        sysApplicationEntity.setAppLogo(entity.getAppLogo());
        /**  应用是否启用（1、启用 2、停用） */
        sysApplicationEntity.setAppStatus(entity.getAppStatus());
        /**  应用名称 */
        sysApplicationEntity.setName(entity.getName());
        /**  版本号 */
        sysApplicationEntity.setVersionNumber(entity.getVersionNumber());
        /**  接入方式（1、接口2、H53、PC网页4、PC应用程序 ） */
        sysApplicationEntity.setAccessMode(entity.getAccessMode());
        /**  所属领域（枚举表） */
        sysApplicationEntity.setAffiliationField(entity.getAffiliationField());
        /**  厂商 */
        sysApplicationEntity.setManufacturer(entity.getManufacturer());
        /**  应用简介 */
        sysApplicationEntity.setAppIntroduction(entity.getAppIntroduction());
        /**  应用客户端地址（PC） */
        sysApplicationEntity.setClientPath(entity.getClientPath());
        /**  应用网页端地址（PC） */
        sysApplicationEntity.setWebPath(entity.getWebPath());
        /**  应用程序地址（移动端） */
        sysApplicationEntity.setProgramPath(entity.getProgramPath());
        /**  应用key */
        sysApplicationEntity.setPublicKey(entity.getPublicKey());
        /**  应用密钥 */
        sysApplicationEntity.setSecretKey(entity.getSecretKey());
        sysApplicationEntity.setAppId(entity.getAppId());
        sysApplicationEntity.setSystemAddress(entity.getSystemAddress());
        /**  接口地址 */
        sysApplicationEntity.setInterfaceAddress(entity.getInterfaceAddress());
        /**  接口环境是否启用（1、开启 2、关闭） */
        sysApplicationEntity.setInterfaceStatus(entity.getInterfaceStatus());
        /**  数据源是否启用（1、开启 2、关闭） */
        sysApplicationEntity.setDbStatus(entity.getDbStatus());
        sysApplicationEntity.setSts("Y");
        sysApplicationEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        sysApplicationEntity.setModify_time(new Date());
        sysApplicationEntity.setNifiAppId(entity.getNifiAppId());
        sysApplicationDao.update(sysApplicationEntity);
        applicationCache.reloadData("1");
        return sysApplicationEntity;
    }


    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用目录查询接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppApiType(JSONObject object) {
        SysApplicationApiTypeEntity entity = getData("jsonStr", object, SysApplicationApiTypeEntity.class);
        List<SysApplicationApiTypeEntity> apiTypeEntities = sysApplicationApiTypeDao.queryByLike(entity);
        return BaseResult.getSuccessMessageEntity("查询目录成功", apiTypeEntities);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用目录保存接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveAppApiType(JSONObject object) {
        SysApplicationApiTypeEntity entity = getData("jsonStr", object, SysApplicationApiTypeEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getName() == null || "".equals(entity.getName())) {
            return BaseResult.getFailureMessageEntity("请先输入目录名称");
        }
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setId(UUIDUtils.getUUID());
        entity.setSts("Y");
        entity.setCreate_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setCreate_time(new Date());
        entity.setModify_time(new Date());
        sysApplicationApiTypeDao.save(entity);
        return BaseResult.getSuccessMessageEntity("保存目录成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用目录修改接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity updateAppApiType(JSONObject object) {
        SysApplicationApiTypeEntity entity = getData("jsonStr", object, SysApplicationApiTypeEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getName() == null || "".equals(entity.getName())) {
            return BaseResult.getFailureMessageEntity("请先输入业务类型");
        }
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationApiTypeEntity checkEntity = new SysApplicationApiTypeEntity();
        checkEntity.setSts("Y");
        checkEntity.setId(entity.getId());
        checkEntity.setName(entity.getName());
        checkEntity.setAppId(entity.getAppId());
        int checkCount = sysApplicationApiTypeDao.entity_count_not_id(checkEntity);
        if (checkCount > 0) {
            return BaseResult.getFailureMessageEntity("业务类型已存在");
        }
        entity.setSts("Y");
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_time(new Date());
        sysApplicationApiTypeDao.update(entity);
        return BaseResult.getSuccessMessageEntity("修改业务类型成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用目录删除接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity deleteAppApiType(JSONObject object) {

        SysApplicationApiTypeEntity entity = getData("jsonStr", object, SysApplicationApiTypeEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationApiEntity checkEntity = new SysApplicationApiEntity();
        checkEntity.setSts("Y");
        checkEntity.setAppId(entity.getAppId());
        checkEntity.setCatalogueId(entity.getId());
        int checkCount = sysApplicationApiDao.checkCatalogue(checkEntity);
        if (checkCount > 0) {
            return BaseResult.getFailureMessageEntity("业务模块下的接口已被其他接口使用，请先删除接口");
        }
        //删除
        SysApplicationApiEntity sysApplicationApiEntity = new SysApplicationApiEntity();
        sysApplicationApiEntity.setCatalogueId(entity.getId());
        sysApplicationApiEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        sysApplicationApiEntity.setModify_time(new Date());
        sysApplicationApiEntity.setSts("Y");
        sysApplicationApiDao.logicRemoveMultiCondition(sysApplicationApiEntity);
        applicationCache.reloadData("2");
        //删除
        SysApplicationApiTypeEntity sysApplicationApiTypeEntity = new SysApplicationApiTypeEntity();
        sysApplicationApiTypeEntity.setId(entity.getId());
        sysApplicationApiTypeEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        sysApplicationApiTypeEntity.setModify_time(new Date());
        sysApplicationApiTypeEntity.setSts("Y");
        sysApplicationApiTypeDao.logicRemoveMultiCondition(sysApplicationApiTypeEntity);
        return BaseResult.getSuccessMessageEntity("删除业务类型成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 根据应用、目录、查询条件查询api接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppApi(JSONObject object) {
        SysApplicationApiDto entity = getData("jsonStr", object, SysApplicationApiDto.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<SysApplicationApiVo> entities = sysApplicationApiDao.queryVoList(entity);


        PageInfo pageInfo = new PageInfo(entities);
        if (entities != null && entities.size() > 0) {
            for (int i = 0; i < entities.size(); i++) {
                if (entities.get(i).getAuthDetail() != null && !"".equals(entities.get(i).getAuthDetail())) {
                    String[] a = entities.get(i).getAuthDetail().split(",");
                    entities.get(i).setAuthDetails(a);
                } else {
                    entities.get(i).setAuthDetails(new String[]{});
                }
            }
        }
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 查询调试参数接口 根据调试内容，查询认证以及自己环境参数以及api设置参数
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity debugAppApi(JSONObject object) {
        SysApplicationApiDto entity = getData("jsonStr", object, SysApplicationApiDto.class);
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //查询app
        SysApplicationEntity sysApplicationEntity = sysApplicationDao.get(entity.getAppId());
        //查询接口
        SysApplicationApiEntity sysApplicationApiEntity = sysApplicationApiDao.get(entity.getId());
        //查询接口参数
        SysApplicationApiParaEntity sysApplicationApiParaEntity = new SysApplicationApiParaEntity();
        sysApplicationApiParaEntity.setSts("Y");
        sysApplicationApiParaEntity.setAppId(entity.getAppId());
        List<SysApplicationApiParaEntity> sysApplicationApiParaEntityList = sysApplicationApiParaDao.queryBase(sysApplicationApiParaEntity);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("app", sysApplicationEntity);
        jsonObject.put("api", sysApplicationApiEntity);
        jsonObject.put("para", sysApplicationApiParaEntityList);
        return BaseResult.getSuccessMessageEntity("查询数据成功", jsonObject);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 查询api接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity getAppApi(JSONObject object) {
        SysApplicationApiDto entity = getData("jsonStr", object, SysApplicationApiDto.class);
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //查询接口
        SysApplicationApiEntity sysApplicationApiEntity = sysApplicationApiDao.get(entity.getId());
        return BaseResult.getSuccessMessageEntity("查询数据成功", sysApplicationApiEntity);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 查询接口日志 查询接口发送错误，以及不发送的数据
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppApiLog(JSONObject object) {
        SysMessageManageLogEntity entity = getData("jsonStr", object, SysMessageManageLogEntity.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        //日期转换
        if (entity.getCreateTimeStart() != null) {
            DateTime beginOfDay = DateUtil.beginOfDay(entity.getCreateTimeStart());
            entity.setCreateTimeStart(beginOfDay);
        }
        //日期转换
        if (entity.getCreateTimeEnd() != null) {
            DateTime endOfDay = DateUtil.endOfDay(entity.getCreateTimeEnd());
            entity.setCreateTimeEnd(endOfDay);
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<String> ids = sysMessageManageLogDao.querySysMessageManageLogIds(entity);
        PageInfo pageInfo = new PageInfo(ids);
        List<SysMessageManageLogPageVo> sysMessageManageLogEntities = new ArrayList<>();
        if (ids != null && ids.size() > 0) {
            entity.setIds(ids);
            sysMessageManageLogEntities = sysMessageManageLogDao.queryListByErrorPageVo(entity);
        }
        pageInfo.setList(sysMessageManageLogEntities);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 共享保存接口 根据选择的应用和目录，
     * 查询对应应用是否有该接口，有返回提示，没有保存，
     * 同步判断是否有认证接口，以及认证接口是否存在，如果存在不保存
     * @Date 2023/9/23
     **/
    @Override
    public JsonResultEntity saveApiShare(JSONObject object) {
        SysApplicationApiDto entity = getData("jsonStr", object, SysApplicationApiDto.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("请先选择应用");
        }
        if (entity.getCatalogueId() == null || "".equals(entity.getCatalogueId())) {
            return BaseResult.getFailureMessageEntity("请先选择目录");
        }
        SysApplicationApiEntity apiEntity = sysApplicationApiDao.get(entity.getId());
        //判断接口是否已经存在
        SysApplicationApiEntity checkEntity = new SysApplicationApiEntity();
        checkEntity.setSts("Y");
        checkEntity.setAppId(entity.getAppId());
        checkEntity.setApiName(apiEntity.getApiName());
        List<SysApplicationApiEntity> checkList = sysApplicationApiDao.queryBase(checkEntity);
        if (checkList != null && checkList.size() > 0) {
            return BaseResult.getFailureMessageEntity("接口已存在");
        } else {
            doSaveApiShare(apiEntity, entity.getAppId(), entity.getCatalogueId());
            return BaseResult.getSuccessMessageEntity("共享接口成功");
        }
    }

    /**
     * @param apiEntity   需要复制的接口
     * @param appId       复制后的应用id
     * @param catalogueId 复制后的目录id
     * @return java.lang.String
     * @Author lvleigang
     * @Description 保存接口
     * @Date 3:45 下午 2023/9/25
     **/
    private String doSaveApiShare(SysApplicationApiEntity apiEntity, String appId, String catalogueId) {
        //判断接口是否已经存在
        String authenticationPortId = null;
        SysApplicationApiEntity checkEntity = new SysApplicationApiEntity();
        checkEntity.setSts("Y");
        checkEntity.setAppId(appId);
        checkEntity.setApiName(apiEntity.getApiName());
        List<SysApplicationApiEntity> checkList = sysApplicationApiDao.queryBase(checkEntity);
        if (checkList != null && checkList.size() > 0) {
            return authenticationPortId;
        }
        //新的认证接口id
        //修改设置参数
        apiEntity.setApiCode(null);
        apiEntity.setAppId(appId);
        apiEntity.setCatalogueId(catalogueId);
        apiEntity.setId(UUIDUtils.getUUID());
        apiEntity.setSts("Y");
        apiEntity.setCreate_user_id(StpUtil.getLoginIdAsString());
        apiEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        apiEntity.setCreate_time(new Date());
        apiEntity.setModify_time(new Date());
        //判断是否有认证接口
        if (apiEntity.getNeedLogin() != null && "1".equals(apiEntity.getNeedLogin()) && apiEntity.getAuthenticationPort() != null && !"".equals(apiEntity.getAuthenticationPort())) {
            String rnId = null;
            //存在认证接口
            SysApplicationApiEntity authenticationPort = sysApplicationApiDao.get(apiEntity.getAuthenticationPort());
            //查询保存认证接口目录
            SysApplicationApiTypeEntity sysApplicationApiTypeEntity = sysApplicationApiTypeDao.get(authenticationPort.getCatalogueId());
            //判断目录是否存在
            SysApplicationApiTypeEntity checkType = new SysApplicationApiTypeEntity();
            checkType.setSts("Y");
            checkType.setAppId(appId);
            checkType.setName(sysApplicationApiTypeEntity.getName());
            List<SysApplicationApiTypeEntity> apiTypeEntities = sysApplicationApiTypeDao.queryBase(checkType);
            //	目录不存在时候
            if (apiTypeEntities == null || apiTypeEntities.size() == 0) {
                SysApplicationApiTypeEntity saveApiType = new SysApplicationApiTypeEntity();
                saveApiType.setAppId(appId);
                saveApiType.setName(sysApplicationApiTypeEntity.getName());
                saveApiType.setId(UUIDUtils.getUUID());
                saveApiType.setSts("Y");
                saveApiType.setCreate_user_id(StpUtil.getLoginIdAsString());
                saveApiType.setModify_user_id(StpUtil.getLoginIdAsString());
                saveApiType.setCreate_time(new Date());
                saveApiType.setModify_time(new Date());
                sysApplicationApiTypeDao.save(saveApiType);
                apiEntity.setAuthenticationPort(doSaveApiShare(authenticationPort, appId, saveApiType.getId()));
            } else {
                apiEntity.setAuthenticationPort(doSaveApiShare(authenticationPort, appId, apiTypeEntities.get(0).getId()));
            }
        }
        authenticationPortId = apiEntity.getId();
        sysApplicationApiDao.save(apiEntity);
        applicationCache.reloadData("2");
        return authenticationPortId;
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description api删除接口 接口删除校验是否有api配置时候有使用，以及esb中心是否有配置该接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity deleteApi(JSONObject object) {

        SysApplicationApiDto entity = getData("jsonStr", object, SysApplicationApiDto.class);
        //判断编码是否重复
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("请先填写内容");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("请先选择数据");
        }
        //判断api是否有使用
        SysApplicationApiEntity checkApi = new SysApplicationApiEntity();
        checkApi.setAuthenticationPort(entity.getId());
        checkApi.setSts("Y");
        Integer checkApiCount = sysApplicationApiDao.getCount(checkApi);
        if (checkApiCount != null && checkApiCount > 0) {
            return BaseResult.getFailureMessageEntity("当前api已被别的api引用，请先删除引用");
        }
        //判断esb是否有使用
        SysMessageManageEntity checkMessageManage = new SysMessageManageEntity();
        checkMessageManage.setSendApi(entity.getId());
        checkMessageManage.setSts("Y");
        Integer checkMessageManageCount = sysMessageManageDao.getCount(checkMessageManage);
        if (checkMessageManageCount != null && checkMessageManageCount > 0) {
            return BaseResult.getFailureMessageEntity("当前api已再esb中心配置，请先删除引用");
        }
        SysMessageManageDetailEntity checkMessageManageDetail = new SysMessageManageDetailEntity();
        checkMessageManageDetail.setReceiveApi(entity.getId());
        checkMessageManageDetail.setSts("Y");
        Integer checkMessageManageDetailCount = sysMessageManageDetailDao.getCount(checkMessageManageDetail);
        if (checkMessageManageDetailCount != null && checkMessageManageDetailCount > 0) {
            return BaseResult.getFailureMessageEntity("当前api已再esb中心配置，请先删除引用");
        }
        //删除
        SysApplicationApiEntity sysApplicationApiEntity = new SysApplicationApiEntity();
        sysApplicationApiEntity.setId(entity.getId());
        sysApplicationApiEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        sysApplicationApiEntity.setModify_time(new Date());
        sysApplicationApiEntity.setSts("Y");
        sysApplicationApiDao.logicRemove(sysApplicationApiEntity);
        applicationCache.reloadData("2");
        return BaseResult.getSuccessMessageEntity("删除成功");
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description api新增接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveApi(JSONObject object) {
        SysApplicationApiEntity entity = getData("jsonStr", object, SysApplicationApiEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getApiName() == null || "".equals(entity.getApiName())) {
            return BaseResult.getFailureMessageEntity("请先输入接口名称");
        }
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationApiEntity checkEntity = new SysApplicationApiEntity();
        checkEntity.setSts("Y");
        checkEntity.setApiName(entity.getApiName());
        checkEntity.setAppId(entity.getAppId());
        int checkCount = sysApplicationApiDao.getCount(checkEntity);
        if (checkCount > 0) {
            return BaseResult.getFailureMessageEntity("接口名称已存在");
        }
        entity.setId(UUIDUtils.getUUID());
        entity.setSts("Y");
        entity.setCreate_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setCreate_time(new Date());
        entity.setModify_time(new Date());
        sysApplicationApiDao.save(entity);
        applicationCache.reloadData("2");
        return BaseResult.getSuccessMessageEntity("保存接口成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description api修改接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity updateApi(JSONObject object) {
        SysApplicationApiEntity entity = getData("jsonStr", object, SysApplicationApiEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getApiName() == null || "".equals(entity.getApiName())) {
            return BaseResult.getFailureMessageEntity("请先输入接口名称");
        }
        if (entity.getAppId() == null || "".equals(entity.getAppId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationApiEntity checkEntity = new SysApplicationApiEntity();
        checkEntity.setSts("Y");
        checkEntity.setId(entity.getId());
        checkEntity.setApiName(entity.getApiName());
        checkEntity.setAppId(entity.getAppId());
        int checkCount = sysApplicationApiDao.entity_count_not_id(checkEntity);
        if (checkCount > 0) {
            return BaseResult.getFailureMessageEntity("接口名称已存在");
        }
        entity.setSts("Y");
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_time(new Date());
        sysApplicationApiDao.update(entity);
        applicationCache.reloadData("2");
        return BaseResult.getSuccessMessageEntity("修改接口成功", entity.getId());

    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 三方调用系统查询接口 根据应用查询三方调用系统
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppApiAuth(JSONObject object) {
        SysApplicationApiAuthEntity entity = getData("jsonStr", object, SysApplicationApiAuthEntity.class);
        List<SysApplicationApiAuthEntity> apiAuthEntities = sysApplicationApiAuthDao.queryByLike(entity);
        return BaseResult.getSuccessMessageEntity("查询三方调用系统成功", apiAuthEntities);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 三方调用系统保存接口 保存三方系统，全量修改保存，同步删除api关联三方系统配置表已经删除的三方调用系统接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveAppApiAuth(JSONObject object) {

        SysApplicationApiAuthDto entity = getData("jsonStr", object, SysApplicationApiAuthDto.class);
        //判断编码是否重复
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("请先填写内容");
        }
        //删除
        SysApplicationApiAuthEntity sysApplicationApiAuthEntity = new SysApplicationApiAuthEntity();
        sysApplicationApiAuthEntity.setAppId(entity.getAppId());
        sysApplicationApiAuthEntity.setModify_user_id(StpUtil.getLoginIdAsString());
        sysApplicationApiAuthEntity.setModify_time(new Date());
        sysApplicationApiAuthEntity.setSts("Y");
        sysApplicationApiAuthDao.logicRemoveMultiCondition(sysApplicationApiAuthEntity);
        List<String> tripartiteSystemIds = new ArrayList<>();
        //添加
        List<SysApplicationApiAuthEntity> apiAuths = entity.getApiAuths();
        if (apiAuths != null && apiAuths.size() > 0) {
            for (int i = 0; i < apiAuths.size(); i++) {
                apiAuths.get(i).setAppId(entity.getAppId());
                apiAuths.get(i).setSts("Y");
                apiAuths.get(i).setModify_user_id(StpUtil.getLoginIdAsString());
                apiAuths.get(i).setModify_time(new Date());
                if (apiAuths.get(i).getId() != null && !"".equals(apiAuths.get(i).getId())) {
                    //修改
                    tripartiteSystemIds.add(apiAuths.get(i).getId());
                    sysApplicationApiAuthDao.update(apiAuths.get(i));
                } else {
                    //新增
                    apiAuths.get(i).setId(UUIDUtils.getUUID());
                    apiAuths.get(i).setCreate_user_id(StpUtil.getLoginIdAsString());
                    apiAuths.get(i).setCreate_time(new Date());
                    tripartiteSystemIds.add(apiAuths.get(i).getId());
                    sysApplicationApiAuthDao.save(apiAuths.get(i));
                }
            }
        }
        //删除三方系统关联表
        SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = new SysApplicationApiAuthDetailEntity();
        sysApplicationApiAuthDetailEntity.setAppId(entity.getAppId());
        sysApplicationApiAuthDetailEntity.setTripartiteSystemIds(tripartiteSystemIds);
        sysApplicationApiAuthDetailDao.updateDeleteTripartiteSystem(sysApplicationApiAuthDetailEntity);
        applicationCache.reloadData("3");
        applicationCache.reloadData("4");
        return BaseResult.getSuccessMessageEntity("保存成功");
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description api关联三方系统保存接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveAppApiAuthDetail(JSONObject object) {
        SysApplicationApiAuthDetailEntity entity = getData("jsonStr", object, SysApplicationApiAuthDetailEntity.class);
        //判断编码是否重复
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("请先填写内容");
        }
        if (entity.getStatusType() == null || "".equals(entity.getStatusType())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //状态 1、取消选择 2、选择
        if ("1".equals(entity.getStatusType())) {
            SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = new SysApplicationApiAuthDetailEntity();
            //sysApplicationApiAuthDetailEntity.setSts("N");
            sysApplicationApiAuthDetailEntity.setModify_user_id(StpUtil.getLoginIdAsString());
            sysApplicationApiAuthDetailEntity.setModify_time(new Date());
            sysApplicationApiAuthDetailEntity.setAppId(entity.getAppId());
            sysApplicationApiAuthDetailEntity.setCatalogueId(entity.getCatalogueId());
            sysApplicationApiAuthDetailEntity.setApiId(entity.getApiId());
            sysApplicationApiAuthDetailEntity.setTripartiteSystemId(entity.getTripartiteSystemId());
            sysApplicationApiAuthDetailDao.logicRemoveMultiCondition(sysApplicationApiAuthDetailEntity);
            applicationCache.reloadData("4");
            return BaseResult.getSuccessMessageEntity("取消关联成功");

        } else {
            SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = new SysApplicationApiAuthDetailEntity();
            sysApplicationApiAuthDetailEntity.setAppId(entity.getAppId());
            sysApplicationApiAuthDetailEntity.setCatalogueId(entity.getCatalogueId());
            sysApplicationApiAuthDetailEntity.setApiId(entity.getApiId());
            sysApplicationApiAuthDetailEntity.setTripartiteSystemId(entity.getTripartiteSystemId());
            List<SysApplicationApiAuthDetailEntity> sysApplicationApiAuthDetailEntities = sysApplicationApiAuthDetailDao.queryBase(sysApplicationApiAuthDetailEntity);
            if (sysApplicationApiAuthDetailEntities != null && sysApplicationApiAuthDetailEntities.size() > 0) {
                sysApplicationApiAuthDetailEntity = sysApplicationApiAuthDetailEntities.get(0);
                sysApplicationApiAuthDetailEntity.setSts("Y");
                sysApplicationApiAuthDetailEntity.setModify_user_id(StpUtil.getLoginIdAsString());
                sysApplicationApiAuthDetailEntity.setModify_time(new Date());
                sysApplicationApiAuthDetailDao.update(sysApplicationApiAuthDetailEntity);
                applicationCache.reloadData("4");
            } else {
                sysApplicationApiAuthDetailEntity.setId(UUIDUtils.getUUID());
                sysApplicationApiAuthDetailEntity.setSts("Y");
                sysApplicationApiAuthDetailEntity.setCreate_user_id(StpUtil.getLoginIdAsString());
                sysApplicationApiAuthDetailEntity.setModify_user_id(StpUtil.getLoginIdAsString());
                sysApplicationApiAuthDetailEntity.setCreate_time(new Date());
                sysApplicationApiAuthDetailEntity.setModify_time(new Date());
                sysApplicationApiAuthDetailDao.save(sysApplicationApiAuthDetailEntity);
                applicationCache.reloadData("4");
            }
            return BaseResult.getSuccessMessageEntity("关联成功");
        }
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 插件查询接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppPlugin(JSONObject object) {
        SysApplicationPluginDto entity = getData("jsonStr", object, SysApplicationPluginDto.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<SysApplicationPluginEntity> sysApplicationPluginEntities = sysApplicationPluginDao.queryListlike(entity);
        PageInfo pageInfo = new PageInfo(sysApplicationPluginEntities);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 插件保存接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveAppPlugin(JSONObject object) {
        SysApplicationPluginEntity entity = getData("jsonStr", object, SysApplicationPluginEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        entity.setId(UUIDUtils.getUUID());
        entity.setSts("Y");
        entity.setCreate_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setCreate_time(new Date());
        entity.setModify_time(new Date());
        sysApplicationPluginDao.save(entity);
        return BaseResult.getSuccessMessageEntity("保存插件成功", entity.getId());
    }

    @Override
    public JsonResultEntity deleteAppPluginPackage(JSONObject object){
        SysApplicationPluginEntity entity = getData("jsonStr", object, SysApplicationPluginEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        String pluginPackageName = entity.getPluginPackageName();

        String classPath = TOMCATPATH + "com\\hzya\\frame\\plugin\\" + pluginPackageName;

        String xmlPath = TOMCATPATH + "cfgHome\\plugin\\" + pluginPackageName;

        try{
            deleteDirectory(classPath);
            deleteDirectory(xmlPath);
            System.out.println("Directory deleted successfully.");
        }catch (Exception e){
            return BaseResult.getFailureMessageEntity("删除插件包失败"+e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("删除插件包成功");
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 获取插件接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity getAppPlugin(JSONObject object) {
        SysApplicationPluginEntity entity = getData("jsonStr", object, SysApplicationPluginEntity.class);
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //查询接口
        SysApplicationPluginEntity sysApplicationPluginEntity = iIntegrationTaskCacheableService.getSysApplicationPluginEntity(entity.getId());
        return BaseResult.getSuccessMessageEntity("查询数据成功", sysApplicationPluginEntity);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 插件修改接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity updateAppPlugin(JSONObject object) {
        SysApplicationPluginEntity entity = getData("jsonStr", object, SysApplicationPluginEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_time(new Date());
        iIntegrationTaskCacheableService.updateSysApplicationPluginEntity(entity);
        return BaseResult.getSuccessMessageEntity("修改插件成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 插件删除接口
     * @Date 2:10 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity deleteAppPlugin(JSONObject object) {
        SysApplicationPluginEntity entity = getData("jsonStr", object, SysApplicationPluginEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setSts("N");
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_time(new Date());
        iIntegrationTaskCacheableService.updateSysApplicationPluginEntity(entity);
        return BaseResult.getSuccessMessageEntity("删除插件成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 插件启用停用接口
     * @Date 2:10 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity enableOrDisableAppPlugin(JSONObject object) {
        SysApplicationPluginEntity entity = getData("jsonStr", object, SysApplicationPluginEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getPluginStatus() == null || "".equals(entity.getPluginStatus())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setModify_user_id(StpUtil.getLoginIdAsString());
        entity.setModify_time(new Date());
        iIntegrationTaskCacheableService.updateSysApplicationPluginEntity(entity);
        if ("1".equals(entity.getPluginStatus())) {// 1启用2停用
            return BaseResult.getSuccessMessageEntity("启用成功");
        } else {
            return BaseResult.getSuccessMessageEntity("停用成功");
        }
    }


    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 查询api所有数据
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppAll(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //查询app
        SysApplicationEntity sysApplicationEntity = sysApplicationDao.get(entity.getId());
        //查询接口参数
        SysApplicationApiParaEntity sysApplicationApiParaEntity = new SysApplicationApiParaEntity();
        sysApplicationApiParaEntity.setSts("Y");
        sysApplicationApiParaEntity.setAppId(entity.getId());
        List<SysApplicationApiParaEntity> sysApplicationApiParaEntityList = sysApplicationApiParaDao.queryBase(sysApplicationApiParaEntity);

        SysApplicationDatabaseEntity sysApplicationDatabaseEntity = new SysApplicationDatabaseEntity();
        sysApplicationDatabaseEntity.setAppId(entity.getId());
        sysApplicationDatabaseEntity.setSts("Y");
        List<SysApplicationDatabaseEntity> list = sysApplicationDatabaseDao.queryBase(sysApplicationDatabaseEntity);

        if (list != null && list.size() > 0) {
            sysApplicationDatabaseEntity = list.get(0);
            sysApplicationDatabaseEntity.setPassword(AESUtil.decrypt(sysApplicationDatabaseEntity.getPassword()));
        } else {
            sysApplicationDatabaseEntity = null;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("app", sysApplicationEntity);
        jsonObject.put("databaseEntity", sysApplicationDatabaseEntity);
        jsonObject.put("apiParas", sysApplicationApiParaEntityList);
        return BaseResult.getSuccessMessageEntity("查询数据成功", jsonObject);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用接口启用停用接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity enableOrDisableAppApi(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getInterfaceStatus() == null || "".equals(entity.getInterfaceStatus())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //接口环境是否启用（1、开启 2、关闭）
        if ("1".equals(entity.getInterfaceStatus())) {// 1启用2停用
            //判断接口参数是否存在，如果存在判断是否有值
            //查询接口参数
            SysApplicationApiParaEntity sysApplicationApiParaEntity = new SysApplicationApiParaEntity();
            sysApplicationApiParaEntity.setSts("Y");
            sysApplicationApiParaEntity.setAppId(entity.getId());
            List<SysApplicationApiParaEntity> sysApplicationApiParaEntityList = sysApplicationApiParaDao.queryBase(sysApplicationApiParaEntity);
            boolean flag = true;
            if (sysApplicationApiParaEntityList != null && sysApplicationApiParaEntityList.size() > 0) {
                for (int i = 0; i < sysApplicationApiParaEntityList.size(); i++) {
                    if (sysApplicationApiParaEntityList.get(i).getInterfaceKey() == null || "".equals(sysApplicationApiParaEntityList.get(i).getInterfaceKey())
                            || sysApplicationApiParaEntityList.get(i).getInterfaceType() == null || "".equals(sysApplicationApiParaEntityList.get(i).getInterfaceType())
                            || sysApplicationApiParaEntityList.get(i).getInterfaceValue() == null || "".equals(sysApplicationApiParaEntityList.get(i).getInterfaceValue())) {
                        flag = false;
                        break;
                    }

                }
            }
            if (flag) {
                //查询接口参数
                SysApplicationEntity sysApplicationEntity = new SysApplicationEntity();
                sysApplicationEntity.setSts("Y");
                sysApplicationEntity.setId(entity.getId());
                sysApplicationEntity.setInterfaceStatus(entity.getInterfaceStatus());
                sysApplicationEntity.setModify_user_id(StpUtil.getLoginIdAsString());
                sysApplicationEntity.setModify_time(new Date());
                sysApplicationDao.update(sysApplicationEntity);
                applicationCache.reloadData("1");
                return BaseResult.getSuccessMessageEntity("启用成功");
            } else {
                return BaseResult.getFailureMessageEntity("接口参数配置不完整，请先配置参数");
            }
        } else {
            //查询接口参数
            SysApplicationEntity sysApplicationEntity = new SysApplicationEntity();
            sysApplicationEntity.setSts("Y");
            sysApplicationEntity.setId(entity.getId());
            sysApplicationEntity.setInterfaceStatus(entity.getInterfaceStatus());
            sysApplicationEntity.setModify_user_id(StpUtil.getLoginIdAsString());
            sysApplicationEntity.setModify_time(new Date());
            sysApplicationDao.update(sysApplicationEntity);
            applicationCache.reloadData("1");
            return BaseResult.getSuccessMessageEntity("停用成功");
        }
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用数据源启用停用接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity enableOrDisableAppDatasource(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getDbStatus() == null || "".equals(entity.getDbStatus())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //接口环境是否启用（1、开启 2、关闭）
        if ("1".equals(entity.getDbStatus())) {// 1启用2停用
            //判断接口参数是否存在，如果存在判断是否有值
            //查询接口参数
            SysApplicationDatabaseEntity sysApplicationDatabaseEntity = new SysApplicationDatabaseEntity();
            sysApplicationDatabaseEntity.setSts("Y");
            sysApplicationDatabaseEntity.setAppId(entity.getId());
            List<SysApplicationDatabaseEntity> sysApplicationDatabaseEntityList = sysApplicationDatabaseDao.queryBase(sysApplicationDatabaseEntity);
            boolean flag = true;
            if (sysApplicationDatabaseEntityList != null && sysApplicationDatabaseEntityList.size() > 0) {
                if (sysApplicationDatabaseEntityList.get(0).getSourceType() == null || "".equals(sysApplicationDatabaseEntityList.get(0).getSourceType())
                        || sysApplicationDatabaseEntityList.get(0).getSourceUrl() == null || "".equals(sysApplicationDatabaseEntityList.get(0).getSourceUrl())
                        || sysApplicationDatabaseEntityList.get(0).getPassword() == null || "".equals(sysApplicationDatabaseEntityList.get(0).getPassword())
                        || sysApplicationDatabaseEntityList.get(0).getDbName() == null || "".equals(sysApplicationDatabaseEntityList.get(0).getDbName())
                        || sysApplicationDatabaseEntityList.get(0).getLoginName() == null || "".equals(sysApplicationDatabaseEntityList.get(0).getLoginName())) {
                    flag = false;
                }
                if (flag) {
                    //校验连接
                    SysApplicationDatasourceDto testDb = new SysApplicationDatasourceDto();
                    testDb.setSourceUrl(sysApplicationDatabaseEntityList.get(0).getSourceUrl());
                    testDb.setLoginName(sysApplicationDatabaseEntityList.get(0).getLoginName());
                    testDb.setPassword(sysApplicationDatabaseEntityList.get(0).getPassword());
                    testDb.setSourceType(sysApplicationDatabaseEntityList.get(0).getSourceType());
                    if (dsDataSourceUtil.testConnection(testDb)) {
                        sysApplicationDatabaseEntity = sysApplicationDatabaseEntityList.get(0);
                        sysApplicationDatabaseEntity.setDbStatus(entity.getDbStatus());
                        sysApplicationDatabaseEntity.setModify_user_id(StpUtil.getLoginIdAsString());
                        sysApplicationDatabaseEntity.setModify_time(new Date());
                        sysApplicationDatabaseDao.update(sysApplicationDatabaseEntity);
                        //查询接口参数
                        SysApplicationEntity sysApplicationEntity = new SysApplicationEntity();
                        sysApplicationEntity.setSts("Y");
                        sysApplicationEntity.setId(entity.getId());
                        sysApplicationEntity.setDbStatus(entity.getDbStatus());
                        sysApplicationEntity.setModify_user_id(StpUtil.getLoginIdAsString());
                        sysApplicationEntity.setModify_time(new Date());
                        sysApplicationDao.update(sysApplicationEntity);
                        applicationCache.reloadData("1");
                        return BaseResult.getSuccessMessageEntity("启用成功");
                    } else {
                        return BaseResult.getFailureMessageEntity("数据源连接失败，请先配置参数");
                    }
                } else {
                    return BaseResult.getFailureMessageEntity("数据源配置不完整，请先配置参数");
                }
            } else {
                return BaseResult.getFailureMessageEntity("请先配置数据源");
            }

        } else {
            SysApplicationDatabaseEntity sysApplicationDatabaseEntity = new SysApplicationDatabaseEntity();
            sysApplicationDatabaseEntity.setSts("Y");
            sysApplicationDatabaseEntity.setAppId(entity.getId());
            sysApplicationDatabaseEntity.setAppId(entity.getId());
            sysApplicationDatabaseEntity.setDbStatus(entity.getDbStatus());
            sysApplicationDatabaseDao.update(sysApplicationDatabaseEntity);
            //查询接口参数
            SysApplicationEntity sysApplicationEntity = new SysApplicationEntity();
            sysApplicationEntity.setSts("Y");
            sysApplicationEntity.setId(entity.getId());
            sysApplicationEntity.setDbStatus(entity.getDbStatus());
            sysApplicationEntity.setModify_user_id(StpUtil.getLoginIdAsString());
            sysApplicationEntity.setModify_time(new Date());
            sysApplicationDao.update(sysApplicationEntity);
            applicationCache.reloadData("1");
            return BaseResult.getSuccessMessageEntity("停用成功");
        }
    }

    /**
     * @param servletRequest
     * @param servletResponse
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 外部系统调用接口
     * @Date 4:21 下午 2023/10/19
     **/
    @Override
    @DSTransactional()
    public JsonResultEntity externalCallInterface(ServletRequest servletRequest, ServletResponse servletResponse) {
        //例如：A应用发送数据到中台，中台转发到B应用
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String oldbodys = ServletUtil.getBody(servletRequest);
        Map<String, String> oldheaderMap = ServletUtil.getHeaderMap(request);
        String oldquerys = request.getQueryString();
        //应用key
        String publicKey = request.getHeader("publicKey");
        //应用密钥
        String secretKey = request.getHeader("secretKey");
        //appId
        String appId = request.getHeader("appId");
        //apiCode
        String apiCode = request.getHeader("apiCode");

        String ip = IPHelper.getIpAddr(request);
        if (publicKey == null || "".equals(publicKey)) {
            return BaseResult.getFailureMessageEntity("请先传递公钥");
        }
        if (secretKey == null || "".equals(secretKey)) {
            return BaseResult.getFailureMessageEntity("请先传递密钥");
        }
        if (appId == null || "".equals(appId)) {
            return BaseResult.getFailureMessageEntity("请先传递接收方应用");
        }
        if (apiCode == null || "".equals(apiCode)) {
            return BaseResult.getFailureMessageEntity("请先传递发送接口");
        }

        logger.info("请求参数：publicKey：【" + publicKey + "】secretKey：【" + secretKey + "】appId：【" + appId + "】apiCode：【" + apiCode);
        //根据请求a应用的公钥、密钥是否能查找到一条数据

        SysApplicationEntity sendApp = getAppByPublicKeySecretKey(publicKey, secretKey);
        if (sendApp == null) {
            //saveLog(new SysApplicationEntity(), new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"公钥、密钥错误");
            return BaseResult.getFailureMessageEntity("公钥、密钥错误,请联系管理员");
        }
        //判断应用是否启用
        if (sendApp.getAppStatus() == null || !"1".equals(sendApp.getAppStatus())) {
            saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,sendApp.getName() + "应用未启用");
            return BaseResult.getFailureMessageEntity(sendApp.getName() + "应用未启用,请联系管理员");
        }


        SysApplicationEntity receiveApp = getAppByAppId(appId);
        if (receiveApp == null) {
            saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"根据appId:" + appId + "未匹配到应用");
            return BaseResult.getFailureMessageEntity("根据appId:" + appId + "未匹配到应用,请联系管理员");
        }
        //判断应用是否启用
        if (receiveApp.getAppStatus() == null || !"1".equals(receiveApp.getAppStatus())) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用未启用" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用未启用,请联系管理员");
        }
        //判断应用接口是否启用
        if (receiveApp.getInterfaceStatus() == null || !"1".equals(receiveApp.getInterfaceStatus())) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用接口环境未启用" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用接口环境未启用,请联系管理员");
        }

        SysApplicationApiEntity receiveApi = getApiByAppIdApiCode(receiveApp.getId(), apiCode);
        if (receiveApi == null) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + ":" + apiCode + "未启用或者未创建" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + ":" + apiCode + "未启用或者未创建");
        }

        SysApplicationApiAuthEntity sysApplicationApiAuthEntity = getApiAuthByNameAppId(sendApp.getId(), receiveApp.getId());
        if (sysApplicationApiAuthEntity == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用权限配置错误" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用权限配置错误");
        }
        if (sysApplicationApiAuthEntity.getSystemAddress() != null && !"".equals(sysApplicationApiAuthEntity.getSystemAddress())
                && !sysApplicationApiAuthEntity.getSystemAddress().contains(ip)) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误");
        }

        SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = getApiAuthDetailByAppIdApiIdTripartiteSystemId(receiveApp.getId(), receiveApi.getId(), sysApplicationApiAuthEntity.getId());
        if (sysApplicationApiAuthDetailEntity == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApi.getApiName() + "未授权给" + sendApp.getName() );
            return BaseResult.getFailureMessageEntity(receiveApi.getApiName() + "未授权给" + sendApp.getName() + "，请联系管理员");
        }
        SysExtensionApiEntity sysExtensionApiEntity = new SysExtensionApiEntity();


        List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        Map<String, String> headers = new HashMap<>();
        if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
            JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    headers.put(object1.getString("parameterName"), object1.getString("example"));
                }
            }
        }
        if (oldheaderMap != null && oldheaderMap.size() > 0) {
            for (Map.Entry<String, String> entry : oldheaderMap.entrySet()) {
                if (!a.contains(entry.getKey())) {
                    headers.put(entry.getKey(), entry.getValue());
                }
            }
        }



        sysExtensionApiEntity.setSendApp(sendApp);
        sysExtensionApiEntity.setReceiveApp(receiveApp);
        sysExtensionApiEntity.setReceiveApi(receiveApi);
        sysExtensionApiEntity.setHeaders(headers);
        sysExtensionApiEntity.setQuerys(oldquerys);
        sysExtensionApiEntity.setBodys(oldbodys);
        Method[] methods = null;
        Object object = null;




        // 判断是否有内部api 是否扩展api 1、启用 2、停用
        if (receiveApi.getExtensionApi() != null && "1".equals(receiveApi.getExtensionApi())
                && receiveApi.getBeanName() != null && !"".equals(receiveApi.getBeanName())
                && receiveApi.getFunName() != null && !"".equals(receiveApi.getFunName())
        ) {
            //获取类
            try {
                object = ApplicationContextUtil.getBeanByName(receiveApi.getBeanName());
            } catch (SecurityException e) {

            }
            //获取类下面的方法
            methods = object.getClass().getMethods();
            if (methods == null || methods.length == 0) {
                return BaseResult.getFailureMessageEntity("未找到内部方法，请联系管理员");
            }
            for (Method m : methods) {
                if (null != m) {
                    if (m.getName().equals(receiveApi.getFunName().trim())) {
                        try {
                            logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            sysExtensionApiEntity = (SysExtensionApiEntity) m.invoke(object, sysExtensionApiEntity);
                            logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            break;
                        } catch (Exception e) {
                            logger.error("invokeException{}", e.getMessage());
                            return BaseResult.getFailureMessageEntity("内部方法执行错误，请联系管理员");
                        }
                    }
                }
            }

        }
        headers = sysExtensionApiEntity.getHeaders();
        String querys = sysExtensionApiEntity.getQuerys();
        String bodys = sysExtensionApiEntity.getBodys();
        //设置参数获取参数
        StringBuffer url = new StringBuffer();
        if(!receiveApi.getDestinationAddress().toLowerCase().startsWith("http")){
            url.append(receiveApp.getInterfaceAddress());
        }
        url.append(receiveApi.getDestinationAddress());
        if (querys != null) {
            url.append("?");
            url.append(querys);
        }
        Integer outTime = 6000;
        if (receiveApi.getTimeoutPeriod() != null && !"".equals(receiveApi.getTimeoutPeriod())) {
            outTime = Integer.valueOf(receiveApi.getTimeoutPeriod());
        }
        //1、POST 2、GET
        String method = "POST";
        if ("2".equals(receiveApi.getRequestMethod())) {
            method = "GET";
        }
        //List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        //Map<String, String> headers = new HashMap<>();
        //if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
        //    JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
        //    if (jsonArray != null && jsonArray.size() > 0) {
        //        for (int i = 0; i < jsonArray.size(); i++) {
        //            JSONObject object1 = jsonArray.getJSONObject(i);
        //            headers.put(object1.getString("parameterName"), object1.getString("example"));
        //        }
        //    }
        //}
        //if (headerMap != null && headerMap.size() > 0) {
        //    for (Map.Entry<String, String> entry : headerMap.entrySet()) {
        //        if (!a.contains(entry.getKey())) {
        //            headers.put(entry.getKey(), entry.getValue());
        //        }
        //    }
        //}


        if ("POST".equals(method)) {

            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            //CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            // 创建一个 CloseableHttpClient 并配置 SSL 上下文和主机名验证器
            // 创建一个信任所有证书的 SSLContext
            SSLContext sslContext = null;
            try {
                sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, TrustAllStrategy.INSTANCE)
                        .build();
            } catch (Exception e) {

            }
            CloseableHttpClient closeableHttpClient = HttpClients.custom()
                    .setSSLContext(sslContext)
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

            //HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            //CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpPost post = new HttpPost(url.toString());
            CloseableHttpResponse response = null;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).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();
                }

            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(),true,null);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), jsonObject);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
                        }
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", body);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), body);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", body);
                        }
                    }
                }
            } else {
                if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                    return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), body);
                }else {
                    return BaseResult.getFailureMessageEntity("转发失败", body);
                }
            }

        } else {//GET

            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpGet get = new HttpGet(url.toString());
            CloseableHttpResponse response = null;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).build();
            get.setConfig(requestConfig);//设置请求参数【超时时间】
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    get.setHeader(key, headers.get(key));
                }
            }
            StringBuilder body = new StringBuilder();

            boolean flag = true;
            try {

                response = closeableHttpClient.execute(get);
                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();
                }
            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(), true,null);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), jsonObject);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
                        }
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", body);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), body);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", body);
                        }
                    }
                }
            } else {
                return BaseResult.getFailureMessageEntity("转发失败", body);
            }
        }
    }

    /**
     * @param servletRequest
     * @param servletResponse
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 外部系统调用接口
     * @Date 4:21 下午 2023/10/19
     **/
    @Override
    @DSTransactional()
    public JsonResultEntity externalCallInterfacefileUpload(ServletRequest servletRequest, ServletResponse servletResponse) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) servletRequest;
        // 获取普通表单参数
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        Map<String, String> oldheaderMap = ServletUtil.getHeaderMap(request);
        //应用key
        String publicKey = request.getHeader("publicKey");
        //应用密钥
        String secretKey = request.getHeader("secretKey");
        //appId
        String appId = request.getHeader("appId");
        //apiCode
        String apiCode = request.getHeader("apiCode");

        Enumeration<String> bodyname = multipartRequest.getParameterNames();
        JSONObject bodysss = new JSONObject();
        if (bodyname.hasMoreElements()) {
            while (bodyname.hasMoreElements()) {
                String headerName = bodyname.nextElement();
                String headerValue = multipartRequest.getParameter(headerName);
                bodysss.put( headerName,headerValue);
            }
        }
        String oldquerys = multipartRequest.getQueryString();
        String oldbodys = bodysss.toJSONString();
        Iterator<String> filenemes = multipartRequest.getFileNames();
        Map<String, List<MultipartFile>> files =  new HashMap<>();

        if (filenemes.hasNext()) {
            filenemes.forEachRemaining(element -> files.put(element,multipartRequest.getFiles(element)));
        }

        String ip = IPHelper.getIpAddr(multipartRequest);
        if (publicKey == null || "".equals(publicKey)) {
            return BaseResult.getFailureMessageEntity("请先传递公钥");
        }
        if (secretKey == null || "".equals(secretKey)) {
            return BaseResult.getFailureMessageEntity("请先传递密钥");
        }
        if (appId == null || "".equals(appId)) {
            return BaseResult.getFailureMessageEntity("请先传递接收方应用");
        }
        if (apiCode == null || "".equals(apiCode)) {
            return BaseResult.getFailureMessageEntity("请先传递发送接口");
        }

        logger.info("请求参数：publicKey：【" + publicKey + "】secretKey：【" + secretKey + "】appId：【" + appId + "】apiCode：【" + apiCode);
        //根据请求a应用的公钥、密钥是否能查找到一条数据

        SysApplicationEntity sendApp = getAppByPublicKeySecretKey(publicKey, secretKey);
        if (sendApp == null) {
            return BaseResult.getFailureMessageEntity("公钥、密钥错误,请联系管理员");
        }
        //判断应用是否启用
        if (sendApp.getAppStatus() == null || !"1".equals(sendApp.getAppStatus())) {
            saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,sendApp.getName() + "应用未启用");
            return BaseResult.getFailureMessageEntity(sendApp.getName() + "应用未启用,请联系管理员");
        }


        SysApplicationEntity receiveApp = getAppByAppId(appId);
        if (receiveApp == null) {
            saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"根据appId:" + appId + "未匹配到应用");
            return BaseResult.getFailureMessageEntity("根据appId:" + appId + "未匹配到应用,请联系管理员");
        }
        //判断应用是否启用
        if (receiveApp.getAppStatus() == null || !"1".equals(receiveApp.getAppStatus())) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用未启用" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用未启用,请联系管理员");
        }
        //判断应用接口是否启用
        if (receiveApp.getInterfaceStatus() == null || !"1".equals(receiveApp.getInterfaceStatus())) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用接口环境未启用" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用接口环境未启用,请联系管理员");
        }

        SysApplicationApiEntity receiveApi = getApiByAppIdApiCode(receiveApp.getId(), apiCode);
        if (receiveApi == null) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + ":" + apiCode + "未启用或者未创建" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + ":" + apiCode + "未启用或者未创建");
        }

        SysApplicationApiAuthEntity sysApplicationApiAuthEntity = getApiAuthByNameAppId(sendApp.getId(), receiveApp.getId());
        if (sysApplicationApiAuthEntity == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用权限配置错误" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用权限配置错误");
        }
        if (sysApplicationApiAuthEntity.getSystemAddress() != null && !"".equals(sysApplicationApiAuthEntity.getSystemAddress())
                && !sysApplicationApiAuthEntity.getSystemAddress().contains(ip)) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误");
        }

        SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = getApiAuthDetailByAppIdApiIdTripartiteSystemId(receiveApp.getId(), receiveApi.getId(), sysApplicationApiAuthEntity.getId());
        if (sysApplicationApiAuthDetailEntity == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApi.getApiName() + "未授权给" + sendApp.getName() );
            return BaseResult.getFailureMessageEntity(receiveApi.getApiName() + "未授权给" + sendApp.getName() + "，请联系管理员");
        }
        SysExtensionApiEntity sysExtensionApiEntity = new SysExtensionApiEntity();


        List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        Map<String, String> headers = new HashMap<>();
        if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
            JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    headers.put(object1.getString("parameterName"), object1.getString("example"));
                }
            }
        }
        if (oldheaderMap != null && oldheaderMap.size() > 0) {
            for (Map.Entry<String, String> entry : oldheaderMap.entrySet()) {
                if (!a.contains(entry.getKey())) {
                    headers.put(entry.getKey(), entry.getValue());
                }
            }
        }



        sysExtensionApiEntity.setSendApp(sendApp);
        sysExtensionApiEntity.setReceiveApp(receiveApp);
        sysExtensionApiEntity.setReceiveApi(receiveApi);
        sysExtensionApiEntity.setHeaders(headers);
        sysExtensionApiEntity.setQuerys(oldquerys);
        sysExtensionApiEntity.setBodys(oldbodys);
        Method[] methods = null;
        Object object = null;




        // 判断是否有内部api 是否扩展api 1、启用 2、停用
        if (receiveApi.getExtensionApi() != null && "1".equals(receiveApi.getExtensionApi())
                && receiveApi.getBeanName() != null && !"".equals(receiveApi.getBeanName())
                && receiveApi.getFunName() != null && !"".equals(receiveApi.getFunName())
        ) {
            //获取类
            try {
                object = ApplicationContextUtil.getBeanByName(receiveApi.getBeanName());
            } catch (SecurityException e) {

            }
            //获取类下面的方法
            methods = object.getClass().getMethods();
            if (methods == null || methods.length == 0) {
                return BaseResult.getFailureMessageEntity("未找到内部方法，请联系管理员");
            }
            for (Method m : methods) {
                if (null != m) {
                    if (m.getName().equals(receiveApi.getFunName().trim())) {
                        try {
                            logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            sysExtensionApiEntity = (SysExtensionApiEntity) m.invoke(object, sysExtensionApiEntity);
                            logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            break;
                        } catch (Exception e) {
                            logger.error("invokeException{}", e.getMessage());
                            return BaseResult.getFailureMessageEntity("内部方法执行错误，请联系管理员");
                        }
                    }
                }
            }

        }
        headers = sysExtensionApiEntity.getHeaders();
        String querys = sysExtensionApiEntity.getQuerys();
        String bodys = sysExtensionApiEntity.getBodys();
        //设置参数获取参数
        StringBuffer url = new StringBuffer();
        if(!receiveApi.getDestinationAddress().toLowerCase().startsWith("http")){
            url.append(receiveApp.getInterfaceAddress());
        }
        url.append(receiveApi.getDestinationAddress());
        if (querys != null) {
            url.append("?");
            url.append(querys);
        }
        Integer outTime = 6000;
        if (receiveApi.getTimeoutPeriod() != null && !"".equals(receiveApi.getTimeoutPeriod())) {
            outTime = Integer.valueOf(receiveApi.getTimeoutPeriod());
        }
        //1、POST 2、GET
        String method = "POST";
        if ("2".equals(receiveApi.getRequestMethod())) {
            method = "GET";
        }

        if ("POST".equals(method)) {
            StringBuilder body = new StringBuilder();
            boolean flag = true;

            try {
                HttpPost httpPost = new HttpPost(url.toString());
                MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                if(!files.isEmpty()){
                    for (Map.Entry<String, List<MultipartFile>> entry : files.entrySet()) {
                        String key = entry.getKey();
                        List<MultipartFile> multipartFile = entry.getValue();
                        if(multipartFile != null && multipartFile.size() > 0){
                            for (int i = 0; i < multipartFile.size(); i++) {
                                File file = new File(multipartFile.get(i).getOriginalFilename());
                                Files.write(Paths.get(file.getAbsolutePath()), multipartFile.get(i).getBytes());
                                builder.addBinaryBody(key, file, ContentType.APPLICATION_OCTET_STREAM, file.getName());
                            }
                        }
                    }
                }
                if (headers != null && headers.size() > 0) {
                    for (String key : headers.keySet()) {
                        httpPost.setHeader(key, headers.get(key));
                    }
                }
                //if (bodys != null && !"".equals(bodys)) {
                //    builder.addTextBody("fileFlag", "true", ContentType.TEXT_PLAIN);
                //    builder.addTextBody("businessType", "application", ContentType.TEXT_PLAIN);
                //}
                HttpEntity entity = builder.build();
                httpPost.setEntity(entity);

                HttpResponse response = null;
                response = HttpClientBuilder.create().build().execute(httpPost);

                HttpEntity entity1 = response.getEntity();
                synchronized (lock) {
                    body.append(EntityUtils.toString(entity1,"UTF-8"));
                }
                flag = true;
                logger.info("返回结果：" + body);
            } catch (Exception e) {
                logger.error("请求错误：" + e.getMessage());
                body.append(e.getMessage());
                flag = false;
            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(),true,null);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), jsonObject);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
                        }
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", body);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), body);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", body);
                        }
                    }
                }
            } else {
                if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                    return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), body);
                }else {
                    return BaseResult.getFailureMessageEntity("转发失败", body);
                }
            }
        } else {//GET

            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpGet get = new HttpGet(url.toString());
            CloseableHttpResponse response = null;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).build();
            get.setConfig(requestConfig);//设置请求参数【超时时间】
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    get.setHeader(key, headers.get(key));
                }
            }
            StringBuilder body = new StringBuilder();

            boolean flag = true;
            try {

                response = closeableHttpClient.execute(get);
                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();
                }
            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(), true,null);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), jsonObject);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
                        }
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", body);
                    }else {
                        if(sysMessageManageLogEntity.getReturnMsg()!= null&& !"".equals(sysMessageManageLogEntity.getReturnMsg())){
                            return BaseResult.getFailureMessageEntity("转发失败："+sysMessageManageLogEntity.getReturnMsg(), body);
                        }else {
                            return BaseResult.getFailureMessageEntity("转发失败", body);
                        }
                    }
                }
            } else {
                return BaseResult.getFailureMessageEntity("转发失败", body);
            }
        }
    }

    @Override
    @DSTransactional()
    public JsonResultEntity externalCallInterfaceResend(SysMessageManageLogEntity resendLogEntity) {

        JSONObject objectSourceData = JSON.parseObject(resendLogEntity.getSourceData());
        JSONObject headerObject = objectSourceData.getJSONObject("header");
        if (headerObject == null || headerObject.equals("")) {
            return BaseResult.getFailureMessageEntity("传入源数据为空");
        }
        JSONObject bodyObject = objectSourceData.getJSONObject("body");
        //将请求头转换为map
        Map<String, String> oldheaderMap = new HashMap<>();
        Iterator it = headerObject.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
            oldheaderMap.put(entry.getKey(), entry.getValue());
        }

        String oldId = resendLogEntity.getId();
        String oldbodys = bodyObject.toString();
        String oldquerys = "";
        //应用key
        String publicKey = headerObject.getString("publickey");
        //应用密钥
        String secretKey = headerObject.getString("secretkey");
        //appId
        String appId = headerObject.getString("appid");
        //apiCode
        String apiCode = headerObject.getString("apicode");
        String ip = headerObject.getString("x-real-ip");
        if (publicKey == null || "".equals(publicKey)) {
            return BaseResult.getFailureMessageEntity("请先传递公钥");
        }
        if (secretKey == null || "".equals(secretKey)) {
            return BaseResult.getFailureMessageEntity("请先传递密钥");
        }
        if (appId == null || "".equals(appId)) {
            return BaseResult.getFailureMessageEntity("请先传递接收方应用");
        }
        if (apiCode == null || "".equals(apiCode)) {
            return BaseResult.getFailureMessageEntity("请先传递发送接口");
        }

        logger.info("请求参数：publicKey：【" + publicKey + "】secretKey：【" + secretKey + "】appId：【" + appId + "】apiCode：【" + apiCode);
        //根据请求a应用的公钥、密钥是否能查找到一条数据

        SysApplicationEntity sendApp = getAppByPublicKeySecretKey(publicKey, secretKey);
        if (sendApp == null) {
            //saveLog(new SysApplicationEntity(), new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"公钥、密钥错误");
            return BaseResult.getFailureMessageEntity("公钥、密钥错误,请联系管理员");
        }
        //判断应用是否启用
        if (sendApp.getAppStatus() == null || !"1".equals(sendApp.getAppStatus())) {
            return BaseResult.getFailureMessageEntity(sendApp.getName() + "应用未启用,请联系管理员");
        }

        SysApplicationEntity receiveApp = getAppByAppId(appId);
        if (receiveApp == null) {
            return BaseResult.getFailureMessageEntity("根据appId:" + appId + "未匹配到应用,请联系管理员");
        }
        //判断应用是否启用
        if (receiveApp.getAppStatus() == null || !"1".equals(receiveApp.getAppStatus())) {
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用未启用,请联系管理员");
        }
        //判断应用接口是否启用
        if (receiveApp.getInterfaceStatus() == null || !"1".equals(receiveApp.getInterfaceStatus())) {
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用接口环境未启用,请联系管理员");
        }

        SysApplicationApiEntity receiveApi = getApiByAppIdApiCode(receiveApp.getId(), apiCode);
        if (receiveApi == null) {
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + ":" + apiCode + "未启用或者未创建");
        }

        SysApplicationApiAuthEntity sysApplicationApiAuthEntity = getApiAuthByNameAppId(sendApp.getId(), receiveApp.getId());
        if (sysApplicationApiAuthEntity == null) {
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用权限配置错误");
        }
        if (sysApplicationApiAuthEntity.getSystemAddress() != null && !"".equals(sysApplicationApiAuthEntity.getSystemAddress())
                && !sysApplicationApiAuthEntity.getSystemAddress().contains(ip)) {
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误");
        }

        SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = getApiAuthDetailByAppIdApiIdTripartiteSystemId(receiveApp.getId(), receiveApi.getId(), sysApplicationApiAuthEntity.getId());
        if (sysApplicationApiAuthDetailEntity == null) {
            return BaseResult.getFailureMessageEntity(receiveApi.getApiName() + "未授权给" + sendApp.getName() + "，请联系管理员");
        }
        SysExtensionApiEntity sysExtensionApiEntity = new SysExtensionApiEntity();


        List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        Map<String, String> headers = new HashMap<>();
        if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
            JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    headers.put(object1.getString("parameterName"), object1.getString("example"));
                }
            }
        }
        if (oldheaderMap != null && oldheaderMap.size() > 0) {
            for (Map.Entry<String, String> entry : oldheaderMap.entrySet()) {
                if (!a.contains(entry.getKey())) {
                    headers.put(entry.getKey(), entry.getValue());
                }
            }
        }

        sysExtensionApiEntity.setSendApp(sendApp);
        sysExtensionApiEntity.setReceiveApp(receiveApp);
        sysExtensionApiEntity.setReceiveApi(receiveApi);
        sysExtensionApiEntity.setHeaders(headers);
        sysExtensionApiEntity.setQuerys(oldquerys);
        sysExtensionApiEntity.setBodys(oldbodys);
        Method[] methods = null;
        Object object = null;

        // 判断是否有内部api 是否扩展api 1、启用 2、停用
        if (receiveApi.getExtensionApi() != null && "1".equals(receiveApi.getExtensionApi())
                && receiveApi.getBeanName() != null && !"".equals(receiveApi.getBeanName())
                && receiveApi.getFunName() != null && !"".equals(receiveApi.getFunName())
        ) {
            //获取类
            try {
                object = ApplicationContextUtil.getBeanByName(receiveApi.getBeanName());
            } catch (SecurityException e) {

            }
            //获取类下面的方法
            methods = object.getClass().getMethods();
            if (methods == null || methods.length == 0) {
                return BaseResult.getFailureMessageEntity("未找到内部方法，请联系管理员");
            }
            for (Method m : methods) {
                if (null != m) {
                    if (m.getName().equals(receiveApi.getFunName().trim())) {
                        try {
                            logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            sysExtensionApiEntity = (SysExtensionApiEntity) m.invoke(object, sysExtensionApiEntity);
                            logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            break;
                        } catch (Exception e) {
                            logger.error("invokeException{}", e.getMessage());
                            return BaseResult.getFailureMessageEntity("内部方法执行错误，请联系管理员");
                        }
                    }
                }
            }

        }
        headers = sysExtensionApiEntity.getHeaders();
        String querys = sysExtensionApiEntity.getQuerys();
        String bodys = sysExtensionApiEntity.getBodys();
        //设置参数获取参数
        StringBuffer url = new StringBuffer();
        if(!receiveApi.getDestinationAddress().toLowerCase().startsWith("http")){
            url.append(receiveApp.getInterfaceAddress());
        }
        url.append(receiveApi.getDestinationAddress());
        if (querys != null) {
            url.append("?");
            url.append(querys);
        }
        Integer outTime = 6000;
        if (receiveApi.getTimeoutPeriod() != null && !"".equals(receiveApi.getTimeoutPeriod())) {
            outTime = Integer.valueOf(receiveApi.getTimeoutPeriod());
        }
        //1、POST 2、GET
        String method = "POST";
        if ("2".equals(receiveApi.getRequestMethod())) {
            method = "GET";
        }
        //List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        //Map<String, String> headers = new HashMap<>();
        //if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
        //    JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
        //    if (jsonArray != null && jsonArray.size() > 0) {
        //        for (int i = 0; i < jsonArray.size(); i++) {
        //            JSONObject object1 = jsonArray.getJSONObject(i);
        //            headers.put(object1.getString("parameterName"), object1.getString("example"));
        //        }
        //    }
        //}
        //if (headerMap != null && headerMap.size() > 0) {
        //    for (Map.Entry<String, String> entry : headerMap.entrySet()) {
        //        if (!a.contains(entry.getKey())) {
        //            headers.put(entry.getKey(), entry.getValue());
        //        }
        //    }
        //}


        if ("POST".equals(method)) {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpPost post = new HttpPost(url.toString());
            CloseableHttpResponse response = null;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).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();
                }

            }
            logger.info("保存日志开始");
            //重写saveLog方法，利用他原有逻辑判断重推结果，根据重推结果，设置该条日志的状态
            SysMessageManageLogEntity sysMessageManageLogEntity = updateLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(),true,null,oldId);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("重推成功", jsonObject);
                    }else {
                        return BaseResult.getSuccessMessageEntity("重推失败", jsonObject);
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("重推成功", body);
                    }else {
                        return BaseResult.getSuccessMessageEntity("重推失败", body);
                    }
                }
            } else {
                return BaseResult.getSuccessMessageEntity("重推失败", body);
            }

        } else {//GET

            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpGet get = new HttpGet(url.toString());
            CloseableHttpResponse response = null;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).build();
            get.setConfig(requestConfig);//设置请求参数【超时时间】
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    get.setHeader(key, headers.get(key));
                }
            }
            StringBuilder body = new StringBuilder();

            boolean flag = true;
            try {
                response = closeableHttpClient.execute(get);
                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();
                }
            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = updateLog(sendApp, receiveApp, receiveApi, oldbodys,bodys, oldheaderMap,headers, headers, oldquerys,querys, body.toString(), true,null,oldId);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("重推成功", jsonObject);
                    }else {
                        return BaseResult.getSuccessMessageEntity("重推失败", jsonObject);
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("重推成功", body);
                    }else {
                        return BaseResult.getSuccessMessageEntity("重推失败", body);
                    }
                }
            } else {
                return BaseResult.getSuccessMessageEntity("重推失败", body);
            }
        }
    }

    private SysApplicationApiAuthDetailEntity getApiAuthDetailByAppIdApiIdTripartiteSystemId(String appId, String apiId, String tripartiteSystemId) {
        String str = "appId" + appId + "apiId" + apiId + "tripartiteSystemId" + tripartiteSystemId;
        Object o = applicationCache.get("4", str);
        if (o != null) {
            return (SysApplicationApiAuthDetailEntity) o;
        }
        return null;
    }

    public static void deleteDirectory(String directoryPath) throws IOException {
        Path path = Paths.get(directoryPath);

        if (Files.exists(path) && Files.isDirectory(path)) {
            Files.walk(path)
                    .sorted((p1, p2) -> -1) // 从子目录到父目录排序，确保先删除子目录
                    .forEach(p -> {
                        try {
                            Files.delete(p);
                        } catch (IOException e) {
                            System.err.println("Error when deleting file: " + p.toString());
                            e.printStackTrace();
                        }
                    });
        }
    }

    private SysApplicationApiAuthEntity getApiAuthByNameAppId(String name, String appId) {
        String str = "name" + name + "appId" + appId;
        Object o = applicationCache.get("3", str);
        if (o != null) {
            return (SysApplicationApiAuthEntity) o;
        }
        return null;
    }

    private SysApplicationApiEntity getApiByAppIdApiCode(String appId, String apiCode) {

        String str = "appId" + appId + "apiCode" + apiCode;
        Object o = applicationCache.get("2", str);
        if (o != null) {
            return (SysApplicationApiEntity) o;
        }
        return null;
    }

    private SysApplicationEntity getAppByAppId(String appId) {
        String str = "appId" + appId;
        Object o = applicationCache.get("1", str);
        if (o != null) {
            return (SysApplicationEntity) o;
        }
        return null;
    }

    private SysApplicationEntity getAppByPublicKeySecretKey(String publicKey, String secretKey) {
        String str = "publicKey" + publicKey + "secretKey" + secretKey;
        Object o = applicationCache.get("1", str);
        if (o != null) {
            return (SysApplicationEntity) o;
        }
        return null;
    }

    /**
     * @param sendApp
     * @param receiveApp
     * @param receiveApi
     * @param bodys
     * @param headerMap
     * @param querys
     * @param body
     * @return void
     * @Author lvleigang
     * @Description 保存日志
     * @Date 11:36 上午 2023/10/20
     **/
    private SysMessageManageLogEntity saveLog(SysApplicationEntity sendApp, SysApplicationEntity receiveApp, SysApplicationApiEntity receiveApi,
                                              String oldbodys,String bodys,
                                              Map<String, String> oldheaderMap,Map<String, String> headerMap,
                                              Map<String, String> headers,
                                              String oldquerys, String querys,
                                              String body, boolean flag,String msg) {
        SysMessageManageLogEntity sysMessageManageLogEntity = new SysMessageManageLogEntity();
        //messageManageId 消息主表主键
        //theme  消息主题
        //messageCode  消息编码
        //sendApp
        sysMessageManageLogEntity.setSendApp(sendApp.getId());//发送者应用
        //sendApi  发送者
        sysMessageManageLogEntity.setReceiveCode(receiveApi.getApiCode() != null ? receiveApi.getApiCode().toString() : null);//接收者编码
        sysMessageManageLogEntity.setReceiveApp(receiveApp.getId());//接收者应用
        sysMessageManageLogEntity.setReceiveApi(receiveApi.getId());//接收者
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("body", oldbodys);
        jsonObject.put("header", oldheaderMap);
        jsonObject.put("querys", oldquerys);
        sysMessageManageLogEntity.setSourceData(jsonObject.toString());//源数据
        JSONObject send = new JSONObject();
        send.put("body", bodys);
        send.put("header", headers);
        send.put("querys", querys);
        sysMessageManageLogEntity.setTargetData(send.toString());//目标data
        if(receiveApp.getAppType() != null && "4".equals(receiveApp.getAppType())){//宁波银行
            JSONObject jsonObject1 = JSONObject.parseObject(body);
            String retCode = jsonObject1.getString("retCode");
            if(retCode != null && "0000".equals(retCode)){
                JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.getString("data"));
                String fileBytes = jsonObject2.getString("fileBytes");
                if(fileBytes != null && !"".equals(fileBytes)){
                    jsonObject2.put("fileBytes","");
                    jsonObject1.put("data",jsonObject2);
                    sysMessageManageLogEntity.setReturnData(jsonObject1.toJSONString());//返回信息
                }else {
                    sysMessageManageLogEntity.setReturnData(body);//返回信息
                }
            }else {
                sysMessageManageLogEntity.setReturnData(body);//返回信息
            }
        }else {
            sysMessageManageLogEntity.setReturnData(body);//返回信息
        }


        //校验返回
        if (!flag) {
            sysMessageManageLogEntity.setStatus("4");//返回信息
            sysMessageManageLogEntity.setRemark(msg);//返回信息
        } else {
            if (receiveApi.getReturnSuccessField() != null && !"".equals(receiveApi.getReturnSuccessField())
                    && receiveApi.getReturnSuccessValue() != null && !"".equals(receiveApi.getReturnSuccessValue())) {
                if (JSONUtil.isTypeJSON(body)) {
                    JSONObject cheackdatas = JSONObject.parseObject(body);
                    JSONObject datas = JSONObject.parseObject(body);
                    String checkdata = cheackdatas.getString(receiveApi.getReturnSuccessField());
                    if (checkdata != null && receiveApi.getReturnSuccessValue().equals(checkdata)) {
                        sysMessageManageLogEntity.setStatus("3");//返回信息
                        if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                            String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                            sysMessageManageLogEntity.setRemark("接口调用成功，返回信息如下：" + returnMsg);//返回信息
                        } else {
                            sysMessageManageLogEntity.setRemark("接口调用成功");//返回信息
                        }
                    }else if(receiveApi.getReturnSuccessValue().equals("not null") && checkdata != null){
                        sysMessageManageLogEntity.setStatus("3");//返回信息
                        if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                            String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                            sysMessageManageLogEntity.setRemark("接口调用成功，返回信息如下：" + returnMsg);//返回信息
                        } else {
                            sysMessageManageLogEntity.setRemark("接口调用成功");//返回信息
                        }
                    }else {
                        String fieldname = receiveApi.getReturnSuccessField();
                        if(fieldname.contains(".")){
                            String[] fileds = fieldname.split("\\.");
                            boolean flags = false;
                            for (int i = 0; i < fileds.length; i++) {
                                if (JSONUtil.isTypeJSON(datas.getString(fileds[i]))) {
                                    datas = datas.getJSONObject(fileds[i]);
                                    if(fileds.length-2 == i ){
                                        String a = datas.getString(fileds[i+1]);
                                        if (a != null && receiveApi.getReturnSuccessValue().equals(a)) {
                                            flags = true;
                                            break;
                                        }else if(receiveApi.getReturnSuccessValue().equals("not null") && a != null){
                                            flags = true;
                                            break;
                                        }else {
                                            break;
                                        }
                                    }
                                }
                            }
                            if(flags){
                                sysMessageManageLogEntity.setStatus("3");//返回信息
                                if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                                    String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                                    sysMessageManageLogEntity.setRemark("接口调用成功，返回信息如下：" + returnMsg);//返回信息
                                } else {
                                    sysMessageManageLogEntity.setRemark("接口调用成功");//返回信息
                                }
                            }else {
                                sysMessageManageLogEntity.setStatus("4");//返回信息
                                if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                                    String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                                    sysMessageManageLogEntity.setReturnMsg(returnMsg);//返回信息
                                    sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误，返回信息如下：" + returnMsg);//返回信息
                                } else {
                                    sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误");//返回信息
                                }
                            }

                        }else {
                            sysMessageManageLogEntity.setStatus("4");//返回信息
                            if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                                String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                                sysMessageManageLogEntity.setReturnMsg(returnMsg);//返回信息
                                sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误，返回信息如下：" + returnMsg);//返回信息
                            } else {
                                sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误");//返回信息
                            }
                        }
                    }
                } else {
                    sysMessageManageLogEntity.setStatus("4");//返回信息
                    sysMessageManageLogEntity.setRemark("接口调用失败,返回格式错误，不是JSON");//返回信息
                }
            } else {
                sysMessageManageLogEntity.setStatus("4");//返回信息
                if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                    if (JSONUtil.isTypeJSON(body)) {
                        JSONObject cheackdatas = JSONObject.parseObject(body);
                        String checkdata = cheackdatas.getString(receiveApi.getReturnMsg());
                        sysMessageManageLogEntity.setReturnMsg(checkdata);//返回信息
                        sysMessageManageLogEntity.setRemark("接口调用失败,api返回信息字段未配置，返回信息如下：" + checkdata);//返回信息
                    } else {
                        sysMessageManageLogEntity.setRemark("接口调用失败,返回格式错误，不是JSON");//返回信息
                    }
                } else {
                    sysMessageManageLogEntity.setRemark("接口调用失败");//返回信息
                }
            }
        }
        //remark  备注
        sysMessageManageLogEntity.setErrorStatus("2");//返回信息
        sysMessageManageLogEntity.setId(UUIDUtils.getUUID());
        sysMessageManageLogEntity.setCreate_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
        sysMessageManageLogEntity.setModify_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
        sysMessageManageLogEntity.setCreate_time(new Date());
        sysMessageManageLogEntity.setModify_time(new Date());
        sysMessageManageLogEntity.setSts("Y");
        taskExecutor.execute(() -> doEsbTask(sysMessageManageLogEntity));
        SysPushMessageEntity sysPushMessageEntity = new SysPushMessageEntity();
        sysPushMessageEntity.setSendAppName(sendApp.getName());
        sysPushMessageEntity.setReceiveAppName(receiveApp.getName());
        sysPushMessageEntity.setReceiveApiName(receiveApi.getApiName());
        sysPushMessageEntity.setReceiveApiCode(receiveApi.getApiCode());
        sysPushMessageEntity.setReturnData(sysMessageManageLogEntity.getReturnData());
        sysPushMessageEntity.setStatus(sysMessageManageLogEntity.getStatus());
        taskExecutor.execute(() -> sendMssage(sysPushMessageEntity));
        return sysMessageManageLogEntity;
    }

    private void sendMssage(SysPushMessageEntity sysPushMessageEntity) {
        sysSendMessageLogService.sendMessage(sysPushMessageEntity);
    }

    private SysMessageManageLogEntity updateLog(SysApplicationEntity sendApp, SysApplicationEntity receiveApp, SysApplicationApiEntity receiveApi,
                                              String oldbodys,String bodys,
                                              Map<String, String> oldheaderMap,Map<String, String> headerMap,
                                              Map<String, String> headers,
                                              String oldquerys, String querys,
                                              String body, boolean flag,String msg,String oldId) {
        SysMessageManageLogEntity sysMessageManageLogEntity = new SysMessageManageLogEntity();
        //messageManageId 消息主表主键
        //theme  消息主题
        //messageCode  消息编码
        //sendApp
        sysMessageManageLogEntity.setSendApp(sendApp.getId());//发送者应用
        //sendApi  发送者
        sysMessageManageLogEntity.setReceiveCode(receiveApi.getApiCode() != null ? receiveApi.getApiCode().toString() : null);//接收者编码
        sysMessageManageLogEntity.setReceiveApp(receiveApp.getId());//接收者应用
        sysMessageManageLogEntity.setReceiveApi(receiveApi.getId());//接收者
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("body", oldbodys);
        jsonObject.put("header", oldheaderMap);
        jsonObject.put("querys", oldquerys);
        sysMessageManageLogEntity.setSourceData(jsonObject.toString());//源数据
        JSONObject send = new JSONObject();
        send.put("body", bodys);
        send.put("header", headers);
        send.put("querys", querys);
        sysMessageManageLogEntity.setTargetData(send.toString());//目标data
        if(receiveApp.getAppType() != null && "4".equals(receiveApp.getAppType())){//宁波银行
            JSONObject jsonObject1 = JSONObject.parseObject(body);
            String retCode = jsonObject1.getString("retCode");
            if(retCode != null && "0000".equals(retCode)){
                JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.getString("data"));
                String fileBytes = jsonObject2.getString("fileBytes");
                if(fileBytes != null && !"".equals(fileBytes)){
                    jsonObject2.put("fileBytes","");
                    jsonObject1.put("data",jsonObject2);
                    sysMessageManageLogEntity.setReturnData(jsonObject1.toJSONString());//返回信息
                }else {
                    sysMessageManageLogEntity.setReturnData(body);//返回信息
                }
            }else {
                sysMessageManageLogEntity.setReturnData(body);//返回信息
            }
        }else {
            sysMessageManageLogEntity.setReturnData(body);//返回信息
        }


        //校验返回
        if (!flag) {
            sysMessageManageLogEntity.setStatus("4");//返回信息
            sysMessageManageLogEntity.setRemark(msg);//返回信息
        } else {
            if (receiveApi.getReturnSuccessField() != null && !"".equals(receiveApi.getReturnSuccessField())
                    && receiveApi.getReturnSuccessValue() != null && !"".equals(receiveApi.getReturnSuccessValue())) {
                if (JSONUtil.isTypeJSON(body)) {
                    JSONObject cheackdatas = JSONObject.parseObject(body);
                    JSONObject datas = JSONObject.parseObject(body);
                    String checkdata = cheackdatas.getString(receiveApi.getReturnSuccessField());
                    if (checkdata != null && receiveApi.getReturnSuccessValue().equals(checkdata)) {
                        sysMessageManageLogEntity.setStatus("3");//返回信息
                        if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                            String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                            sysMessageManageLogEntity.setRemark("接口调用成功，返回信息如下：" + returnMsg);//返回信息
                        } else {
                            sysMessageManageLogEntity.setRemark("接口调用成功");//返回信息
                        }
                    }else if(receiveApi.getReturnSuccessValue().equals("not null") && checkdata != null){
                        sysMessageManageLogEntity.setStatus("3");//返回信息
                        if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                            String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                            sysMessageManageLogEntity.setRemark("接口调用成功，返回信息如下：" + returnMsg);//返回信息
                        } else {
                            sysMessageManageLogEntity.setRemark("接口调用成功");//返回信息
                        }
                    }else {
                        String fieldname = receiveApi.getReturnSuccessField();
                        if(fieldname.contains(".")){
                            String[] fileds = fieldname.split("\\.");
                            boolean flags = false;
                            for (int i = 0; i < fileds.length; i++) {
                                if (JSONUtil.isTypeJSON(datas.getString(fileds[i]))) {
                                    datas = datas.getJSONObject(fileds[i]);
                                    if(fileds.length-2 == i ){
                                        String a = datas.getString(fileds[i+1]);
                                        if (a != null && receiveApi.getReturnSuccessValue().equals(a)) {
                                            flags = true;
                                            break;
                                        }else if(receiveApi.getReturnSuccessValue().equals("not null") && a != null){
                                            flags = true;
                                            break;
                                        }else {
                                            break;
                                        }
                                    }
                                }
                            }
                            if(flags){
                                sysMessageManageLogEntity.setStatus("3");//返回信息
                                if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                                    String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                                    sysMessageManageLogEntity.setRemark("接口调用成功，返回信息如下：" + returnMsg);//返回信息
                                } else {
                                    sysMessageManageLogEntity.setRemark("接口调用成功");//返回信息
                                }
                            }else {
                                sysMessageManageLogEntity.setStatus("4");//返回信息
                                if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                                    String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                                    sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误，返回信息如下：" + returnMsg);//返回信息
                                } else {
                                    sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误");//返回信息
                                }
                            }

                        }else {
                            sysMessageManageLogEntity.setStatus("4");//返回信息
                            if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                                String returnMsg = cheackdatas.getString(receiveApi.getReturnMsg());
                                sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误，返回信息如下：" + returnMsg);//返回信息
                            } else {
                                sysMessageManageLogEntity.setRemark("接口调用失败,返回值错误");//返回信息
                            }
                        }
                    }
                } else {
                    sysMessageManageLogEntity.setStatus("4");//返回信息
                    sysMessageManageLogEntity.setRemark("接口调用失败,返回格式错误，不是JSON");//返回信息
                }
            } else {
                sysMessageManageLogEntity.setStatus("4");//返回信息
                if (receiveApi.getReturnMsg() != null && !"".equals(receiveApi.getReturnMsg())) {
                    if (JSONUtil.isTypeJSON(body)) {
                        JSONObject cheackdatas = JSONObject.parseObject(body);
                        String checkdata = cheackdatas.getString(receiveApi.getReturnMsg());
                        sysMessageManageLogEntity.setRemark("接口调用失败,api返回信息字段未配置，返回信息如下：" + checkdata);//返回信息
                    } else {
                        sysMessageManageLogEntity.setRemark("接口调用失败,返回格式错误，不是JSON");//返回信息
                    }
                } else {
                    sysMessageManageLogEntity.setRemark("接口调用失败");//返回信息
                }
            }
        }
        //remark  备注
        sysMessageManageLogEntity.setErrorStatus("2");//返回信息
        sysMessageManageLogEntity.setId(oldId);
        sysMessageManageLogEntity.setCreate_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
        sysMessageManageLogEntity.setModify_user_id("c796fd9ba4c9f5ff3cc2fa41a040e443");
        //sysMessageManageLogEntity.setCreate_time(new Date());
        sysMessageManageLogEntity.setModify_time(new Date());
        sysMessageManageLogEntity.setSts("Y");
        taskExecutor.execute(() -> doEsbTaskNew(sysMessageManageLogEntity));



        return sysMessageManageLogEntity;
    }

    /**
     * @param manageLogEntities
     * @return void
     * @Author lvleigang
     * @Description 保存日子
     * @Date 11:43 上午 2023/8/30
     **/
    private void doEsbTask(SysMessageManageLogEntity manageLogEntities) {
        sysMessageManageLogDao.save(manageLogEntities);

    }
    private void doEsbTaskNew(SysMessageManageLogEntity manageLogEntities) {
        sysMessageManageLogDao.update(manageLogEntities);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用列表查询接口 多字段模糊查询，枚举类型字段转换
     * @Date 2:06 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity thirdInterfacequeryApp(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<SysApplicationVo> sysApplicationVos = sysApplicationDao.queryApp(entity);
        PageInfo pageInfo = new PageInfo(sysApplicationVos);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 应用列表查询接口 多字段模糊查询，枚举类型字段转换
     * @Date 2:06 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity thirdInterfacequeryAppAll(JSONObject object) {
        SysApplicationDto entity = getData("jsonStr", object, SysApplicationDto.class);
        List<SysApplicationVo> sysApplicationVos = sysApplicationDao.queryApp(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", sysApplicationVos);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 查询接口日志 查询接口发送错误，以及不发送的数据
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity thirdInterfacequeryAppApiLog(JSONObject object) {
        SysMessageManageLogEntity entity = getData("jsonStr", object, SysMessageManageLogEntity.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        //日期转换
        if (entity.getCreateTimeStart() != null) {
            DateTime beginOfDay = DateUtil.beginOfDay(entity.getCreateTimeStart());
            entity.setCreateTimeStart(beginOfDay);
        }
        //日期转换
        if (entity.getCreateTimeEnd() != null) {
            DateTime endOfDay = DateUtil.endOfDay(entity.getCreateTimeEnd());
            entity.setCreateTimeEnd(endOfDay);
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<String> ids = sysMessageManageLogDao.querySysMessageManageLogIds(entity);
        PageInfo pageInfo = new PageInfo(ids);
        List<SysMessageManageLogPageVo> sysMessageManageLogEntities = new ArrayList<>();
        if (ids != null && ids.size() > 0) {
            entity.setIds(ids);
            sysMessageManageLogEntities = sysMessageManageLogDao.queryListByErrorPageVo(entity);
        }
        pageInfo.setList(sysMessageManageLogEntities);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 查询接口
     * @Date 2:08 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity thirdInterfacequeryAppApi(JSONObject object) {
        SysApplicationApiEntity entity = getData("jsonStr", object, SysApplicationApiEntity.class);
        List<SysApplicationApiEntity> ids = sysApplicationApiDao.queryBaseName(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", ids);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询应用列表
     * @Date 11:52 上午 2024/3/27
     **/
    @Override
    public JsonResultEntity queryEntity(JSONObject jsonObject) {
        SysApplicationEntity entity = getData("jsonStr", jsonObject, SysApplicationEntity.class);
        if (entity == null) {
            entity = new SysApplicationEntity();
        }
        List<SysApplicationEntity> list = sysApplicationDao.queryByLike(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", list);
    }

    /**
     * @param jsonObject
     * @return com.hzya.frame.web.entity.JsonResultEntity
     * @Author lvleigang
     * @Description 查询应用插件列表和api
     * @Date 11:52 上午 2024/3/27
     **/
    @Override
    public JsonResultEntity queryPlugAndApi(JSONObject jsonObject) {
        SysApplicationPluginEntity entity = getData("jsonStr", jsonObject, SysApplicationPluginEntity.class);
        if (entity == null || entity.getAppId() == null || "".equals(entity.getAppId()) || entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        SysApplicationPluginEntity sysApplicationPluginEntity = new SysApplicationPluginEntity();
        sysApplicationPluginEntity.setAppId(entity.getAppId());
        List<SysApplicationPluginEntity> sysApplicationPluginEntities = sysApplicationPluginDao.queryBase(sysApplicationPluginEntity);

        SysApplicationApiEntity sysApplicationApiEntity = sysApplicationApiDao.get(entity.getId());
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("app",sysApplicationPluginEntities);
        jsonObject1.put("api",sysApplicationApiEntity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", jsonObject1);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 脚本查询分页接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppScriptPage(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        //判断分页
        if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) {
            return BaseResult.getFailureMessageEntity("分页查询参数不存在");
        }
        PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
        List<SysApplicationScriptEntity> sysApplicationScriptEntities = sysApplicationScriptDao.queryByLike(entity);
        PageInfo pageInfo = new PageInfo(sysApplicationScriptEntities);
        return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 脚本查询接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity queryAppScript(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        List<SysApplicationScriptEntity> sysApplicationScriptEntities = sysApplicationScriptDao.queryByLike(entity);
        return BaseResult.getSuccessMessageEntity("查询数据成功", sysApplicationScriptEntities);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 脚本修改接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity saveAppScript(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getScriptCode() == null || "".equals(entity.getScriptCode())) {
            return BaseResult.getFailureMessageEntity("请先输入脚本编号");
        }
        if (entity.getScriptData() == null || "".equals(entity.getScriptData())) {
            return BaseResult.getFailureMessageEntity("请先输入脚本内容");
        }
        entity.setCreate();
        sysApplicationScriptDao.save(entity);
        return BaseResult.getSuccessMessageEntity("保存脚本成功", entity.getId());
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 脚本修改接口
     * @Date 2:09 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity updateAppScript(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getScriptCode() == null || "".equals(entity.getScriptCode())) {
            return BaseResult.getFailureMessageEntity("请先输入脚本编号");
        }
        if (entity.getScriptData() == null || "".equals(entity.getScriptData())) {
            return BaseResult.getFailureMessageEntity("请先输入脚本内容");
        }
        entity.setUpdate();
        sysApplicationScriptDao.update(entity);
        return BaseResult.getSuccessMessageEntity("修改脚本成功");
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 脚本删除接口
     * @Date 2:10 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity deleteAppScript(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        MdmModuleDistributeEntity mdmModuleDistributeEntity = new MdmModuleDistributeEntity();
        mdmModuleDistributeEntity.setAddScript(entity.getId());
        mdmModuleDistributeEntity.setUpdateScript(entity.getId());
        mdmModuleDistributeEntity.setDeleteScript(entity.getId());
        Integer a = mdmModuleDistributeDao.queryCountUse(mdmModuleDistributeEntity);
        if(a > 0){
            return BaseResult.getFailureMessageEntity("脚本已经被使用，请先取消关联");
        }
        entity.setUpdate();
        sysApplicationScriptDao.logicRemoveMultiCondition(entity);
        return BaseResult.getSuccessMessageEntity("删除脚本成功");
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 获取脚本接口
     * @Date 2:10 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity getAppScript(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        //查询接口
        SysApplicationScriptEntity sysApplicationScriptEntity = sysApplicationScriptDao.get(entity.getId());
        return BaseResult.getSuccessMessageEntity("查询数据成功", sysApplicationScriptEntity);
    }

    /**
     * @param object
     * @return
     * @Author lvleigang
     * @Description 脚本启用停用接口
     * @Date 2:10 下午 2023/9/23
     **/
    @Override
    public JsonResultEntity enableOrDisableAppScript(JSONObject object) {
        SysApplicationScriptEntity entity = getData("jsonStr", object, SysApplicationScriptEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("参数不允许为空");
        }
        if (entity.getId() == null || "".equals(entity.getId())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        if (entity.getScriptStatus() == null || "".equals(entity.getScriptStatus())) {
            return BaseResult.getFailureMessageEntity("系统错误");
        }
        entity.setUpdate();
        sysApplicationScriptDao.update(entity);
        if ("1".equals(entity.getScriptStatus())) {// 1启用2停用
            return BaseResult.getSuccessMessageEntity("启用成功");
        } else {
            return BaseResult.getSuccessMessageEntity("停用成功");
        }
    }

    @Override
    public JsonResultEntity externalCallInterfaceToESB(ServletRequest servletRequest, ServletResponse servletResponse) {

        //例如：A应用发送数据到中台，中台转发到B应用
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String oldbodys = ServletUtil.getBody(servletRequest);
        Map<String, String> oldheaderMap = ServletUtil.getHeaderMap(request);
        String oldquerys = request.getQueryString();
        //应用key
        String publicKey = request.getHeader("publicKey");
        //应用密钥
        String secretKey = request.getHeader("secretKey");
        //appId
        String appId = request.getHeader("appId");
        //apiCode
        String apiCode = request.getHeader("apiCode");

        String ip = IPHelper.getIpAddr(request);
        if (publicKey == null || "".equals(publicKey)) {
            return BaseResult.getFailureMessageEntity("请先传递公钥");
        }
        if (secretKey == null || "".equals(secretKey)) {
            return BaseResult.getFailureMessageEntity("请先传递密钥");
        }
        if (appId == null || "".equals(appId)) {
            return BaseResult.getFailureMessageEntity("请先传递接收方应用");
        }
        if (apiCode == null || "".equals(apiCode)) {
            return BaseResult.getFailureMessageEntity("请先传递发送接口");
        }

        logger.info("请求参数：publicKey：【" + publicKey + "】secretKey：【" + secretKey + "】appId：【" + appId + "】apiCode：【" + apiCode);
        //根据请求a应用的公钥、密钥是否能查找到一条数据

        SysApplicationEntity sendApp = getAppByPublicKeySecretKey(publicKey, secretKey);
        if (sendApp == null) {
            //saveLog(new SysApplicationEntity(), new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"公钥、密钥错误");
            return BaseResult.getFailureMessageEntity("公钥、密钥错误,请联系管理员");
        }
        //判断应用是否启用
        if (sendApp.getAppStatus() == null || !"1".equals(sendApp.getAppStatus())) {
            saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,sendApp.getName() + "应用未启用");
            return BaseResult.getFailureMessageEntity(sendApp.getName() + "应用未启用,请联系管理员");
        }


        SysApplicationEntity receiveApp = getAppByAppId(appId);
        if (receiveApp == null) {
            saveLog(sendApp, new SysApplicationEntity(), new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,"根据appId:" + appId + "未匹配到应用");
            return BaseResult.getFailureMessageEntity("根据appId:" + appId + "未匹配到应用,请联系管理员");
        }
        //判断应用是否启用
        if (receiveApp.getAppStatus() == null || !"1".equals(receiveApp.getAppStatus())) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用未启用" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用未启用,请联系管理员");
        }
        //判断应用接口是否启用
        if (receiveApp.getInterfaceStatus() == null || !"1".equals(receiveApp.getInterfaceStatus())) {
            saveLog(sendApp, receiveApp, new SysApplicationApiEntity(), oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用接口环境未启用" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用接口环境未启用,请联系管理员");
        }

        SysApplicationApiEntity receiveApi = getApiByAppIdApiCode(receiveApp.getId(), apiCode);
        if (receiveApi == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + ":" + apiCode + "未启用或者未创建" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + ":" + apiCode + "未启用或者未创建");
        }

        SysApplicationApiAuthEntity sysApplicationApiAuthEntity = getApiAuthByNameAppId(sendApp.getId(), receiveApp.getId());
        if (sysApplicationApiAuthEntity == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "应用权限配置错误" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "应用权限配置错误");
        }
        if (sysApplicationApiAuthEntity.getSystemAddress() != null && !"".equals(sysApplicationApiAuthEntity.getSystemAddress())
                && !sysApplicationApiAuthEntity.getSystemAddress().contains(ip)) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误" );
            return BaseResult.getFailureMessageEntity(receiveApp.getName() + "发送应用" + receiveApp.getName() + "的ip白名单配置错误");
        }

        SysApplicationApiAuthDetailEntity sysApplicationApiAuthDetailEntity = getApiAuthDetailByAppIdApiIdTripartiteSystemId(receiveApp.getId(), receiveApi.getId(), sysApplicationApiAuthEntity.getId());
        if (sysApplicationApiAuthDetailEntity == null) {
            saveLog(sendApp, receiveApp, receiveApi, oldbodys, null, oldheaderMap, null, null, oldquerys, null, null, false,receiveApi.getApiName() + "未授权给" + sendApp.getName() );
            return BaseResult.getFailureMessageEntity(receiveApi.getApiName() + "未授权给" + sendApp.getName() + "，请联系管理员");
        }
        SysExtensionApiEntity sysExtensionApiEntity = new SysExtensionApiEntity();


        List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        Map<String, String> headers = new HashMap<>();
        if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
            JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    headers.put(object1.getString("parameterName"), object1.getString("example"));
                }
            }
        }
        if (oldheaderMap != null && oldheaderMap.size() > 0) {
            for (Map.Entry<String, String> entry : oldheaderMap.entrySet()) {
                if (!a.contains(entry.getKey())) {
                    headers.put(entry.getKey(), entry.getValue());
                }
            }
        }



        sysExtensionApiEntity.setSendApp(sendApp);
        sysExtensionApiEntity.setReceiveApp(receiveApp);
        sysExtensionApiEntity.setReceiveApi(receiveApi);
        sysExtensionApiEntity.setHeaders(headers);
        sysExtensionApiEntity.setQuerys(oldquerys);
        sysExtensionApiEntity.setBodys(oldbodys);
        Method[] methods = null;
        Object object = null;




        // 判断是否有内部api 是否扩展api 1、启用 2、停用
        if (receiveApi.getExtensionApi() != null && "1".equals(receiveApi.getExtensionApi())
                && receiveApi.getBeanName() != null && !"".equals(receiveApi.getBeanName())
                && receiveApi.getFunName() != null && !"".equals(receiveApi.getFunName())
        ) {
            //获取类
            try {
                object = ApplicationContextUtil.getBeanByName(receiveApi.getBeanName());
            } catch (SecurityException e) {

            }
            //获取类下面的方法
            methods = object.getClass().getMethods();
            if (methods == null || methods.length == 0) {
                return BaseResult.getFailureMessageEntity("未找到内部方法，请联系管理员");
            }
            for (Method m : methods) {
                if (null != m) {
                    if (m.getName().equals(receiveApi.getFunName().trim())) {
                        try {
                            logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            sysExtensionApiEntity = (SysExtensionApiEntity) m.invoke(object, sysExtensionApiEntity);
                            logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                        } catch (Exception e) {
                            logger.error("invokeException{}", e.getMessage());
                            return BaseResult.getFailureMessageEntity("内部方法执行错误，请联系管理员");
                        }
                    }
                }
            }

        }
        headers = sysExtensionApiEntity.getHeaders();
        String querys = sysExtensionApiEntity.getQuerys();

        byte[] byteBodys = sysExtensionApiEntity.getByteBodys();
        //设置参数获取参数
        StringBuffer url = new StringBuffer();
        if(!receiveApi.getDestinationAddress().toLowerCase().startsWith("http")){
            url.append(receiveApp.getInterfaceAddress());
        }
        url.append(receiveApi.getDestinationAddress());
        if (querys != null) {
            url.append("?");
            url.append(querys);
        }
        Integer outTime = 6000;
        if (receiveApi.getTimeoutPeriod() != null && !"".equals(receiveApi.getTimeoutPeriod())) {
            outTime = Integer.valueOf(receiveApi.getTimeoutPeriod());
        }
        //1、POST 2、GET
        String method = "POST";
        if ("2".equals(receiveApi.getRequestMethod())) {
            method = "GET";
        }
        //List<String> a = Arrays.asList(new String[]{"apicode", "appid", "secretkey", "publickey", "x-forwarded-for", "cookie", "x-forwarded-proto", "x-real-ip", "content-length", "accept-language", "host", "content-type", "connection", "cache-control", "accept-encoding", "pragma", "accept", "user-agent"});
        //Map<String, String> headers = new HashMap<>();
        //if (receiveApi.getHeaderIn() != null && !"".equals(receiveApi.getHeaderIn())) {
        //    JSONArray jsonArray = JSONArray.parseArray(receiveApi.getHeaderIn());
        //    if (jsonArray != null && jsonArray.size() > 0) {
        //        for (int i = 0; i < jsonArray.size(); i++) {
        //            JSONObject object1 = jsonArray.getJSONObject(i);
        //            headers.put(object1.getString("parameterName"), object1.getString("example"));
        //        }
        //    }
        //}
        //if (headerMap != null && headerMap.size() > 0) {
        //    for (Map.Entry<String, String> entry : headerMap.entrySet()) {
        //        if (!a.contains(entry.getKey())) {
        //            headers.put(entry.getKey(), entry.getValue());
        //        }
        //    }
        //}


        if ("POST".equals(method)) {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpPost post = new HttpPost(url.toString());
            CloseableHttpResponse response = null;

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

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

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

            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,Base64.getEncoder().encodeToString(byteBodys) , oldheaderMap,headers, headers, oldquerys,querys, body.toString(),true,null);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
                    }else {
                        return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", body);
                    }else {
                        return BaseResult.getFailureMessageEntity("转发失败", body);
                    }
                }
            } else {
                return BaseResult.getFailureMessageEntity("转发失败", body);
            }

        } else {//GET

            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            // HttpClient
            CloseableHttpClient closeableHttpClient = httpClientBuilder.disableCookieManagement().build();
            HttpGet get = new HttpGet(url.toString());
            CloseableHttpResponse response = null;

            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(outTime).build();
            get.setConfig(requestConfig);//设置请求参数【超时时间】
            if (headers != null && headers.size() > 0) {
                for (String key : headers.keySet()) {
                    get.setHeader(key, headers.get(key));
                }
            }
            StringBuilder body = new StringBuilder();

            boolean flag = true;
            try {
                response = closeableHttpClient.execute(get);
                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();
                }
            }
            logger.info("保存日志开始");
            SysMessageManageLogEntity sysMessageManageLogEntity = saveLog(sendApp, receiveApp, receiveApi, oldbodys,Base64.getEncoder().encodeToString(byteBodys) , oldheaderMap,headers, headers, oldquerys,querys, body.toString(), true,null);
            if (methods != null && methods.length > 0) {
                for (Method m : methods) {
                    if (null != m) {
                        if (m.getName().equals(receiveApi.getFunName().trim()+"CallBack")) {
                            try {
                                logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                m.invoke(object, sysMessageManageLogEntity);
                                logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                            } catch (Exception e) {
                                logger.error("invokeException{}", e.getMessage());
                            }
                        }
                    }
                }
            }
            logger.info("保存日志结束");
            if (flag) {
                if (JSONUtil.isTypeJSON(body.toString())) {
                    JSONObject jsonObject = JSONObject.parseObject(body.toString());
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", jsonObject);
                    }else {
                        return BaseResult.getFailureMessageEntity("转发失败", jsonObject);
                    }
                } else {
                    if(sysMessageManageLogEntity.getStatus() != null && "3".equals(sysMessageManageLogEntity.getStatus())){
                        return BaseResult.getSuccessMessageEntity("转发成功", body);
                    }else {
                        return BaseResult.getFailureMessageEntity("转发失败", body);
                    }
                }
            } else {
                return BaseResult.getFailureMessageEntity("转发失败", body);
            }
        }
    }

    @Override
    public SysExtensionApiEntity setDDtoken(SysExtensionApiEntity sysExtensionApiEntity) {
        SysApplicationApiEntity sysApplicationApiEntity = sysExtensionApiEntity.getReceiveApi();
        StringBuilder stringBuilder = new StringBuilder();

        if (sysApplicationApiEntity.getQueryIn() != null && !"".equals(sysApplicationApiEntity.getQueryIn())) {
            JSONArray jsonArray = JSONArray.parseArray(sysApplicationApiEntity.getQueryIn());
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object1 = jsonArray.getJSONObject(i);
                    if(i > 0){
                        stringBuilder.append("&");
                    }
                    stringBuilder.append(object1.getString("parameterName")).append("=").append(object1.getString("example"));
                }
            }
        }
        sysExtensionApiEntity.setQuerys(stringBuilder.toString());
        return sysExtensionApiEntity;
    }

    @Override
    public SysExtensionApiEntity setDDUserId(SysExtensionApiEntity sysExtensionApiEntity) {
        String bodys = sysExtensionApiEntity.getBodys();
        StringBuilder stringBuilder = new StringBuilder();
        JSONObject jsonObject = JSONObject.parseObject(bodys);
        stringBuilder.append("userid=").append(jsonObject.getString("userid"));
        stringBuilder.append("&");
        stringBuilder.append("access_token=").append(jsonObject.getString("access_token"));
        sysExtensionApiEntity.setQuerys(stringBuilder.toString());
        return sysExtensionApiEntity;
    }


}
