package com.jianshui.invoice.utils.elephant;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dxhy.order.InvokeDxhyApi;
import com.dxhy.order.protocol.invoke.DxhyInterfaceRequest;
import com.dxhy.order.protocol.invoke.DxhyInterfaceResponse;
import com.jianshui.common.core.domain.AjaxResult;
import com.jianshui.common.core.domain.entity.Companyservice;
import com.jianshui.common.core.redis.RedisCache;
import com.jianshui.common.exception.jianshui.JianshuiParamErrorException;
import com.jianshui.common.exception.jianshui.JianshuiServiceConfigErrorException;
import com.jianshui.common.exception.jianshui.JianshuiServiceException;
import com.jianshui.common.utils.StringUtils;
import com.jianshui.common.utils.http.HttpUtils;
import com.jianshui.common.utils.jianshui.CommonUtils;
import com.jianshui.common.utils.spring.SpringUtils;
import com.jianshui.invoice.constant.elephant.ElephantConstants;
import com.jianshui.invoice.domain.dto.HXResponse;
import com.jianshui.system.domain.CompanyserviceProp;
import com.jianshui.system.service.ICompanyservicePropService;
import com.jianshui.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.core.env.Environment;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description 大象销项工具类
 * @Author 巩权林
 * @Date 2022-03-24 11:32
 **/
@Slf4j
public class ElephantUtils {

    // 大象V6地址
    private static String ELE_URL_v6;
    // 大象普通服务
    private static String ELE_URL;

    static {
        Environment environment = SpringUtils.getBean(Environment.class);
        ELE_URL_v6 = environment.getProperty("ele_url_v6");
        ELE_URL = environment.getProperty("ele_url");
    }


    public static AjaxResult sendRequest(String uri, JSON data, Companyservice companyservice, Boolean useEleCloudUrl) {
        ISysConfigService configService = SpringUtils.getBean(ISysConfigService.class);

        boolean isDevMode = CommonUtils.isDevMode();

        String host = useEleCloudUrl ? ElephantConstants.PROD_ELECLOUD_HOST : ElephantConstants.PROD_HOST;
        // String host = ElephantConstants.PROD_TOKEN_HOST;
        if (isDevMode) {
            host = useEleCloudUrl ? ElephantConstants.DEV_ELECLOUD_HOST : ElephantConstants.DEV_HOST;
            // host = ElephantConstants.DEV_TOKEN_HOST;
        }
        String url = host + uri;

        String token = getToken(companyservice);
        if (token == "") {
            return null;
        }
        url += "?access_token=" + token; // 拼接token

        // 先处理下请求体
        JSONObject requestBody = new JSONObject();
        String entCode = configService.selectConfigByKey("elephant_entcode");
        requestBody.put("entCode", entCode);
        requestBody.put("zipCode", 0); // 不压缩
        requestBody.put("encryptCode", 0); // 不加密

        // 处理下数据交换流水号
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dataExchangeId = df.format(new Date());
        String randomString = Long.toString((long) (Math.random() * 9 * Math.pow(10, 14)) + (long) Math.pow(10, 14));
        requestBody.put("dataExchangeId", dataExchangeId + randomString); // 数据交换流水号
        BASE64Encoder encoder = new BASE64Encoder();
        String dataJson = JSONUtil.toJsonStr(data);
        // data.toJSONString();
        byte[] contentByte = dataJson.getBytes();

        requestBody.put("content", encoder.encode(contentByte));
        JSONObject result = null; // 返回的结果
        String stringRequest = "";
        HttpClient httpclient = null;
        PostMethod post = null;
        try {
            // 构造请求String
            stringRequest = requestBody.toJSONString();
            System.out.println(stringRequest);
            RequestEntity se = new StringRequestEntity(stringRequest, "application/json", "UTF-8");
            // 开始构造请求体
            httpclient = new HttpClient();
            post = new PostMethod(url);
            //设置编码方式
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            // 设置请求体
            post.setRequestEntity(se);
            //执行
            httpclient.executeMethod(post);
            //接口返回信息
            InputStream inputStream = post.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
            result = JSONObject.parseObject(stringBuffer.toString());
            log.info("【大象工具类】请求返回报文：" + stringBuffer.toString());
            // 处理外层报文信息
            // 先检查外部state
            JSONObject returnStateInfo = result.getJSONObject("returnStateInfo");
            String returnCode = returnStateInfo.getString("returnCode");
            if (!StringUtils.equals("0000", returnCode)) {
                String base64Result = returnStateInfo.getString("returnMessage");
                String errorMsg = new String(Base64.decodeBase64(base64Result));
                return AjaxResult.error(errorMsg);
            }

            // 返回内层报文content
            String content = new String(Base64.decodeBase64(result.getString("content")));
            try {
                JSONObject contentJson = JSONObject.parseObject(content);
                return AjaxResult.success(contentJson);
            } catch (com.alibaba.fastjson.JSONException e) {
                JSONArray contentArray = JSONArray.parseArray(content);
                return AjaxResult.success(contentArray);
            }


        } catch (Exception e) {
            result = null;
            e.printStackTrace();
            log.error("【销项】【大象接口】调用HttpsUtil.sendToNuoNuo Exception, url=" + url + ",request=" + stringRequest, e);
        } finally {
            //关闭连接，释放资源
            post.releaseConnection();
            ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
        }

        return AjaxResult.error("请求失败");
    }

    public static AjaxResult sendRequest(String uri, JSON data) {
        ISysConfigService configService = SpringUtils.getBean(ISysConfigService.class);

        boolean isDevMode = CommonUtils.isDevMode();

        String host = ElephantConstants.PROD_HOST;
        // String host = ElephantConstants.PROD_TOKEN_HOST;
        if (isDevMode) {
            host = ElephantConstants.DEV_HOST;
            // host = ElephantConstants.DEV_TOKEN_HOST;
        }
        String url = host + uri;

        String token = getToken();
        if (token == "") {
            return null;
        }
        url += "?access_token=" + token; // 拼接token

        // 先处理下请求体
        JSONObject requestBody = new JSONObject();
        String entCode = configService.selectConfigByKey("elephant_entcode");
        requestBody.put("entCode", entCode);
        requestBody.put("zipCode", 0); // 不压缩
        requestBody.put("encryptCode", 0); // 不加密

        // 处理下数据交换流水号
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String dataExchangeId = df.format(new Date());
        String randomString = Long.toString((long) (Math.random() * 9 * Math.pow(10, 14)) + (long) Math.pow(10, 14));
        requestBody.put("dataExchangeId", dataExchangeId + randomString); // 数据交换流水号
        BASE64Encoder encoder = new BASE64Encoder();
        String dataJson = JSONUtil.toJsonStr(data);
        // data.toJSONString();
        byte[] contentByte = dataJson.getBytes();

        requestBody.put("content", encoder.encode(contentByte));
        JSONObject result = null; // 返回的结果
        String stringRequest = "";
        HttpClient httpclient = null;
        PostMethod post = null;
        try {
            // 构造请求String
            stringRequest = requestBody.toJSONString();
            RequestEntity se = new StringRequestEntity(stringRequest, "application/json", "UTF-8");
            // 开始构造请求体
            httpclient = new HttpClient();
            post = new PostMethod(url);
            //设置编码方式
            post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            // 设置请求体
            post.setRequestEntity(se);
            //执行
            httpclient.executeMethod(post);
            //接口返回信息
            InputStream inputStream = post.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer stringBuffer = new StringBuffer();
            String str = "";
            while ((str = br.readLine()) != null) {
                stringBuffer.append(str);
            }
            result = JSONObject.parseObject(stringBuffer.toString());
            log.info("【大象工具类】请求返回报文：" + stringBuffer.toString());
            // 处理外层报文信息
            // 先检查外部state
            JSONObject returnStateInfo = result.getJSONObject("returnStateInfo");
            String returnCode = returnStateInfo.getString("returnCode");
            if (!StringUtils.equals("0000", returnCode)) {
                String base64Result = returnStateInfo.getString("returnMessage");
                String errorMsg = new String(Base64.decodeBase64(base64Result));
                return AjaxResult.error(errorMsg);
            }

            // 返回内层报文content
            String content = new String(Base64.decodeBase64(result.getString("content")));
            try {
                JSONObject contentJson = JSONObject.parseObject(content);
                return AjaxResult.success(contentJson);
            } catch (com.alibaba.fastjson.JSONException e) {
                JSONArray contentArray = JSONArray.parseArray(content);
                return AjaxResult.success(contentArray);
            }


        } catch (Exception e) {
            result = null;
            e.printStackTrace();
            log.error("【销项】【大象接口】调用HttpsUtil.sendToNuoNuo Exception, url=" + url + ",request=" + stringRequest, e);
        } finally {
            //关闭连接，释放资源
            post.releaseConnection();
            ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
        }

        return AjaxResult.error("请求失败");
    }

    public static String getToken(Companyservice companyservice) {
        ICompanyservicePropService configService = SpringUtils.getBean(ICompanyservicePropService.class);
        CompanyserviceProp companyserviceProp = configService.selectPropByKey(companyservice.getCompanyid(), "elephant_appkey");
        String appkey = companyserviceProp.getValue();
        if (appkey == null || "".equals(appkey)) {
            throw new JianshuiServiceConfigErrorException("未配置上游app key！");
        }
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        JSONObject temp = redisCache.getCacheObject(ElephantConstants.TOKEN_REDIS_KEY + "appkey:" + appkey);

        // 如果不为空，且没有过期
        if (temp != null) {
            return (String) temp.get("access_token");
        }

        companyserviceProp = configService.selectPropByKey(companyservice.getCompanyid(), "elephant_secret");
        String appSecret = companyserviceProp.getValue();
        if (appSecret == null || "".equals(appSecret)) {
            throw new JianshuiServiceConfigErrorException("未配置上游app secret！");
        }
        boolean isDevMode = CommonUtils.isDevMode();

//        String url = ElephantConstants.PROD_TOKEN_HOST;
//        if (isDevMode) {
//            url = ElephantConstants.DEV_TOKEN_HOST;
//        }
        // TODO 20231109 地址改成了京东云
        /*String url = ElephantConstants.PROD_HOST_LOCAL_V6_JingDongYun;
        if (isDevMode) {
            url = ElephantConstants.DEV_HOST_LOCAL_V6_JingDongYun;
        }*/

        String url = ELE_URL;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appKey", appkey);
        jsonObject.put("appSecret", appSecret);
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        String info = HttpUtils.sendJsonPost(url, jsonObject, header);
        log.info("【销项】【大象接口】调用京东云，调用地址：{},入参：{},头信息：{},返回结果：{}",url,jsonObject,header,info);
        JSONObject obj = JSONObject.parseObject(info);
        redisCache.setCacheObject(ElephantConstants.TOKEN_REDIS_KEY + "appkey:" + appkey, obj, (int) obj.get("expires_in") - 60, TimeUnit.SECONDS);
        return (String) obj.get("access_token");

    }

    public static String getToken() {
        RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
        ISysConfigService configService = SpringUtils.getBean(ISysConfigService.class);
        JSONObject temp = redisCache.getCacheObject(ElephantConstants.TOKEN_REDIS_KEY);

        // 如果不为空，且没有过期
        if (temp != null) {
            return (String) temp.get("access_token");
        }

        String appkey = configService.selectConfigByKey("elephant_appkey");
        if (appkey == null || "".equals(appkey)) {
            throw new JianshuiServiceConfigErrorException("未配置大象app key！");
        }
        String appSecret = configService.selectConfigByKey("elephant_secret");
        if (appSecret == null || "".equals(appSecret)) {
            throw new JianshuiServiceConfigErrorException("未配置大象app secret！");
        }
        boolean isDevMode = CommonUtils.isDevMode();

        String url = ElephantConstants.PROD_TOKEN_HOST;
        if (isDevMode) {
            url = ElephantConstants.DEV_TOKEN_HOST;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appKey", appkey);
        jsonObject.put("appSecret", appSecret);
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/json");
        String info = HttpUtils.sendJsonPost(url, jsonObject, header);
        JSONObject obj = JSONObject.parseObject(info);
        redisCache.setCacheObject(ElephantConstants.TOKEN_REDIS_KEY, obj, (int) obj.get("expires_in") - 60, TimeUnit.SECONDS);
        return (String) obj.get("access_token");
    }


    /**
     * 大象请求 大象部署版 v6 无token
     * Post请求
     *
     * @param uri            请求uri
     * @param methodName     文档里的"接口方法"
     * @param data           请求体
     * @param companyservice companyservice
     * @return
     */
    public static DxhyInterfaceResponse sendRequestWithoutTokenV6(String uri, String methodName, JSON data, Companyservice companyservice) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

        ICompanyservicePropService companyserviceProp = SpringUtils.getBean(ICompanyservicePropService.class);
        CompanyserviceProp secretIdProp = companyserviceProp.selectPropByKey(companyservice.getCompanyid(), "elephant_secret_id");
        if (secretIdProp == null) {
            throw new JianshuiServiceException("企业未配置属性，请联系管理员！");
        }

        String secretId = secretIdProp.getValue();
        CompanyserviceProp sercretKeyProp = companyserviceProp.selectPropByKey(companyservice.getCompanyid(), "elephant_secret_key");
        if (sercretKeyProp == null) {
            throw new JianshuiServiceException("企业未配置属性，请联系管理员！");
        }

        String sercretKey = sercretKeyProp.getValue();
        // 调用v6请求内容（content字段）
        String str = JSONUtil.toJsonStr(data);
        boolean isDevMode = CommonUtils.isDevMode();
        // 主机名（京东云地址）
        /*String host = ElephantConstants.PROD_HOST_LOCAL_V6_JingDongYun;
        if (isDevMode) {
            host = ElephantConstants.DEV_HOST_LOCAL_V6_JingDongYun;
        }*/

        String host = ELE_URL_v6;
        // 最终接口地址
        String url = host + uri;


        // 封装大象v6调用类
        DxhyInterfaceRequest dxhyInterfaceRequest = new DxhyInterfaceRequest();
        // 地址
        dxhyInterfaceRequest.setRequestUrl(url);
        // 请求方式
        dxhyInterfaceRequest.setRequestType("POST");
        // 超时时间（毫秒值）
        dxhyInterfaceRequest.setHttpTimeOut("100000");
        // 流水号（拷贝的接口文档的）
//        dxhyInterfaceRequest.setDataExchangeId("1617954341800234234234552");
        // 生成流水号
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        long snowflakeId = snowflake.nextId();
        String snowflakeIdStr = String.valueOf(snowflakeId);
        dxhyInterfaceRequest.setDataExchangeId(snowflakeIdStr);

        // appid
        dxhyInterfaceRequest.setSecretId(secretId);
        // appkey
        dxhyInterfaceRequest.setSecretKey(sercretKey);
        // 内容字段（content请求体）
        dxhyInterfaceRequest.setContent(str);
        // 不打包
        dxhyInterfaceRequest.setZipCode("0");
        // 不加密
        dxhyInterfaceRequest.setEncryptCode("0");

        DxhyInterfaceResponse dxhyInterfaceResponse = null;

        try {

            // 大象v6调用方法（获取结果处理）
            log.info("【销项】【大象工具类】调用V6接口，入参{}", JSONUtil.toJsonStr(dxhyInterfaceRequest));
            dxhyInterfaceResponse = InvokeDxhyApi.dxhyInterfaceInvoke(dxhyInterfaceRequest);
            log.info("【销项】【大象工具类】请求成功，结果{}", JSONUtil.toJsonStr(dxhyInterfaceResponse));


        } catch (Exception e) {
            log.error("【销项】【大象接口】调用HttpsUtilV6.Exception, url=" + url + ",request=" + JSONUtil.toJsonStr(dxhyInterfaceRequest), e);
        }

        return dxhyInterfaceResponse;
    }


    /**
     * 大象请求 大象部署版 1.2.4 无token
     *
     * @param uri            请求uri
     * @param methodName     文档里的"接口方法"
     * @param data           请求体
     * @param companyservice companyservice
     * @return
     */
    public static AjaxResult sendRequestWithoutToken(String uri, String methodName, JSON data, Companyservice companyservice) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        ICompanyservicePropService companyserviceProp = SpringUtils.getBean(ICompanyservicePropService.class);
        CompanyserviceProp secretIdProp = companyserviceProp.selectPropByKey(companyservice.getCompanyid(), "elephant_secret_id");
        if (secretIdProp == null) {
            throw new JianshuiServiceException("企业未配置属性，请联系管理员！");
        }
        String secretId = secretIdProp.getValue();
        CompanyserviceProp sercretKeyProp = companyserviceProp.selectPropByKey(companyservice.getCompanyid(), "elephant_secret_key");
        if (sercretKeyProp == null) {
            throw new JianshuiServiceException("企业未配置属性，请联系管理员！");
        }
        String sercretKey = sercretKeyProp.getValue();
        boolean isDevMode = CommonUtils.isDevMode();

//        String host = ElephantConstants.PROD_HOST_LOCAL;
//        if (isDevMode) {
//            host = ElephantConstants.DEV_HOST_LOCAL;
//        }

        // TODO : 2023/11/09 大象接口迁京东云
        /*String host = ElephantConstants.PROD_HOST_LOCAL_V6_JingDongYun;
        if (isDevMode) {
            host = ElephantConstants.DEV_HOST_LOCAL_V6_JingDongYun;
        }*/

        String host = ELE_URL;

        //kk TODO : 2023/9/5 大象接口迁京东云
        //https://js.ele12.com/
//        host = "https://js.ele12.com/order-api";
        String url = host + uri;

        // String token = getToken();
        // if (token == "") {
        //     return null;
        // }
        // url += "?access_token=" + token; // 拼接token

        // 先处理下请求体
        // JSONObject requestBody = new JSONObject();
        Map<String, Object> requestBody = new LinkedHashMap<>();
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] contentByte = JSONUtil.toJsonStr(data).getBytes();
        // byte[] contentByte  = "{\"DDPCXX\":{\"DDQQPCH\":\"5767e3e0907c4e3c848c3f459b68394b\",\"NSRSBH\":\"110101MYJ2GPQQ4\",\"FPLXDM\":\"004\"},\"DDZXX\":[{\"DDTXX\":{\"DDQQLSH\":\"4767e3e0907c4e3c848c3f459b68394b\",\"NSRSBH\":\"110101MYJ2GPQQ4\",\"NSRMC\":\"测试 localhost\",\"KPLX\":\"0\",\"XHFSBH\":\"110101MYJ2GPQQ4\",\"XHFMC\":\"测试 localhost\",\"XHFDZ\":\"山东省济南市济微路141号中铁物流园1楼\",\"XHFDH\":\"1\",\"XHFYH\":\"齐鲁银行济南王官庄支行 1170 8140 0000 0016 252\",\"XHFZH\":\"1170814000000016252\",\"GMFSBH\":\"91320700774687205M\",\"GMFMC\":\"连云港天邦科技开发有限公司\",\"GMFDZ\":\"江苏省连云港市海州开发区新浦工业园振兴路\",\"GMFDH\":\"0518-85287867\",\"GMFYH\":\"江苏银行连云港浦中支行 \",\"GMFZH\":\"70300101314068535\",\"GMFLX\":\"01\",\"KPR\":\"test1\",\"QDBZ\":\"0\",\"JSHJ\":\"7475.76\",\"HJJE\":\"6615.72\",\"HJSE\":\"860.04\",\"DDH\":\"4767e3e0907c4e3c848c3f459b68394b\",\"DDSJ\":\"2022-05-17 10:09:33\"},\"DDMXXX\":[{\"XH\":\"1\",\"FPHXZ\":\"0\",\"SPBM\":\"108020799\",\"YHZCBS\":\"0\",\"XMMC\":\"圆钢\",\"GGXH\":\"60\",\"DW\":\"吨\",\"SPSL\":1.014,\"DJ\":\"4991.15\",\"JE\":\"5061.03\",\"HSBZ\":\"0\",\"SL\":\"0.13\",\"SE\":\"657.93\",\"BYZD1\":\"\",\"BYZD2\":\"\",\"BYZD3\":\"\"},{\"XH\":\"2\",\"FPHXZ\":\"0\",\"SPBM\":\"108020799\",\"YHZCBS\":\"0\",\"XMMC\":\"圆钢\",\"GGXH\":\"55\",\"DW\":\"吨\",\"SPSL\":0.23,\"DJ\":\"4902.65\",\"JE\":\"1127.61\",\"HSBZ\":\"0\",\"SL\":\"0.13\",\"SE\":\"146.59\",\"BYZD1\":\"\",\"BYZD2\":\"\",\"BYZD3\":\"\"},{\"XH\":\"3\",\"FPHXZ\":\"0\",\"SPBM\":\"108020799\",\"YHZCBS\":\"0\",\"XMMC\":\"圆钢\",\"GGXH\":\"10\",\"DW\":\"吨\",\"SPSL\":0.076,\"DJ\":\"5619.47\",\"JE\":\"427.08\",\"HSBZ\":\"0\",\"SL\":\"0.13\",\"SE\":\"55.52\",\"BYZD1\":\"\",\"BYZD2\":\"\",\"BYZD3\":\"\"}]}]}".getBytes();
        String byteContent = encoder.encode(contentByte);

        byte[] aaa = cn.hutool.core.codec.Base64.decode(byteContent);
        String result11 = new String(aaa, StandardCharsets.UTF_8);
        System.out.println(result11);


        int randomInt = RandomUtil.randomInt(10, 100);
        requestBody.put("Nonce", Integer.toString(randomInt));
        requestBody.put("SecretId", secretId);
        requestBody.put("Timestamp", Long.toString(DateUtil.currentSeconds()));
        requestBody.put("content", byteContent);
        requestBody.put("encryptCode", "0"); // 不加密
        requestBody.put("zipCode", "0"); // 不压缩
        Iterator it = requestBody.keySet().iterator();
        String query = "";
        while (it.hasNext()) {
            String key = (String) it.next();
            String value = (String) requestBody.get(key);
            query += "&" + key + "=" + value;
        }
        query = StrUtil.removePrefix(query, "&");
        query = query.replace("_", ".");
        query = "POST" +
                host.replace("http://", "").replace("https://", "") +
                uri +
                "?" +
                query;
        String srcStr = query;
        String sign = localSign(sercretKey, srcStr);
        // String sign = localSign("27a06832a2214a4fa3b7105e4a72d370", "POSTapi.ele-cloud.com/order-api/invoice/api/v4/interfaceTest?Nonce=11886&SecretId=289efb7512e54146273b982456b03f42ea93&Timestamp=1484718385&content=ewogICAgIlBhcmFtZXRlciI6ICIxIgp9&encryptCode=0&zipCode=0");
        // SecretKeySpec keySpec = new SecretKeySpec(sercretKey.getBytes("UTF-8"), "HmacSHA1");
        // Mac mac = Mac.getInstance("HmacSHA1");
        // mac.init(keySpec);
        // byte[] signBytes = mac.doFinal(srcStr.getBytes("UTF-8"));
        // String sign = Base64.encodeBase64URLSafeString(signBytes);
        requestBody.put("Signature", sign);

        JSONObject result = null; // 返回的结果
        String stringRequest = "";
        try {
            // it = requestBody.keySet().iterator();
            // 构造请求String
            // while (it.hasNext()) {
            //     String key = (String) it.next();
            //     String value = requestBody.getString(key);
            //     stringRequest += "&" + key + "=" + value;
            // }
            // stringRequest = StrUtil.removePrefix(stringRequest, "&");
            // RequestEntity se = new StringRequestEntity(stringRequest, "application/json", "UTF-8");

            // 开始构造form data
            log.info("【大象工具类】向大象请求报文：{}，原始报文：{}", requestBody.toString(), JSONUtil.toJsonStr(data));
            //kk TODO : 2023/8/26 本地调试
//            url = url.replace("140.143.226.17","127.0.0.1");
            String response = HttpRequest.post(url)
                    // .setHttpProxy("127.0.0.1", 9090)
                    .contentType(ContentType.MULTIPART.getValue())
                    .form(requestBody)//表单内容
                    .timeout(10000)//超时，毫秒
                    .execute().body();

            log.info("【大象工具类】请求返回报文：" + response);
            result = JSONObject.parseObject(response);
            // 处理外层报文信息
            // 先检查外部state
            JSONObject responseStatus = result.getJSONObject("responseStatus");
            String returnCode = responseStatus.getString("code");
            if (!StringUtils.equals("0000", returnCode)) {
                String message = responseStatus.getString("message");
                return AjaxResult.error(message);
            }

            // 返回内层报文content
            JSONObject responseData = result.getJSONObject("responseData");
            String content = new String(Base64.decodeBase64(responseData.getString("content")));
            try {
                JSONObject contentJson = JSONObject.parseObject(content);
                return AjaxResult.success(contentJson);
            } catch (com.alibaba.fastjson.JSONException e) {
                JSONArray contentArray = JSONArray.parseArray(content);
                return AjaxResult.success(contentArray);
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("【销项】【大象接口】调用HttpsUtil.sendToNuoNuo Exception, url=" + url + ",request=" + stringRequest, e);
        } finally {
            //关闭连接，释放资源
        }

        return AjaxResult.error("请求失败");
    }

    /**
     * 大象本地部署的验签
     *
     * @return
     */
    public static String localSign(String secretKey, String srcStr) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
        // secretKey = "27a06832a2214a4fa3b7105e4a72d370";
        // srcStr = "POSTapi.ele-cloud.com/order-api/invoice/api/v4/interfaceTest?Nonce=11886&SecretId=289efb7512e54146273b982456b03f42ea93&Timestamp=1484718385&content=ewogICAgIlBhcmFtZXRlciI6ICIxIgp9&encryptCode=0&zipCode=0";
        SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
        byte[] signBytes = mac.doFinal(srcStr.getBytes("UTF-8"));
        String sign = Base64.encodeBase64URLSafeString(signBytes);
        System.out.println(sign);
        return sign;
    }

    /**
     * 大象发票类型转换
     *
     * @param originType 原始类型
     * @param to         要转换到的目标类型，1：转换为大象的类型；2转换为系统类型
     * @return
     */
    public static String transElephantType(String originType, int to) {
        if (to == 1) {
            switch (originType) {
                case "p":
                    return "026";
                case "c":
                    return "007";
                case "s":
                    return "004";
                case "b":
                    return "028";
                case "j":
                    // return "005";
                    throw new JianshuiParamErrorException("暂不支持的开票类型，请联系管理员！", null, "invoice");
                case "u":
                    // return "006";
                    throw new JianshuiParamErrorException("暂不支持的开票类型，请联系管理员！", null, "invoice");
                    //普票
                case "82":
                    return "002";
                case "81":
                    return "001";
                case "":
                default:
                    throw new JianshuiParamErrorException("暂不支持的开票类型，请联系管理员！", null, "invoice");
            }
        }

        if (to == 2) {
            switch (originType) {
                case "026":
                    return "p";
                case "007":
                    return "c";
                case "004":
                    return "s";
                case "028":
                    return "b";
                case "005":
                    return "j";
                case "006":
                    return "u";
                case "002":
                    return "82";
                case "001":
                    return "81";
                default:
                    throw new JianshuiParamErrorException("暂不支持的开票类型，请联系管理员！", null, "invoice");
            }
        }
        throw new JianshuiParamErrorException("暂不支持的开票类型，请联系管理员！", null, "invoice");
    }


    /**
     * @Author: kk
     * @Description: 大象接口V6调用工具类  对应销项-》大象-》V6实例
     */
    public static AjaxResult sendRequestWithoutTokenV6New(String uri, String methodName, JSON data, Companyservice companyservice) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

        ICompanyservicePropService companyserviceProp = SpringUtils.getBean(ICompanyservicePropService.class);
        CompanyserviceProp secretIdProp = companyserviceProp.selectPropByKey(companyservice.getCompanyid(), "elephant_secret_id");
        if (secretIdProp == null) {
            throw new JianshuiServiceException("企业未配置属性，请联系管理员！");
        }

        String secretId = secretIdProp.getValue();
        CompanyserviceProp sercretKeyProp = companyserviceProp.selectPropByKey(companyservice.getCompanyid(), "elephant_secret_key");
        if (sercretKeyProp == null) {
            throw new JianshuiServiceException("企业未配置属性，请联系管理员！");
        }

        String sercretKey = sercretKeyProp.getValue();
        // 调用v6请求内容（content字段）
        String str = JSONUtil.toJsonStr(data);
        boolean isDevMode = CommonUtils.isDevMode();
        // 主机名（京东云地址）
        /*String host = ElephantConstants.PROD_HOST_LOCAL_V6_JingDongYun;
        if (isDevMode) {
            host = ElephantConstants.DEV_HOST_LOCAL_V6_JingDongYun;
        }*/
        String host = ELE_URL_v6;
        // 最终接口地址
        String url = host + uri;

        // 封装大象v6调用类
        DxhyInterfaceRequest dxhyInterfaceRequest = new DxhyInterfaceRequest();
        // 地址
        dxhyInterfaceRequest.setRequestUrl(url);
        // 请求方式
        dxhyInterfaceRequest.setRequestType("POST");
        // 超时时间（毫秒值）
        dxhyInterfaceRequest.setHttpTimeOut("100000");
        // 流水号（拷贝的接口文档的）
//        dxhyInterfaceRequest.setDataExchangeId("1617954341800234234234552");
        // 生成流水号
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        long snowflakeId = snowflake.nextId();
        String snowflakeIdStr = String.valueOf(snowflakeId);
        dxhyInterfaceRequest.setDataExchangeId(snowflakeIdStr);

        // appid
        dxhyInterfaceRequest.setSecretId(secretId);
        // appkey
        dxhyInterfaceRequest.setSecretKey(sercretKey);
        // 内容字段（content请求体）
        dxhyInterfaceRequest.setContent(str);
        // 不打包
        dxhyInterfaceRequest.setZipCode("0");
        // 不加密
        dxhyInterfaceRequest.setEncryptCode("0");

        try {
            DxhyInterfaceResponse dxhyInterfaceResponse = null;

            // 大象v6调用方法（获取结果处理）
            log.info("【销项】【大象工具类】调用V6接口，入参{}", JSONUtil.toJsonStr(dxhyInterfaceRequest));
            dxhyInterfaceResponse = InvokeDxhyApi.dxhyInterfaceInvoke(dxhyInterfaceRequest);
            log.info("【销项】【大象工具类】请求成功，结果{}", JSONUtil.toJsonStr(dxhyInterfaceResponse));

            // 返回报文处理为简税报文
            String dataDxhy = dxhyInterfaceResponse.getData();
            String codeDxhy = dxhyInterfaceResponse.getCode();
            String messageDxhy = dxhyInterfaceResponse.getMessage();

            if ("000000".equals(codeDxhy)) {
                return AjaxResult.success("000000", dataDxhy);
            } else {
                return AjaxResult.error(codeDxhy, messageDxhy);
            }

        } catch (Exception e) {
            log.error("【销项】【大象接口】调用HttpsUtilV6.Exception, url=" + url + ",request=" + JSONUtil.toJsonStr(dxhyInterfaceRequest), e);
        }

        return AjaxResult.error("9999", "请求失败！");
    }


}
