/*
 * The Hefei JingTong RDC(Research and Development Centre) Group.
 * __________________
 *
 *    Copyright 2015-2020
 *    All Rights Reserved.
 *
 *    NOTICE:  All information contained herein is, and remains
 *    the property of JingTong Company and its suppliers,
 *    if any.
 */

package com.jwipc.shopping.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.jwipc.shopping.model.vo.*;
import com.jwipc.shopping.service.IMiddleWareService;
import org.apache.http.Consts;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p> </p>
 *
 * @author EE
 * @version 1.0
 * @since JDK 1.7
 */
@Service
public class MiddleWareServiceImpl implements IMiddleWareService {

    private final static Logger LOGGER = LoggerFactory.getLogger(MiddleWareServiceImpl.class);


//    @Value("${cks-middleware.url:http://172.16.154.46:18081}")
//    private String url;
//
//    @Value("${cks-middleware.interface:/rest/srm/sap/distribute}")
//    private String interfaceAddress;
//
//    @Value("${cks-middleware.defaultValue:0000000000}")
//    private String defaultValue;
//
//    @Value("${cks-middleware.secret:0000000000}")
//    private String secret;
//
//    @Value("${cks-middleware.access:0000000000}")
//    private String access;
//
//    @Value("${cks-middleware.oa-interface:/rest/srm/oa/distribute}")
//    private String oaAddress;
//
//    @Value("${cks-middleware.oa-approval-interface:/rest/srm/oa/getWorkflowRequest}")
//    private String oaFlowAddress;
//
//    @Value("${cks-middleware.get-oa-info:/rest/srm/distribute}")
//    private String oaGetInfoAddress;
//
//    @Value("${cks-middleware.get-oa-flow-page:/rest/ecology/getUrl/viewWF}")
//    private String oaFlowPageGetAddress;
//
//    @Value("${cks-middleware.oa-invoince-interface:/rest/transmit/invoices/query}")
//    private String oaInvoinceAddress;
//
//    @Value("${cks-middleware.oa-invoince-add-interface:/rest/transmit/invoices/update}")
//    private String oaAddInvoinceAddress;
//
//    @Value("${cks-middleware.oa-invoince-login-interface:/web-api/invoices/login-sso}")
//    private String oaInvoinceLogin;

    @Value("${cks-middleware.XY.url:http://eis-test5.ehsy.com}")
    private String XYUrl;

    @Value("${cks-middleware.XY.token-interface:/punchout/api/accessToken}")
    private String XYTokenAddress;

    @Value("${cks-middleware.XY.product-interface:/punchout/api/punchoutSearch}")
    private String  XYProductAddress;

    @Value("${cks-middleware.XY.submit-order-interface:/punchout/api/submitOrder}")
    private String  XYSubmitOrder;

    @Value("${cks-middleware.XY.confirm-order-interface:/punchout/api/confirmOrder}")
    private String  XYConfirmOrder;

    @Value("${sys.zkh.url}")
    private String ZKHUrl;

    @Value("${sys.zkh.prefix}")
    private String ZKHPrefix;

    @Value("${cks-middleware.ZKH.token-interface:/oauth2/token}")
    private String ZKHTokenAddress;

    @Value("${cks-middleware.ZKH.product-interface:/searchAllSku}")
    private String  ZKHProductAddress;
    @Value("${cks-middleware.ZKH.detail.product-interface:/getDetail}")
    private String  ZKHProductDetailAddress;
    @Value("${cks-middleware.ZKH.applyProduct.product-interface:/applyProduct}")
    private String  ZKHProductApplyProductAddress;

    @Value("${cks-middleware.ZKH.submit-order-interface:/submitOrder}")
    private String  ZKHSubmitOrder;

    @Value("${cks-middleware.ZKH.service-order-interface:/serviceOrder}")
    private String  ZKHServiceOrder;

    @Value("${cks-middleware.ZKH.service-order-cancel/interface:/serviceOrder/cancel}")
    private String  ZKHServiceOrderCancel;

    @Value("${cks-middleware.ZKH.confirm-order-interface:/confirmOrder}")
    private String  ZKHConfirmOrder;
    @Value("${cks-middleware.ZKH.package-list-interface:/package/list}")
    private String  ZKHPackageList;
    @Value("${cks-middleware.ZKH.orderTrack-interface:/orderTrack}")
    private String  ZKHOrderTrack;
    @Value("${cks-middleware.ZKH.cancel-interface:/cancel}")
    private String ZKHCancel;
    @Value("${cks-middleware.ZKH.get-interface:/get}")
    private String ZKHGet;
    @Value("${cks-middleware.ZKH.delete-interface:/delete}")
    private String ZKHDelete;
    @Value("${cks-middleware.ZKH.product-url:https://esp-uat.zkh360.com/punchout/special/login}")
    private String  ZKHProductUrl;


    /**
     * 同一个接口，必须要调用两次，第一次是获取requesid和token，
     * 第二次调用时，需要将requesid传入header，token则进行签名操作后传入header
     * @param queryJsonString 查询json
     * @return
     */
//    @Override
//    public String requestMiddleWare(String queryJsonString) throws Exception{
//        LOGGER.info("request middle ware for sap data start....");
//        String url = this.url + this.interfaceAddress;
//        LOGGER.info("sap token url:"+url);
//        //发送options请求，获取token
//        String tokenResult = Request.Options(url)
//                .addHeader("X-CKS-ACCESS",this.defaultValue).execute().returnContent().asString();
//        String queryResult = "";
//        LOGGER.info("sap token result:"+tokenResult);
//        if(!Strings.isNullOrEmpty(tokenResult)){
//            MiddleWareToken middleWareToken = JSON.parseObject(tokenResult,MiddleWareToken.class);
//            Integer code = middleWareToken.getCode();
//            String message = middleWareToken.getMessage();
//            if(0 != code){
//                throw new Exception("获取sap token失败："+message);
//            }
//            MiddleWareData middleWareData = middleWareToken.getData();
//            String requestId = middleWareData.getRequestId();
//            String token = middleWareData.getToken();
//            String content = this.interfaceAddress+this.access+token;
//            String signature = encryptContent(this.secret,content);
////            queryResult = Request.Post(url)
////                    .addHeader("X-CKS-REQUEST-ID",requestId)
////                    .addHeader("X-CKS-SIGNATURE",signature)
////                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
////                    .execute().returnContent().asString();
//            HttpResponse response = Request.Post(url).connectTimeout(30000)
//                    .addHeader("X-CKS-REQUEST-ID", requestId)
//                    .addHeader("X-CKS-SIGNATURE", signature)
//                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
//                    .execute().returnResponse();
//            if(null != response) {
//                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//            }
//        }
//
//        return queryResult;
//    }

    /**
     * 同一个接口，必须要调用两次，第一次是获取token，
     * 第二次调用时，传token和其他查询参数进行查询
     * @param params 查询json
     * @return
     */
    @Override
    public OnlineShoppingZkhResponse requestMiddleWareToken(String tokenJsonString, JSONObject params) throws Exception{
        LOGGER.info("request middle ware for sap data start....");

        OnlineShoppingZkhResponse shoppingResponse = new OnlineShoppingZkhResponse();
        String queryResult = "";
        if("XY".equals(params.get("source").toString())){
         /*   params.put("token",tokenJsonString);
            String productUrl = this.XYUrl + this.XYProductAddress;
            LOGGER.info("XY sap product url:"+productUrl);

            String paramJson = JSON.toJSONString(params);
            LOGGER.info("获取在线商城商品XY信息接口请求参数为: {}", paramJson);

            HttpResponse response = Request.Post(productUrl).connectTimeout(30000)
                    .bodyString(paramJson, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();

            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);

                shoppingResponse = JSONObject.parseObject(queryResult, OnlineShoppingResponse.class);
                shoppingResponse.setAccessToken(tokenJsonString);
            }*/
        }else if("ZKH".equals(params.get("source").toString())){
            JSONObject cxparams = new JSONObject();
            cxparams.put("sku", params.get("product_name"));
            cxparams.put("current", params.get("pageNum"));
            cxparams.put("size", params.get("pageSize"));
            cxparams.put("token",tokenJsonString);
            String productUrl = this.ZKHUrl + this.ZKHPrefix + this.ZKHProductAddress;
            LOGGER.info("ZKH sap product url:"+productUrl);

            String paramJson = JSON.toJSONString(cxparams);
            LOGGER.info("获取在线商城商品ZKH信息接口请求参数为: {}", paramJson);

            HttpResponse response = Request.Post(productUrl).connectTimeout(30000)
                    .bodyString(paramJson, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();

            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                shoppingResponse = JSONObject.parseObject(queryResult, OnlineShoppingZkhResponse.class);
                if(Objects.isNull(shoppingResponse)){
                    shoppingResponse.setCode("-1");
                    shoppingResponse.setMessage("接口调用成功, 但未获取到数据");
                }else{
                    shoppingResponse.setCode("1");
                    shoppingResponse.setMessage(shoppingResponse.getResulteMessage());
                    shoppingResponse.setAccessToken(tokenJsonString);

                }
            }
        }

        return shoppingResponse;
    }


    /**
     * 同一个接口，必须要调用两次，第一次是获取token，
     * 第二次调用时，传token和其他查询参数进行查询
     * @param params 查询json
     * @return
     */
    @Override
    public ShoppingDetailReponse findShoppingDetail(String tokenJsonString, JSONObject params) throws Exception{
        LOGGER.info("request middle ware for shopping detail start....");

        ShoppingDetailReponse shoppingResponse = new ShoppingDetailReponse();
        String queryResult = "";
            params.put("token",tokenJsonString);
            String productUrl = this.ZKHUrl + this.ZKHPrefix + this.ZKHProductDetailAddress;
            LOGGER.info("ZKH sap product url:"+productUrl);

            String paramJson = JSON.toJSONString(params);
            LOGGER.info("获取在线商城商品ZKH明细信息接口请求参数为: {}", paramJson);

            HttpResponse response = Request.Post(productUrl).connectTimeout(30000)
                    .bodyString(paramJson, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();

            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                shoppingResponse = JSONObject.parseObject(queryResult, ShoppingDetailReponse.class);
                if(Objects.isNull(shoppingResponse)){
                    shoppingResponse.setResultCode("-1");
                    shoppingResponse.setResulteMessage("接口调用成功, 但未获取到数据");
                }else{
                    shoppingResponse.setResultCode("1");
                    shoppingResponse.setResulteMessage(shoppingResponse.getResulteMessage());

                }
            }


        return shoppingResponse;
    }

    @Override
    public ApplyProductResponse applyProduct(String tokenJsonString, JSONObject params) throws Exception{
        LOGGER.info("request middle ware for applyProduct start....");

        ApplyProductResponse applyProductResponse = new ApplyProductResponse();
        String queryResult = "";
        params.put("token",tokenJsonString);
        String productUrl = this.ZKHUrl + this.ZKHPrefix + this.ZKHProductApplyProductAddress;
        LOGGER.info("ZKH sap product url:"+productUrl);

        String paramJson = JSON.toJSONString(params);
        LOGGER.info("获取在线商城商品上架接口请求参数为: {}", paramJson);

        HttpResponse response = Request.Post(productUrl).connectTimeout(30000)
                .bodyString(paramJson, ContentType.APPLICATION_JSON)
                .execute().returnResponse();

        if(null != response) {
            queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            applyProductResponse = JSONObject.parseObject(queryResult, ApplyProductResponse.class);
            if(Objects.isNull(applyProductResponse)){
                applyProductResponse.setResultCode("-1");
                applyProductResponse.setResultMessage("接口调用成功, 但未获取到数据");
            }else{
                applyProductResponse.setResultCode(applyProductResponse.getResultCode());
                applyProductResponse.setResultMessage(applyProductResponse.getResultMessage());

            }
        }


        return applyProductResponse;
    }
    /**
     * 推送商城时单独获取token
     * @return
     */
    @Override
    public String requestTokenByPush(String tokenJsonString, String params) throws Exception{
        LOGGER.info("request middle ware for sap data start....");

        String token = "";
        OnlineShoppingResponse shoppingResponse = new OnlineShoppingResponse();
        if("XY".equals(params)){
            String url = this.XYUrl + this.XYTokenAddress;
            LOGGER.info("XY sap token url:"+url);
            String tokenResult = "";
            HttpResponse responseToken = Request.Post(url)
                    .bodyString(tokenJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != responseToken) {
                tokenResult = EntityUtils.toString(responseToken.getEntity(), Consts.UTF_8);
            }

            LOGGER.info("XY sap token result:"+tokenResult);
            if(!Strings.isNullOrEmpty(tokenResult)){
                ShoppingToken shoppingToken = JSON.parseObject(tokenResult, ShoppingToken.class);
                String success = shoppingToken.getSuccess();
                String message = shoppingToken.getResultMessage();
                if("false".equals(success)){
                    throw new Exception("获取token失败："+message);
                }
                ShoppingData middleWareData = shoppingToken.getResult();
                token = middleWareData.getAccessToken();
            }
        }else if("ZKH".equals(params)){
            String url = this.ZKHUrl + this.ZKHTokenAddress;
            LOGGER.info("ZKH sap token url:"+url);
            String tokenResult = "";
            try {
                HttpResponse responseToken = Request.Post(url)
                        .bodyString(tokenJsonString, ContentType.APPLICATION_JSON)
                        .execute().returnResponse();
                if (null != responseToken) {
                    tokenResult = EntityUtils.toString(responseToken.getEntity(), Consts.UTF_8);
                }
            }catch (Exception e){
                e.printStackTrace();
            }


            String queryResult = "";
            LOGGER.info("ZKH sap token result:"+tokenResult);
            if(!Strings.isNullOrEmpty(tokenResult)){
                ShoppingToken shoppingToken = JSON.parseObject(tokenResult, ShoppingToken.class);
                String success = shoppingToken.getSuccess();
                String message = shoppingToken.getResultMessage();
                if("false".equals(success)){
                    throw new Exception("获取token失败："+message);
                }
                ShoppingData middleWareData = shoppingToken.getResult();
                token = middleWareData.getAccessToken();
            }
        }

        return token;
    }
//
//    /**
//     * 同一个接口，必须要调用两次，第一次是获取requesid和token，
//     * 第二次调用时，需要将requesid传入header，token则进行签名操作后传入header
//     * @param queryJsonString 查询json
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public String requestMiddleWareForOA(String queryJsonString) throws Exception {
//        LOGGER.info("request middle ware for oa data start....");
//        String url = this.url + this.oaAddress;
//        LOGGER.info("oa token url:"+url);
//        //发送options请求，获取token
//        String tokenResult = Request.Options(url).connectTimeout(30000)
//                .addHeader("X-CKS-ACCESS",this.defaultValue).execute().returnContent().asString();
//        String queryResult = "";
//        LOGGER.info("oa token result:"+tokenResult);
//        if(!Strings.isNullOrEmpty(tokenResult)){
//            MiddleWareToken middleWareToken = JSON.parseObject(tokenResult,MiddleWareToken.class);
//            Integer code = middleWareToken.getCode();
//            String message = middleWareToken.getMessage();
//            if(0 != code){
//                throw new Exception("获取 oa token失败："+message);
//            }
//            MiddleWareData middleWareData = middleWareToken.getData();
//            String requestId = middleWareData.getRequestId();
//            String token = middleWareData.getToken();
//            String content = this.oaAddress+this.access+token;
//            String signature = encryptContent(this.secret,content);
//
////            queryResult = Request.Post(url).connectTimeout(30000)
////                    .addHeader("X-CKS-REQUEST-ID",requestId)
////                    .addHeader("X-CKS-SIGNATURE",signature)
////                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
////                    .execute().returnContent().asString();
//            HttpResponse response = Request.Post(url).connectTimeout(30000)
//                    .addHeader("X-CKS-REQUEST-ID", requestId)
//                    .addHeader("X-CKS-SIGNATURE", signature)
//                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
//                    .execute().returnResponse();
//            if(null != response) {
//                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//            }
//        }
//        return queryResult;
//    }
//
//    @Override
//    public String requestMiddleWareForOAFlow(String queryJsonString) throws Exception {
//        LOGGER.info("request middle ware for oa flow data start....");
//        String url = this.url + this.oaFlowAddress;
//        LOGGER.info("oa token url:"+url);
//        //发送options请求，获取token
//        String tokenResult = Request.Options(url)
//                .addHeader("X-CKS-ACCESS",this.defaultValue).execute().returnContent().asString();
//        String queryResult = "";
//        LOGGER.info("oa flow token result:"+tokenResult);
//        if(!Strings.isNullOrEmpty(tokenResult)){
//            MiddleWareToken middleWareToken = JSON.parseObject(tokenResult,MiddleWareToken.class);
//            Integer code = middleWareToken.getCode();
//            String message = middleWareToken.getMessage();
//            if(0 != code){
//                throw new Exception("获取 oa flow token失败："+message);
//            }
//            MiddleWareData middleWareData = middleWareToken.getData();
//            String requestId = middleWareData.getRequestId();
//            String token = middleWareData.getToken();
//            String content = this.oaFlowAddress+this.access+token;
//            String signature = encryptContent(this.secret,content);
////            queryResult = Request.Post(url)
////                    .addHeader("X-CKS-REQUEST-ID",requestId)
////                    .addHeader("X-CKS-SIGNATURE",signature)
////                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
////                    .execute().returnContent().asString();
//
//            HttpResponse response = Request.Post(url).connectTimeout(30000)
//                    .addHeader("X-CKS-REQUEST-ID", requestId)
//                    .addHeader("X-CKS-SIGNATURE", signature)
//                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
//                    .execute().returnResponse();
//            if(null != response) {
//                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//            }
//
//        }
//        return queryResult;
//    }
//
//    /**
//     * 同一个接口，必须要调用两次，第一次是获取requesid和token，
//     * 第二次调用时，需要将requesid传入header，token则进行签名操作后传入header
//     * @param queryJsonString 查询json
//     * @return
//     * @throws Exception
//     */
//    @Override
//    public String requestMiddleWareForGetOAInfo(String queryJsonString) throws Exception {
//        LOGGER.info("request middle ware for oa table info data start....");
//        String url = this.url + this.oaGetInfoAddress;
//        LOGGER.info("oa token url:"+url);
//        //发送options请求，获取token
//        String tokenResult = Request.Options(url).connectTimeout(30000)
//                .addHeader("X-CKS-ACCESS",this.defaultValue).execute().returnContent().asString();
//        String queryResult = "";
//        LOGGER.info("oa token result:"+tokenResult);
//        if(!Strings.isNullOrEmpty(tokenResult)){
//            MiddleWareToken middleWareToken = JSON.parseObject(tokenResult,MiddleWareToken.class);
//            Integer code = middleWareToken.getCode();
//            String message = middleWareToken.getMessage();
//            if(0 != code){
//                throw new Exception("获取 oa token失败："+message);
//            }
//            MiddleWareData middleWareData = middleWareToken.getData();
//            String requestId = middleWareData.getRequestId();
//            String token = middleWareData.getToken();
//            String content = this.oaGetInfoAddress+this.access+token;
//            String signature = encryptContent(this.secret,content);
////            queryResult = Request.Post(url).connectTimeout(30000)
////                    .addHeader("X-CKS-REQUEST-ID",requestId)
////                    .addHeader("X-CKS-SIGNATURE",signature)
////                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
////                    .execute().returnContent().asString();
//            HttpResponse response = Request.Post(url).connectTimeout(30000)
//                    .addHeader("X-CKS-REQUEST-ID", requestId)
//                    .addHeader("X-CKS-SIGNATURE", signature)
//                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
//                    .execute().returnResponse();
//            if(null != response) {
//                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//            }
//        }
//        return queryResult;
//    }
//
//    /**
//     * 请求中间件，访问OA接口，获取OA流程审批页面
//     *
//     * @param queryJsonString 查询json
//     * @return 结果
//     * @throws Exception 异常抛出
//     */
//    @Override
//    public String requestMiddleWareForGetOAFlowPage(String queryJsonString) throws Exception {
//        LOGGER.info("request middle ware for oa flow page url start....");
//        String url = this.url + this.oaFlowPageGetAddress;
//        LOGGER.info("oa token url:"+url);
//
//        // 发送options请求，获取token
//        String tokenResult = Request.Options(url).connectTimeout(30000)
//                .addHeader("X-CKS-ACCESS", this.defaultValue)
//                .execute().returnContent().asString();
//        LOGGER.info("oa token result:"+ tokenResult);
//        if(Strings.isNullOrEmpty(tokenResult)){
//            return "";
//        }
//        MiddleWareToken middleWareToken = JSON.parseObject(tokenResult,MiddleWareToken.class);
//        Integer code = middleWareToken.getCode();
//        String message = middleWareToken.getMessage();
//        if(0 != code){
//            throw new Exception("获取 oa token失败: "+ message);
//        }
//        MiddleWareData middleWareData = middleWareToken.getData();
//        String requestId = middleWareData.getRequestId();
//        String token = middleWareData.getToken();
//        String content = this.oaFlowPageGetAddress + this.access + token;
//        String signature = encryptContent(this.secret, content);
//
////        return Request.Post(url).connectTimeout(30000)
////                .addHeader("X-CKS-REQUEST-ID", requestId)
////                .addHeader("X-CKS-SIGNATURE", signature)
////                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
////                .execute().returnContent().asString();
//
//        HttpResponse response = Request.Post(url).connectTimeout(30000)
//                .addHeader("X-CKS-REQUEST-ID", requestId)
//                .addHeader("X-CKS-SIGNATURE", signature)
//                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
//                .execute().returnResponse();
//        if(null != response) {
//            return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//        }
//        return "";
//    }
//
//
//    @Override
//    public String requestMiddleWareForGetInvoice(String queryJsonString) throws Exception {
//        return doHttp(this.oaInvoinceAddress,queryJsonString);
//    }
//
//    @Override
//    public String requestMiddleWareForAddInvoice(String queryJsonString) throws Exception {
//        return doHttp(this.oaAddInvoinceAddress,queryJsonString);
//    }
//
//    @Override
//    public String requestMiddleWareForLoginInvoice(String queryJsonString) throws Exception {
//        return doHttpNoToken(this.oaInvoinceLogin,queryJsonString);
//    }
//
//    private String doHttpNoToken(String uri, String json) throws Exception {
//        return  Request.Post(this.url + uri)
//                .bodyString(json, ContentType.APPLICATION_JSON)
//                .execute()
//                .returnContent()
//                .asString();
//    }
//
//    public String doHttp(String uri, String json) throws Exception {
//        String url = this.url + uri;
//        LOGGER.info("oa token url:" + url);
//
//        Pair<String, String> tokenResult = getToken(url);
//        String queryResult = "";
//        if (tokenResult == null) {
//            return queryResult;
//        }
//
//        String requestId = tokenResult.getFirst();
//        String token = tokenResult.getSecond();
//        String content = uri + this.access + token;
//        String signature = encryptContent(this.secret, content);
//        queryResult = Request.Post(url).connectTimeout(30000)
//                .addHeader("X-CKS-REQUEST-ID", requestId)
//                .addHeader("X-CKS-SIGNATURE", signature)
//                .bodyString(json, ContentType.APPLICATION_JSON)
//                .execute().handleResponse(
//                        //防止中文乱码
//                        new ResponseHandler<String>() {
//                            @Override
//                            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
//                                return EntityUtils.toString(response.getEntity(), Consts.UTF_8);
//                            }
//                        }
//                );
//
//
//        return queryResult;
//    }
//
//    /**
//     * 发送options请求，获取token
//     * @param url
//     * @return requestId 和 token
//     * @throws Exception
//     */
//    private Pair<String, String> getToken(String url) throws Exception {
//        String tokenResult = Request.Options(url).connectTimeout(30000)
//                .addHeader("X-CKS-ACCESS", this.defaultValue).execute().returnContent().asString();
//        LOGGER.info("oa token result:" + tokenResult);
//
//        if (!Strings.isNullOrEmpty(tokenResult)) {
//            MiddleWareToken middleWareToken = JSON.parseObject(tokenResult, MiddleWareToken.class);
//            Integer code = middleWareToken.getCode();
//            if (0 != code) {
//                throw new Exception("获取 oa token失败：" + middleWareToken.getMessage());
//            }
//            MiddleWareData middleWareData = middleWareToken.getData();
//            if (middleWareData != null) {
//                return Pair.of(middleWareData.getRequestId(), middleWareData.getToken());
//            }
//        }
//
//        return null;
//    }
//
//
//    /**
//     * token 签名
//     *
//     * @param secret 秘钥
//     * @param content 接口地址 + 账号 + token
//     * @return 结果
//     * @throws Exception 异常抛出
//     */
//    private static String encryptContent(String secret, String content) throws Exception {
//        LOGGER.info("token signature,secret:"+secret+",content:"+content);
//        String encode = "utf-8";
//        //2、使用hmac-sha256的方式，以secret作为key对上面的结果进行加密
//        Mac mac = Mac.getInstance("HmacSHA256");
//        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(encode), "HmacSHA256");
//        mac.init(secretKeySpec);
//        byte[] result = mac.doFinal(content.getBytes(encode));
//        //3、使用Base64的方式对上面的结果进行加密
//        result = Base64.getEncoder().encode(result);
//        //4、将结果转换成字符串
//        return new String(result, encode);
//    }
//
//
    /**
     * 推送预定单
     * @param queryJsonString 查询json
     * @param sourceCode 商城来源
     * @return
     */
    @Override
    public String requestMiddleOrder(String queryJsonString, String sourceCode) throws Exception{
        String queryResult = "";
        if("XY".equals(sourceCode)){
         /*   LOGGER.info("request middle order XY for sap data start....");
            String url = this.XYUrl + this.XYSubmitOrder;
            LOGGER.info("sap middle order XY url:"+url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }*/
        }else if("ZKH".equals(sourceCode)){
            LOGGER.info("request middle order ZKH for sap data start....");
            String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHSubmitOrder;
            LOGGER.info("sap middle order ZKH url:"+url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        }
        return queryResult;
    }

    /**
     * 推送确认订单
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleConfirmOrder(String queryJsonString, String sourceCode) throws Exception{
        LOGGER.info("request confirm order for sap data start....");

        String queryResult = "";
        if("XY".equals(sourceCode)) {
        /*    String url = this.XYUrl + this.XYConfirmOrder;
            LOGGER.info("sap confirm order url:" + url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if (null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }*/
        }else if("ZKH".equals(sourceCode)){
            LOGGER.info("request middle order ZKH for sap data start....");
            String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHConfirmOrder;
            LOGGER.info("sap middle order ZKH url:"+url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        }

        return queryResult;
    }

    /**
     * 推送确认订单
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleConfirmOrder1(String token,String queryJsonString, String sourceCode) throws Exception{
        LOGGER.info("request confirm order for sap data start....");

        String queryResult = "";
         if("ZKH".equals(sourceCode)){
            LOGGER.info("request middle order ZKH for sap data start....");
            String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHServiceOrder;
            LOGGER.info("zkh middle order ZKH url:"+url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .addHeader("Authorization","bearer " + token)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        }

        return queryResult;
    }

    /**
     * 推送确认订单
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleConfirmOrder2(String token,String queryJsonString, String sourceCode) throws Exception{
        LOGGER.info("request confirm order for sap data start....");

        String queryResult = "";
        if("ZKH".equals(sourceCode)){
            LOGGER.info("request middle order ZKH for sap data start....");
            String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHServiceOrderCancel;
            LOGGER.info("zkh middle order ZKH url:"+url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .addHeader("Authorization","bearer " + token)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        }

        return queryResult;
    }

    /**
     * 震坤行免密登录获取地址
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleProductUrl(String queryJsonString) throws Exception{
        LOGGER.info("request product url order for sap data start....");

        String queryResult = "";
        String url = this.ZKHProductUrl;
        LOGGER.info("sap product url ZKH :"+url);

        HttpResponse response = Request.Post(url).connectTimeout(30000)
                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                .execute().returnResponse();
        if(null != response) {
            queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        }

        return queryResult;
    }

    /**
     * 根据震坤行订单号，查询所有发货单明细信息
     * 应用场景
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddlePackageList(String queryJsonString) throws Exception{
        LOGGER.info("request package list for sap data start....");

        String queryResult = "";
            LOGGER.info("request package list ZKH for sap data start....");
            String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHPackageList;
            LOGGER.info("sap package list ZKH url:"+url);

            HttpResponse response = Request.Post(url).connectTimeout(30000)
                    .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                    .execute().returnResponse();
            if(null != response) {
                queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }


        return queryResult;
    }

    /**
     * 商城推送消息接口
     * 应用场景
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleGetMessage(String queryJsonString) throws Exception{
        LOGGER.info("request  get message   for sap data start....");

        String queryResult = "";
        LOGGER.info("request get message  ZKH for sap data start....");
        String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHGet;
        LOGGER.info("sap  get message  ZKH url:"+url);

        HttpResponse response = Request.Post(url).connectTimeout(30000)
                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                .execute().returnResponse();
        if(null != response) {
            queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        }


        return queryResult;
    }
    /**
     * 商城删除消息接口
     * 应用场景
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleDelMessage(String queryJsonString) throws Exception{
        LOGGER.info("request delete message for sap data start....");

        String queryResult = "";
        LOGGER.info("request delete message  ZKH for sap data start....");
        String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHDelete;
        LOGGER.info("sap delete message  ZKH url:"+url);

        HttpResponse response = Request.Post(url).connectTimeout(30000)
                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                .execute().returnResponse();
        if(null != response) {
            queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        }


        return queryResult;
    }

    /**
     * 查询发货单物流轨迹信息接口
     * 应用场景
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleOrderTrack(String queryJsonString) throws Exception{
        LOGGER.info("request orderTrack for sap data start....");

        String queryResult = "";
        LOGGER.info("request porderTrack ZKH for sap data start....");
        String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHOrderTrack;
        LOGGER.info("sap orderTrack  ZKH url:"+url);

        HttpResponse response = Request.Post(url).connectTimeout(30000)
                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                .execute().returnResponse();
        if(null != response) {
            queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        }


        return queryResult;
    }

    /**
     * 取消订单接口
     * 应用场景
     * @param queryJsonString 查询json
     * @return
     */
    @Override
    public String requestMiddleDelOrder(String queryJsonString) throws Exception{
        LOGGER.info("request delOrder for sap data start....");

        String queryResult = "";
        LOGGER.info("request DelOrder ZKH for sap data start....");
        String url = this.ZKHUrl + this.ZKHPrefix + this.ZKHCancel;
        LOGGER.info("sap delOrder  ZKH url:"+url);

        HttpResponse response = Request.Post(url).connectTimeout(30000)
                .bodyString(queryJsonString, ContentType.APPLICATION_JSON)
                .execute().returnResponse();
        if(null != response) {
            queryResult = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
        }

        return queryResult;
    }
}
