package com.hzya.frame.seeyon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.seeyon.dao.ISeeYonInterFaceDao;
import com.hzya.frame.seeyon.entity.OAWorkflowEventDataEntity;
import com.hzya.frame.seeyon.entity.SeeYonInterFaceEntity;
import com.hzya.frame.seeyon.service.ISeeYonInterFace;
import com.hzya.frame.sys.sysenum.SysEnum;
import com.hzya.frame.sysnew.application.api.entity.SysApplicationApiEntity;
import com.hzya.frame.sysnew.application.api.service.ISysApplicationApiService;
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.SysApplicationEntity;
import com.hzya.frame.sysnew.application.entity.SysExtensionApiEntity;
import com.hzya.frame.sysnew.application.service.impl.ApplicationCache;
import com.hzya.frame.util.PluginUtils;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 👻👻👻👻👻👻👻👻👻👻 gjh
 * @version 1.0
 * @content
 * @date 2023-08-22 9:30
 */
@Service(value = "seeYonInterFace")
public class SeeYonInterFaceImpl implements ISeeYonInterFace {
    private static final Logger logger = LoggerFactory.getLogger(SeeYonInterFaceImpl.class);
    /*** rest 用户名*/
    private static final String RESTUSERNAME = "hzyaRest";
    /*** rest 密码*/
    private static final String RESTPASSWORD = "a5ce21b8-91db-4cec-b3e3-3e44719655fd";
    // TODO 此处URL暂时写死，后续根据传递的应用ID获取
    private static final String sendUrl = "http://60.204.152.210/seeyon/";
    //速网esb地址
    private static final String baseUrl = "http://hzya.ufyct.com:9067/kangarooDataCenter/entranceController/externalCallInterface";
    /**
     * 定义所支持的事件静态代码块
     */
    private static final StringBuffer eventTypeBuffer = new StringBuffer();
    //基础档案类型
    private final String ARCHIVESTYPE = "archives";
    //流程表单类型
    private final String FLOWTYPE = "flow";
    //创建基础档案
    private final String CREATEARCHIVES = "create";
    //更新基础档案
    private final String UPDATEARCHIVES = "update";
    //创建基础档案
    private final String CREATEARCHIVESURL = "rest/form/import/";
    //创建基础档案
    private final String UPDATEARCHIVESURL = "rest/form/update";
    @Resource
    private ISysApplicationDatabaseDao sysApplicationDatabaseDao;
    @Autowired
    private ISysApplicationApiService sysApplicationApiService;
    @Resource
    private ISeeYonInterFaceDao seeYonInterFaceDao;
    //上一次同步时间
    private final String LAST_SYNCHRONISED_TIME = "";
    @Value("${zt.url}")
    private String url ;
    @Resource
    private ApplicationCache applicationCache;

    {
        eventTypeBuffer.append("发起前事件 onBeforeStart ,");
        eventTypeBuffer.append("发起事件 onStart ,");
        eventTypeBuffer.append("终止前事件 onBeforeStop ,");
        eventTypeBuffer.append("终止事件 onStop,");
        eventTypeBuffer.append("撤销前事件 onBeforeCancel,");
        eventTypeBuffer.append("撤销事件 onCancel,");
        eventTypeBuffer.append("结束事件 onProcessFinished,");
        eventTypeBuffer.append("处理前事件 onBeforeFinishWorkitem,");
        eventTypeBuffer.append("处理事件 onFinishWorkitem,");
        eventTypeBuffer.append("回退前事件 onBeforeStepBack,");
        eventTypeBuffer.append("回退事件 onStepBack,");
        eventTypeBuffer.append("取回前事件 onBeforeTakeBack,");
        eventTypeBuffer.append("取回事件 onTakeBack,");
    }

    /****
     * @Content:发起无流程表单接口实现
     * @Author 👻👻👻👻👻👻👻👻 gjh
     * @Date 2019/12/23 17:03
     * @Param [templateCode 模版编码, sendLoginName 发送人登录帐号 ,xmlData  ]
     * @return java.lang.Integer
     **/
    public static JsonResultEntity saveNoProcess(String templateCode, String interfaceUrl, String sendLoginName, String xmlData) {
        String token = getToken(RESTUSERNAME, RESTPASSWORD, sendLoginName);
        Map res = new HashMap();
        res.put("loginName", sendLoginName);
        res.put("dataXml", xmlData);
        res.put("token", token);
        String result = HttpRequest.post(sendUrl + interfaceUrl + templateCode).header("token", token).body(JSON.toJSONString(res)).execute().body();
        logger.info("无流程表单执行结果：" + result);
        return BaseResult.getFailureMessageEntity("执行成功", result);
    }

    public static JsonResultEntity upDateNoProcess(String interfaceUrl, String templateCode, String sendLoginName, String moduleId, String xmlData) {
        String token = getToken(RESTUSERNAME, RESTPASSWORD, sendLoginName);
        Map res = new HashMap();
        res.put("loginName", sendLoginName);
        res.put("dataXml", xmlData);
        res.put("token", token);
        res.put("moduleId", moduleId);
        res.put("templateCode", templateCode);
        logger.info("更新无流程表单参数:{}", JSON.toJSONString(res));
        String result = HttpRequest.put(sendUrl + interfaceUrl).header("token", token).body(JSON.toJSONString(res)).execute().body();
        logger.info("更新无流程表单执行结果：" + result);
        return BaseResult.getFailureMessageEntity("执行成功", result);
    }

    //    {
//        "moduleId":"5701605966502512923",
//            "templateCode":"formmain_0360",
//            "loginName":"seeyon",
//            "dataXml":"<forms  version=\"2.1\"><formExport><summary  id=\"7382733425750590212\" name=\"formmain_0360\"/><definitions><column  id=\"field0001\" type=\"0\" name=\"供应商编码\" isNullable=\"false\" length=\"100\"/><column  id=\"field0002\" type=\"0\" name=\"供应商名称\" isNullable=\"false\" length=\"100\"/><column  id=\"field0007\" type=\"0\" name=\"税号\" isNullable=\"false\" length=\"100\"/><column  id=\"field0008\" type=\"0\" name=\"地址\" isNullable=\"false\" length=\"100\"/><column  id=\"field0009\" type=\"0\" name=\"电话\" isNullable=\"false\" length=\"100\"/><column  id=\"field0011\" type=\"0\" name=\"联系人\" isNullable=\"false\" length=\"100\"/></definitions><values><column  name=\"供应商编码\"><value><![CDATA[ 12345 ]]></value></column><column  name=\"供应商名称\"><value><![CDATA[ 测试客户银行1111 ]]></value></column><column  name=\"税号\"><value><![CDATA[ 982698741E96 ]]></value></column><column  name=\"地址\"><value><![CDATA[ 杭州 ]]></value></column><column  name=\"电话\"><value><![CDATA[ null ]]></value></column><column  name=\"联系人\"><value><![CDATA[ null ]]></value></column></values><subForms><subForm><definitions><column  id=\"field0003\" type=\"4\" name=\"序号\" isNullable=\"false\" length=\"20\"/><column  id=\"field0005\" type=\"0\" name=\"开户行名称\" isNullable=\"false\" length=\"100\"/><column  id=\"field0006\" type=\"0\" name=\"银行账号\" isNullable=\"false\" length=\"100\"/><column  id=\"field0004\" type=\"0\" name=\"是否默认\" isNullable=\"false\" length=\"100\"/></definitions><values><row><column  name=\"序号\"><value><![CDATA[1]]></value><title><![CDATA[1438373948291346275]]></title></column><column  name=\"开户行名称\"><value><![CDATA[1234]]></value><title><![CDATA[9218745623489128746]]></title></column><column  name=\"银行账号\"><value><![CDATA[111111111]]></value><title><![CDATA[6897123456789123456]]></title></column><column  name=\"是否默认\"><value><![CDATA[是]]></value><title><![CDATA[5729461284567891234]]></title></column></row></values></subForm></subForms></formExport></forms>"
//    }
    private static String getToken(String userName, String password, String loginName) {
        JSONObject jsonObject = new JSONObject();
        /** 获取token*/

        jsonObject.put("userName", userName);
        jsonObject.put("password", password);
        jsonObject.put("loginName", loginName);
        logger.info("请求获取token开始---------------------------------------------");
        logger.info("请求参数" + jsonObject.toJSONString());
        String result = HttpUtil.post(sendUrl + "rest/token", jsonObject.toJSONString());
        logger.info("获取token结果---------------------------------------------" + result);
        logger.info("获取token结果---------------------------------------------" + result);
        jsonObject = JSONObject.parseObject(result);
        if ("".equals(result) || result == null) {
            logger.info("获取token失败！");
            throw new RuntimeException("获取token失败！");
        } else {
            String token = jsonObject.get("id").toString();
            return token;
        }
    }

    /***
     * 发起OA表单方法
     * @content:
     * @author 👻👻👻👻👻👻👻👻 gjh
     * @date 2023-08-22 9:32
     * @param
     * @return com.hzya.frame.web.entity.BaseResult
     **/
    @Override
    public JsonResultEntity thirdInterfaceSend(JSONObject requestData) {
        JSONObject jsonStr = requestData.getJSONObject("jsonStr");
        if (ObjectUtils.isEmpty(jsonStr)) {
            throw new BaseSystemException("jsonStr为空！请传递参数");
        }
        //类型 flow archives
        String type = jsonStr.getString("type");
        if (StringUtils.isEmpty(type)) {
            throw new BaseSystemException("请传递类型！type 流程表单：flow 基础档案：archives");
        }
        //模版编号
        String templateCode = jsonStr.getString("templateCode");
        if (StringUtils.isEmpty(templateCode)) {
            throw new BaseSystemException("请传入模版编号！templateCode不允许为空");
        }
        JSONObject data = jsonStr.getJSONObject("data");
        String attributeArrayStr = jsonStr.getString("attribute");
        if (StringUtils.isEmpty(attributeArrayStr)) {
            throw new BaseSystemException("attribute不允许为空");
        }
        List<JSONObject> attributeArray = JSON.parseArray(attributeArrayStr, JSONObject.class);
        JsonResultEntity result = null;
        if (ARCHIVESTYPE.equalsIgnoreCase(type)) {
            switch (templateCode) {
                //预留的
                case "abc123":
                    break;
            }
        }
        if (FLOWTYPE.equalsIgnoreCase(type)) {
        }
        return result;
    }


    @Override
    public JsonResultEntity thirdInterfaceSeeYonPlugInInterfaceEntrance(JSONObject requestData) {
        String jsonStr = requestData.getString("jsonStr");
        JSONObject jsonObject = requestData.getJSONObject("jsonStr");
        OAWorkflowEventDataEntity entity = JSON.parseObject(jsonStr, OAWorkflowEventDataEntity.class);
        logger.info("监听OA事件入参：" + jsonObject.toJSONString());
        JSONObject formBeanData = jsonObject.getJSONObject("businessDataStr");
        String eventType = jsonObject.getString("eventType");
        /** 流程ID*/
        String summaryId = entity.getSummaryId();
        /** 节点ID*/
        String affairId = entity.getAffairId();
        String currentActivityId = entity.getCurrentActivityId();
        /****/
        String formViewOperation = entity.getFormViewOperation();
        Object summaryObj = entity.getSummaryObj();
        String deeCfgId = entity.getDeeCfgId();
        String currentNodeLast = entity.getCurrentNodeLast();
        Map<String, Object> businessData = JSON.parseObject(entity.getBusinessDataStr(), Map.class);
        Map<String, Object> extData = entity.getExtData();
        /** 表单表的FORM ID,用此字段标记是哪个流程*/
        String formApp = entity.getFormApp();

        //formApp 最好过滤一下


        JsonResultEntity result = null;
        try {
            //流程事件处理
            result = colEventPost(jsonStr, formApp, eventType);
        } catch (Exception e) {
            return BaseResult.getFailureMessageEntity("传递失败", e.getMessage());
        }
        return result;
//        try {
//            /** 根据事件类型处理相关事件*/
//            switch (eventType) {
//                /** 发起前事件*/
//                case "onBeforeStart":
//                    break;
//                /** 发起事件*/
//                case "onStart":
//                    //流程发起 新增grpu8单据
//                    break;
//                /** 终止前事件*/
//                case "onBeforeStop":
//                    break;
//                /** 终止事件*/
//                case "onStop":
//                    //流程终止，更新grpu8单据
//                    break;
//                /** 撤销前事件*/
//                case "onBeforeCancel":
//                    break;
//                /** 撤销事件*/
//                case "onCancel":
//                    //流程撤销，更新grpu8单据
//                    break;
//                /** 结束事件*/
//                case "onProcessFinished":
//                    break;
//                /** 处理前事件*/
//                case "onBeforeFinishWorkitem":
//                    /** 根据form处理相关业务表单的数据*/
//                    switch (formApp) {
//                        case "abc123":
//                            break;
//                        default:
//                            return   BaseResult.getFailureMessageEntity("未匹配到表单！当前formID：" + formApp,  "");
//                    }
//                    break;
//                /** 处理事件*/
//                case "onFinishWorkitem":
//                    break;
//                /** 回退前事件*/
//                case "onBeforeStepBack":
//                    break;
//                /** 回退事件*/
//                case "onStepBack":
//                    break;
//                /** 取回前事件*/
//                case "onBeforeTakeBack":
//                    break;
//                /** 取回事件*/
//                case "onTakeBack":
//                    break;
//                default:
////                throw new RuntimeException("传入了非法事件类型！请参照：" + eventTypeBuffer.toString());
//                    return   BaseResult.getFailureMessageEntity("传入了非法事件类型！请参照：" + eventTypeBuffer.toString(), "", "");
//            }
//            return BaseResult.getSuccessMessageEntity("传递成功",  result);
//        }catch (Exception e){
//            return BaseResult.getFailureMessageEntity("传递失败",e.getMessage());
//        }
    }


    @Override
    public JsonResultEntity thirdInterfaceSeeYonDefinitionRePush(JSONObject jsonObject) throws Exception {
        JSONObject requestData = jsonObject.getJSONObject("jsonStr");
        JSONArray resultEntityArray = new JSONArray();
        if (null == requestData) {
            throw new BaseSystemException("参数传递错误需要jsonStr!");
        }
        //表单模版ID
        String formAppId = requestData.getString("formAppId");
        //事件事件类型
        String eventType = requestData.getString("eventType");
        //数据源编码
        String dataSourceCode = requestData.getString("dataSourceCode");
        //主表ID集合 formMainIds
        JSONArray formMainIds = requestData.getJSONArray("formMainIds");
        if (StrUtil.isEmpty(eventType)) {
            throw new BaseSystemException("需要传递eventType 参照致远OA事件!");
        }
        if (StrUtil.isEmpty(formAppId)) {
            throw new BaseSystemException("需要传递formAppId 参照致远OA 表 CAP_FORM_DEFINITION!");
        }
        if (StrUtil.isEmpty(dataSourceCode)) {
            throw new BaseSystemException("需要传递dataSourceCode 参照中台表 sys_data_source!");
        }
        if (null == formMainIds || formMainIds.size() == 0) {
            throw new BaseSystemException("需要传递业务主表数据id集合,不允许全量推送!");
        }

        SeeYonInterFaceEntity seeYonInterFaceEntity = new SeeYonInterFaceEntity();
        BeanUtil.copyProperties(requestData, seeYonInterFaceEntity);
        List<SeeYonInterFaceEntity> seeYonInterFaceEntityList = seeYonInterFaceDao.queryDefinitionInfo(seeYonInterFaceEntity);
        if (null != seeYonInterFaceEntityList && seeYonInterFaceEntityList.size() > 0) {
            for (SeeYonInterFaceEntity interFaceEntity : seeYonInterFaceEntityList) {
                String field_info = interFaceEntity.getField_info();
                JSONObject infoJson = JSON.parseObject(field_info);
                //获取主表信息
                JSONObject formMain = infoJson.getJSONObject("front_formmain");
                //获取明细表信息
                JSONArray formSons = infoJson.getJSONArray("formsons");
                //主表tableName
                String formMainTableName = formMain.getString("tableName");

                /** 设置主表查询条件*/
                interFaceEntity.setTabName(formMainTableName);
                interFaceEntity.setDataSourceCode(dataSourceCode);
                interFaceEntity.setFormMainIds(formMainIds.toJavaList(String.class));

                List<Map<String, Object>> forMainList = seeYonInterFaceDao.queryDefinitionData(interFaceEntity);
                for (Map<String, Object> forMainRow : forMainList) {
                    //定义致远OA事件对象
                    JSONObject seeYonBean = new JSONObject();
                    //定义主表对象
                    JSONObject formMainObj = new JSONObject();
                    //获取主表ID
                    String forMainId = String.valueOf(forMainRow.get("ID"));
                    //组装主表数据
                    for (Map.Entry<String, Object> entry : forMainRow.entrySet()) {
                        formMainObj.put(entry.getKey().toLowerCase(), entry.getValue());
                    }
                    //组装明细表数据
                    if (null != formSons && formSons.size() > 0) {
                        for (Object formSon : formSons) {
                            JSONObject son = JSON.parseObject(JSON.toJSONString(formSon));
                            //明细数据
                            String sonTableName = son.getString("tableName");
                            SeeYonInterFaceEntity details = new SeeYonInterFaceEntity();
                            details.setFormMainId(forMainId);
                            details.setTabName(sonTableName);
                            details.setDataSourceCode(dataSourceCode);
                            JSONArray jsonArray = new JSONArray();
                            List<Map<String, Object>> forSonList = seeYonInterFaceDao.queryDefinitionData(details);
                            for (Map<String, Object> forSons : forSonList) {
                                //组装明细数据
                                JSONObject forSonJson = new JSONObject();
                                for (Map.Entry<String, Object> entry : forSons.entrySet()) {
                                    forSonJson.put(entry.getKey().toLowerCase(), entry.getValue());
                                }
                                jsonArray.add(forSonJson);
                            }
                            //设置明细表数据
                            seeYonBean.put(sonTableName, jsonArray);
                        }
                    }

                    seeYonBean.put(formMainTableName, formMainObj);
                    JSONObject rePushRequestData = new JSONObject();
                    JSONObject object = new JSONObject();
                    object.put("formApp", formAppId);
                    object.put("eventType", eventType);
                    object.put("businessDataStr", seeYonBean.toJSONString());
                    object.put("affairId", "");
                    object.put("summaryId", requestData.getString("summaryId"));
                    object.put("currentActivityId", "");
                    object.put("id", forMainId);
                    object.put("hzyaExtData", requestData.getJSONObject("hzyaExtData"));
                    logger.info("Method:thirdInterfaceSeeYonDefinitionRePush 组装seeYonBean DATA: {}", seeYonBean.toJSONString());

                    rePushRequestData.put("jsonStr", object);


                    JsonResultEntity resultEntity = thirdInterfaceSeeYonPlugInInterfaceEntrance(rePushRequestData);
                    if (null != resultEntity) {
                        resultEntityArray.add(resultEntity.getAttribute());
                    } else {
                        JSONObject jsonResultEntity = new JSONObject();
                        jsonResultEntity.put("msg", "从新推送失败");
                        jsonResultEntity.put("id", forMainId);
                        resultEntityArray.add(jsonResultEntity);

                    }

                }
            }
        }
        return BaseResult.getSuccessMessageEntity("从新推送执行结束", resultEntityArray);
    }

    /**
     * seeyon流程事件监听前置方法，绑定数据源
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @Override
    public SysExtensionApiEntity colEventPre(SysExtensionApiEntity entity) throws Exception {
        try {
            SysApplicationEntity applicationEntity = entity.getSendApp();
            SysApplicationDatabaseEntity sysApplicationDatabaseEntity = new SysApplicationDatabaseEntity();
            sysApplicationDatabaseEntity.setSts("Y");
            sysApplicationDatabaseEntity.setDbStatus("1");
            sysApplicationDatabaseEntity.setAppId(applicationEntity.getId());
            sysApplicationDatabaseEntity.setDataSourceCode("master");
            List<SysApplicationDatabaseEntity> sysDataSourceEntities = sysApplicationDatabaseDao.queryDSBase(sysApplicationDatabaseEntity);
            if (sysDataSourceEntities != null && sysDataSourceEntities.size() > 0) {
                String parm = entity.getBodys();
                JSONObject jsonObject = JSONObject.parseObject(parm);
                jsonObject.put("dataSourceCode", sysDataSourceEntities.get(0).getSourceCode());
                entity.setBodys(jsonObject.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return entity;
    }

    /**
     * seeyon流程事件监听
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    public JsonResultEntity colEventListener(JSONObject jsonObject) throws Exception {
        try {
            if (null != jsonObject && StrUtil.isNotEmpty(jsonObject.getString("jsonStr"))) {
                SeeYonInterFaceEntity entity = jsonObject.getJSONObject("jsonStr").toJavaObject(SeeYonInterFaceEntity.class);
                JSONObject requestData = new JSONObject();
                //表单模版ID
                requestData.put("formAppId", entity.getFormAppId());
                //事件事件类型
                requestData.put("eventType", entity.getEventType());
                //数据源编码
                requestData.put("dataSourceCode", entity.getDataSourceCode());
                requestData.put("formMainIds", entity.getFormMainIds());
                requestData.put("summaryId", entity.getSummaryId());
                JSONObject jsonStr = new JSONObject();
                jsonStr.put("jsonStr", requestData);
                thirdInterfaceSeeYonDefinitionRePush(jsonStr);
            }
        } catch (Exception e) {
            logger.error("流程事件通知接口出错:{}", e);
            return BaseResult.getSuccessMessageEntity("失败", e.getMessage());
        }
        return BaseResult.getSuccessMessageEntity("成功");
    }

    /**
     * seeyon流程事件监听后置方法，调用三方接口
     *
     * @param jsonStr
     * @param formAppId
     * @param eventType
     * @return
     * @throws Exception
     */
    @Override
    public JsonResultEntity colEventPost(String jsonStr, String formAppId, String eventType) throws Exception {
        if (StrUtil.isNotEmpty(jsonStr) && StrUtil.isNotEmpty(formAppId) && StrUtil.isNotEmpty(eventType)) {
            SysApplicationApiEntity sysApplicationApiEntity = new SysApplicationApiEntity();
            sysApplicationApiEntity.setHeaderIn(formAppId + "_" + eventType);
            List<SysApplicationApiEntity> applist = sysApplicationApiService.queryLike(sysApplicationApiEntity);
            if (CollectionUtil.isNotEmpty(applist)) {
                if (applist.size() > 1) {
                    throw new BaseSystemException("根据formID：" + formAppId + "查询出多条数据");
                }
                if (applist.size() == 0 ) {
                    throw new BaseSystemException("根据formID：" + formAppId + "eventType:"+eventType+"未查询到API配置");
                }
                SysApplicationApiEntity sysApp = applist.get(0);
                //数据源配置
                SysApplicationDatabaseEntity sysApiDatabase = new SysApplicationDatabaseEntity();
                sysApiDatabase.setAppId(sysApp.getAppId());
                List<SysApplicationDatabaseEntity> apiDataBaseList = sysApplicationDatabaseDao.queryDSBase(sysApiDatabase);
                if (CollectionUtils.isNotEmpty(apiDataBaseList) && apiDataBaseList.size() == 1){
                    sysApiDatabase = apiDataBaseList.get(0);
                }
                JSONArray headerArray = JSONArray.parseArray(sysApp.getHeaderIn());
                Map<String,String> headerMap = new HashMap<>();
                if (null != headerArray && headerArray.size() > 0) {
                    for (int i = 0; i < headerArray.size(); i++) {
                        JSONObject querys = headerArray.getJSONObject(i);
                        //query 只有基本类型，不用循环判断下级
                        //判断参数是否有值
                        //获取对象下面的层级数据
                        String parameterName = querys.getString("parameterName");
                        String example = querys.getString("example");
                        headerMap.put(parameterName,example);
                    }
                    if (headerMap.isEmpty()){
                        throw new BaseSystemException("根据formID：" + formAppId + "未获取到head参数");
                    }
                    PluginBaseEntity pluginBaseEntity = PluginUtils.getPluginsById(headerMap.get("plugId"));
                    if (null == pluginBaseEntity) {
                        throw new BaseSystemException("根据ID获取插件错误！请传入正确的 pluginId");
                    }
                    //执行业务逻辑代码
                    JSONObject  reqJson = new JSONObject();
                    reqJson.put("jsonStr",jsonStr);
                    reqJson.put("formAppId",formAppId);
                    reqJson.put("eventType",eventType);
                    reqJson.put("headers",JSON.toJSONString(headerMap));
                    reqJson.put("apiDataSourceCode",sysApiDatabase.getSourceCode());
                    JsonResultEntity result = pluginBaseEntity.executeBusiness(reqJson);
                    return result;
                } else {
                    throw new BaseSystemException("根据formID：" + formAppId + "未获取到head参数");
                }
            }
        }
        return null;
    }
    @Override
    public JsonResultEntity chengeBody(JSONObject object) throws Exception {
        JSONObject jsonstr = object.getJSONObject("jsonStr");
        PluginBaseEntity pluginBaseEntity = null;
        JsonResultEntity result;
        String pluginId = jsonstr.getString("plugId");
        pluginBaseEntity = PluginUtils.getPluginsById(pluginId);
        if (null == pluginBaseEntity) {
            throw new BaseSystemException("根据ID获取插件错误！请传入正确的 pluginId");
        } else {
            //执行业务逻辑代码
            result = pluginBaseEntity.executeBusiness(object);
        }
        return result;
    }

    @Override
    public SysExtensionApiEntity chengeBodySetPlug(SysExtensionApiEntity entity) {
        Map<String, String> headers = entity.getHeaders();
        JSONObject jsonObject = JSONObject.parseObject(entity.getBodys());
        jsonObject.put("plugId", headers.get("plugId"));
        entity.setBodys(jsonObject.toJSONString());
        return entity;
    }


    @Override
    public SysExtensionApiEntity getToken(SysExtensionApiEntity entity) {
        Map<String, String> headers = entity.getHeaders();
        SysApplicationApiEntity sysApplicationEntity =  entity.getReceiveApi();
        SysApplicationEntity sendApp =  entity.getSendApp();
        SysApplicationEntity receiveApp =  entity.getReceiveApp();
        if("1".equals(sysApplicationEntity.getNeedLogin()) && sysApplicationEntity.getAuthenticationPort() != null){
            SysApplicationApiEntity loginApi = getApiByAppIdApiCode(sysApplicationEntity.getAuthenticationPort());
            if (null == loginApi) {
                return entity;
            }
            String rzquerys = getQuery(loginApi,null,null);
            Map<String, String> headersa = new HashMap<>();
            headersa.put("publicKey", sendApp.getPublicKey());
            headersa.put("secretKey", sendApp.getSecretKey());
            headersa.put("appId", receiveApp.getAppId().toString());
            headersa.put("apiCode", loginApi.getApiCode().toString());
            Map<String, String> rzheaders = getHeaders(loginApi,headersa,null);
            String rzbodys = getBodys(loginApi,null,null);
            JsonResultEntity rzjsonResultEntity = sendData(loginApi,rzheaders,rzbodys,rzquerys);
            if (!rzjsonResultEntity.isFlag()) {
                return entity;
            }
            JSONObject attritube = JSONObject.parseObject(rzjsonResultEntity.getAttribute().toString());
            headers.put("token",attritube.getJSONObject("attribute").getString("id"));
        }
        entity.setHeaders(headers);
        return entity;
    }
    private SysApplicationApiEntity getApiByAppIdApiCode(String apiId) {

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

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

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

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

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

    private String getBodys(SysApplicationApiEntity loginApi,String sendDatastr, JSONObject loginData) {
        JSONObject sendData = new JSONObject();
        if(sendDatastr != null ){
            sendData = JSONObject.parseObject(sendDatastr);
        }
        if(loginData == null){
            loginData = new JSONObject();
        }
        if (loginApi.getBodyIn() != null && !"".equals(loginApi.getBodyIn())) {
            if (JSONUtil.isTypeJSONArray(loginApi.getBodyIn())) {
                JSONArray headerbodyArray = JSON.parseArray(loginApi.getBodyIn());
                JSONObject bodyjson = headerbodyArray.getJSONObject(0);
                JSONArray headerArray = bodyjson.getJSONArray("children");
                for (int i = 0; i < headerArray.size(); i++) {
                    //获取到第一个数据
                    JSONObject querys = headerArray.getJSONObject(i);
                    if (SysEnum.FUNDAMENTAL.getValue().equals(querys.getString(SysEnum.PARAMETERTYPE.getValue()))) {//认证类型
                        String query = querys.getString(SysEnum.EXAMPLE.getValue());
                        if (query != null && !"".equals(query)) {
                            sendData.put(querys.getString(SysEnum.PARAMETERNAME.getValue()),query);
                        }
                    }
                }
            }
        }
        return sendData.toString();
    }

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




    }

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