package cn.pluss.platform.klk.service;

import cn.hutool.core.util.ObjectUtil;
import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.dto.MerChantOrderDTO;
import cn.pluss.platform.entity.MerchantBackLkl;
import cn.pluss.platform.entity.MerchantBaseInfo;
import cn.pluss.platform.entity.MerchantChannelStatus;
import cn.pluss.platform.entity.MerchantOrder;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.klk.LakalaConfig;
import cn.pluss.platform.mapper.MerchantBackLklMapper;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.SnowFlakeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.io.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class LklPayService {

    private static Integer index = 0;


    /**
     * 字符集固定 utf-8
     */


    /**
     * API schema ,固定 LKLAPI-SHA256withRSA
     */
    public final static String SCHEMA = "LKLAPI-SHA256withRSA";

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final SecureRandom RANDOM = new SecureRandom();


    @Autowired
    LakalaConfig lakalaConfig;

    @Autowired
    MerchantBackLklMapper merchantBackLklMapper;



    public boolean activityCloudDevice(MerchantBaseInfo merchantBaseInfo,String sno){
        QueryWrapper<MerchantBackLkl> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("merchant_code",merchantBaseInfo.getMerchantCode());
        queryWrapper.eq("channel","5");
        MerchantBackLkl backLkl= merchantBackLklMapper.selectOne(queryWrapper);
        MsgException.checkNull(backLkl,"缺失的进件信息"+merchantBaseInfo.getMerchantCode());
        String req_time= DateUtils.getSdfTimes();

        String body="{\n" +
                "    \"ver\":\"1.0.0\",\n" +
                "    \"timestamp\":\""+req_time+"\",\n" +
                "    \"reqId\":\""+req_time+"\",\n" +
                "    \"reqData\":{\n" +
                "         \"merId\":\""+backLkl.getExternalCustomerNo()+"\",\n" +
                "         \"termId\":\""+backLkl.getTermNos()+"\",\n" +
                "         \"sn\":\""+sno+"\",\n" +
                "         \"businessType\":\"1\",\n" +
                "         \"shopName\":\""+merchantBaseInfo.getAlias()+"\",\n" +
                "         \"source\":\"LOAP\",\n" +
                "         \"merOrgNo\":\"966805\"\n" +
                "    }\n" +
                "}";

        String response = req(body, "api/v2/iot/cloud/device/activate");
        if (ObjectUtil.isNotEmpty(response)) {
            JSONObject object = JSONObject.parseObject(response);
            if (object.containsKey("retCode") && "000000".equals(object.getString("retCode"))) {
                return true;
            } else {
                return false;
            }
        }
        return false;

    }

    public boolean deactivate(MerchantBaseInfo merchantBaseInfo,String sNo){
        QueryWrapper<MerchantBackLkl> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("merchant_code",merchantBaseInfo.getMerchantCode());
        queryWrapper.eq("channel","5");
        MerchantBackLkl backLkl= merchantBackLklMapper.selectOne(queryWrapper);
        MsgException.checkNull(backLkl,"缺失的进件信息"+merchantBaseInfo.getMerchantCode());
        String req_time= DateUtils.getSdfTimes();

        String body="{\n" +
                "    \"ver\":\"1.0.0\",\n" +
                "    \"timestamp\":\""+req_time+"\",\n" +
                "    \"reqId\":\""+req_time+"\",\n" +
                "    \"reqData\":{\n" +
                "        \"merId\":\""+backLkl.getExternalCustomerNo()+"\",\n" +
                "        \"termId\":\""+backLkl.getTermNos()+"\",\n" +
                "        \"sn\":\""+sNo+"\",\n" +
                "        \"source\":\"KSAAS\"\n" +
                "    }\n" +
                "}";


        JSONObject result = new JSONObject();
        String response = req(body, "api/v2/iot/cloud/device/deactivate");
        if (ObjectUtil.isNotEmpty(response)) {
            JSONObject object = JSONObject.parseObject(response);
            if (object.containsKey("retCode") && "000000".equals(object.getString("retCode"))) {

                return true;
            } else {

                return false;
            }
        }
        return false;

    }


    public JSONObject tradePay(MerchantOrder order, MerchantChannelStatus channel, MerchantBaseInfo merchant){


        return new JSONObject();

    }




    public String querySubMerInfo(String orgCode,String merInnerNo,String merCupNo){
        String req_time= DateUtils.getSdfTimes();
        String body=null;
        if(ObjectUtil.isNotEmpty(orgCode)&&ObjectUtil.isNotEmpty(merInnerNo)){
            body="{\n" +
                    "\t\"reqData\": {\n" +
                    "\t\t\"version\": \"1.0\",\n" +
                    "\t\t\"orderNo\": \""+req_time+"\",\n" +
                    "\t\t\"orgCode\": \""+orgCode+"\",\n" +
                    "\t\t\"merInnerNo\": \""+merInnerNo+"\"\n" +
                    "\t}\n" +
                    "}";
        }else if(ObjectUtil.isNotEmpty(orgCode)&&ObjectUtil.isNotEmpty(merCupNo)){
            body="{\n" +
                    "\t\"reqData\": {\n" +
                    "\t\t\"version\": \"1.0\",\n" +
                    "\t\t\"orderNo\": \""+req_time+"\",\n" +
                    "\t\t\"orgCode\": \""+orgCode+"\",\n" +
                    "\t\t\"merCupNo\": \""+merCupNo+"\"\n" +
                    "\t}\n" +
                    "}";
        }else {
            body="{\n" +
                    "\t\"reqData\": {\n" +
                    "\t\t\"version\": \"1.0\",\n" +
                    "\t\t\"orderNo\": \""+req_time+"\",\n" +
                    "\t\t\"orgCode\": \""+orgCode+"\"\n" +
                    "\t}\n" +
                    "}";
        }



        String resp= req(body,"api/v2/mms/openApi/querySubMerInfo");
        log.info("resp:{}",resp);
        return resp;

    }








    public Map<String,Object> tradePay(String amount,MerchantChannelStatus channel,String authCode,String ip,String paymentApp){


        QueryWrapper<MerchantBackLkl> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("merchant_code",channel.getMerchantCode());
        queryWrapper.eq("merchant_id",channel.getMerchantId());
        queryWrapper.eq("channel","5");
        queryWrapper.eq("user_no","22241007");

        MerchantBackLkl merchantBackLkl=merchantBackLklMapper.selectOne(queryWrapper);
        MsgException.checkNull(merchantBackLkl,"进件信息不存在");


        String req_time= DateUtils.getSdfTimes();


        Long order_amt = new BigDecimal(amount).multiply(new BigDecimal(100)).longValue();
        String out_trade_no= "LKL".concat(SnowFlakeUtil.nextId().toString());


        String body="{\n" +
                "\t\"req_data\": {\n" +
                "\t\t\"out_trade_no\": \""+out_trade_no+"\",\n" +
                "\t\t\"merchant_no\": \""+lakalaConfig.getMerchantNo()+"\",\n" +
                "\t\t\"term_no\": \""+lakalaConfig.getTermNo()+"\",\n" +
                "\t\t\"auth_code\": \""+authCode+"\",\n" +
                "\t\t\"total_amount\": \""+order_amt+"\",\n" +
                "\t\t\"notify_url\": \""+lakalaConfig.getCallBackUrl()+"\",\n" +
                "\t\t\"location_info\": \"{\\\"request_ip\\\":\\\""+ip+"\\\",\\\"base_station\\\":\\\"陕西省西安市未央区\\\",\\\"location\\\":\\\"34.34727,108.94647\\\"}\"\n" +
                "\t},\n" +
                "\t\"version\": \"3.0\",\n" +
                "\t\"req_time\": \""+req_time+"\"\n" +
                "}";


        String response=req(body,"api/v3/labs/trans/micropay");
        if(ObjectUtil.isNotEmpty(response)){
            JSONObject object= JSON.parseObject(response);
            if(object.containsKey("code")&&"BBS10000".equals(object.get("code"))){
                Map<String,Object> result = new HashMap<>(2);
                result.put("data", object.get("resp_data"));
                result.put("code", "1");
                result.put("msg", "获取成功");
                return result;

            }else {
                JSONObject reqData = new JSONObject(2);
                reqData.put("userAuthCode", authCode);
                reqData.put("paymentApp", paymentApp);
                reqData.put("code", ResultCode.FAIL.code());

                reqData.put("msg",object.get("msg"));

                return reqData;
            }
        }
        JSONObject reqData = new JSONObject(2);
        reqData.put("code", ResultCode.FAIL.code());
        reqData.put("msg","失败");
        return reqData;
    }


    public String req(String body,String mothod) {
        String encode = encode("client_id:client_secret".getBytes());
        System.out.println("base64:" + encode);

        try {

            String authorization = getAuthorization(body, lakalaConfig.getAppid(), lakalaConfig.getMchSerialNo(), lakalaConfig.getPrivateKeyPath());
            HttpResponse lakalaResponse = post(lakalaConfig.getApiUrl() + mothod, body, authorization, "utf-8");
            if (lakalaResponse.getStatusLine().getStatusCode() != 200) {
                log.error("请求失败,statusCode:{},message:{}", lakalaResponse.getStatusLine(), IOUtils.toString(lakalaResponse.getEntity().getContent(), "utf-8"));
                MsgException.throwException(IOUtils.toString(lakalaResponse.getEntity().getContent(), "utf-8"));
            }

            String appid = getHeadValue(lakalaResponse, "Lklapi-Appid");
            String lklapiSerial = getHeadValue(lakalaResponse, "Lklapi-Serial");
            String timestamp = getHeadValue(lakalaResponse, "Lklapi-Timestamp");
            String nonce = getHeadValue(lakalaResponse, "Lklapi-Nonce");
            String signature = getHeadValue(lakalaResponse, "Lklapi-Signature");
            String responseStr = IOUtils.toString(lakalaResponse.getEntity().getContent(), "utf-8");
            log.info("返回的信息为 responseStr:{}", responseStr);

            String source = appid + "\n" + lklapiSerial + "\n" + timestamp + "\n" + nonce + "\n" + responseStr + "\n";
            log.info("请求的数据为:{}", source);
            X509Certificate lklCertificate = loadCertificate(new FileInputStream(new File(lakalaConfig.getCertificatePath())));
            boolean verify = verify(lklCertificate, source.getBytes("utf-8"), signature);

            if (verify) {
                log.info("验签通过");
                return responseStr;
            } else {
                return null;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public static String encode(byte[] content) {
        return new sun.misc.BASE64Encoder().encode(content);
    }


    public static boolean isNumeric(String str) {
        //?:0或1个, *:0或多个, +:1或多个
        Boolean strResult = str.matches("-?[0-9]+.?[0-9]*");
        if (strResult == true) {
            return true;
        } else {
            return false;
        }
    }

    private boolean isNumber(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    public static HttpResponse post(String url, String message, String authorization, String ENCODING) throws Exception {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] xcs, String str) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] xcs, String str) {
            }
        };
        HttpClient http = new DefaultHttpClient();
        ClientConnectionManager ccm = http.getConnectionManager();
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = ccm.getSchemeRegistry();
        registry.register(new Scheme("https", ssf, 443));
        HttpPost post = new HttpPost(url);
        StringEntity myEntity = new StringEntity(message, ENCODING);
        post.setEntity(myEntity);
        post.setHeader("Authorization", SCHEMA + " " + authorization);
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Type", "application/json");
        return http.execute(post);
    }

    private String getNowDate() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        return simpleDateFormat.format(date);
    }

    private String getRandom() {
        String rand = "";
        for (int i = 0; i < 8; i++) {
            rand = rand + (int) (Math.random() * 10);
        }
        return rand;

    }

    public String createOrderCode() {
        String OrderCode = getNowDate() + getRandom();
        return OrderCode;
    }


    protected static long generateTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    protected  static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    public static final String getAuthorization(String body, String appid, String mchSerialNo, String merchantPrivateKeyPath) throws IOException {
        String nonceStr = generateNonceStr();
        long timestamp = generateTimestamp();

        String message = appid + "\n" + mchSerialNo + "\n" + timestamp + "\n" + nonceStr + "\n" + body + "\n";

        System.out.println("getToken message :  " + message);

        PrivateKey merchantPrivateKey = loadPrivateKey(new FileInputStream(new File(merchantPrivateKeyPath)));

        String signature = sign(message.getBytes("utf-8"), merchantPrivateKey);

        String authorization = "appid=\"" + appid + "\"," + "serial_no=\"" + mchSerialNo + "\"," + "timestamp=\""
                + timestamp + "\"," + "nonce_str=\"" + nonceStr + "\"," + "signature=\"" + signature + "\"";
        System.out.println("authorization message :" + authorization);

        return authorization;
    }

    public static String sign(byte[] message, PrivateKey privateKey) {
        try {
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(privateKey);
            sign.update(message);
            return new String(Base64.encodeBase64(sign.sign()));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持SHA256withRSA", e);
        } catch (SignatureException e) {
            throw new RuntimeException("签名计算失败", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效的私钥", e);
        }
    }

    private static String getHeadValue(HttpResponse response, String key) {
        return (response.containsHeader(key)) ? response.getFirstHeader(key).getValue() : "";
    }

    private static boolean verify(X509Certificate certificate, byte[] message, String signature) {
        try {
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initVerify(certificate);
            sign.update(message);
            byte[] signatureB = Base64.decodeBase64(signature);
            return sign.verify(signatureB);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持SHA256withRSA", e);
        } catch (SignatureException e) {
            throw new RuntimeException("签名验证过程发生了错误", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效的证书", e);
        }
    }

    public static PrivateKey loadPrivateKey(InputStream inputStream) {
        try {
            ByteArrayOutputStream array = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                array.write(buffer, 0, length);
            }

            String privateKey = array.toString("utf-8").replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "").replaceAll("\\s+", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        } catch (IOException e) {
            throw new RuntimeException("无效的密钥");
        }
    }

    public static X509Certificate loadCertificate(InputStream inputStream) {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);

            cert.checkValidity();
            return cert;
        } catch (CertificateExpiredException e) {
            throw new RuntimeException("证书已过期", e);
        } catch (CertificateNotYetValidException e) {
            throw new RuntimeException("证书尚未生效", e);
        } catch (CertificateException e) {
            throw new RuntimeException("无效的证书", e);
        }
    }


    protected final String getBody(HttpServletRequest request) throws Exception {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8);
            StringBuffer bf = new StringBuffer();
            int len;
            char[] chs = new char[1024];
            while ((len = in.read(chs)) != -1) {
                bf.append(new String(chs, 0, len));
            }
            return bf.toString();
        } catch (Exception e) {
            log.error("请求头部取数据异常：{}", e);
            throw new RuntimeException("999999", e.getCause());
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (Exception e) {
                    log.error("流关闭异常:{}", e);
                }
            }
        }
    }


    public static void main(String[] args)throws  Exception{
        String appId="OP00000657",
                mchSerialNo="01887665511e",
                privateKeyPath="E:\\project\\chaozhanggui\\v1.0.1\\chaozhanggui\\pluss-common-bundle\\src\\main\\resources\\lakalaConf\\api_private_key.pem",
                apiUrl="https://s2.lakala.com/",
                certificatePath="E:\\project\\chaozhanggui\\v1.0.1\\chaozhanggui\\pluss-common-bundle\\src\\main\\resources\\lakalaConf\\lkl-apigw-v1.cer",
                termNo="A0073841",
                merchant_no="8221210594300JY",
                mothod="api/v3/labs/relation/refund";



        String req_time= DateUtils.getSdfTimes();

//        String body="{\n" +
//                " \"req_time\":\""+req_time+"\",\n" +
//                " \"version\":\"3.0\",\n" +
//                " \"out_org_code\":\""+appId+"\",\n" +
//                " \"req_data\":{\n" +
//                "  \"merchant_no\":\""+merchant_no+"\",\n" +
//                "  \"term_no\":\""+termNo+"\",\n" +
//                "  \"out_trade_no\":\""+"lkl_".concat(req_time)+"\",\n" +
//                "  \"refund_amount\":\"1\",\n" +
//                "  \"refund_reason\":\"test测试退款\",\n" +
//                "  \"origin_out_trade_no\":\"20230608094619\",\n" +
//                "  \"location_info\":{\n" +
//                "   \"request_ip\":\"10.176.1.192\",\n" +
//                "   \"location\":\"+37.123456789,-121.123456789\"\n" +
//                "  }\n" +
//                " }\n" +
//                "}\n" +
//                "\n";

        //主扫
//        String body="{\n" +
//                "\t\"out_org_code\": \""+appId+"\",\n" +
//                "\t\"req_data\": {\n" +
//                "\t\t\"account_type\": \"ALIPAY\",\n" +
//                "\t\t\"location_info\": {\n" +
//                "\t\t\t\"request_ip\": \"192.168.3.1\"\n" +
//                "\t\t},\n" +
//                "\t\t\"merchant_no\": \""+merchant_no+"\",\n" +
//                "\t\t\"notify_url\": \"http://127.0.0.1:8080/\",\n" +
//                "\t\t\"out_trade_no\": \""+req_time+"\",\n" +
//                "\t\t\"term_no\": \""+termNo+"\",\n" +
//                "\t\t\"total_amount\": \"1\",\n" +
//                "\t\t\"trans_type\": \"41\"\n" +
//                "\t},\n" +
//                "\t\"req_time\": \""+req_time+"\",\n" +
//                "\t\"version\": \"3.0\"\n" +
//                "}";
//        mothod="api/v3/labs/trans/preorder";


        //扫码交易查询
//        String body="{\n" +
//                "\"req_time\":\""+req_time+"\",\n" +
//                "\"version\":\"3.0\",\n" +
//                "\"out_org_code\":\""+appId+"\",\n" +
//                "\"req_data\":{\n" +
//                "\"merchant_no\":\""+merchant_no+"\",\n" +
//                "\"term_no\":\""+termNo+"\",\n" +
//                "\"out_trade_no\":\"20230608094619\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v3/labs/query/tradequery";

        //退款查询
//        String body="{\n" +
//                " \"req_time\":\""+req_time+"\",\n" +
//                " \"version\":\"3.0\",\n" +
//                " \"out_org_code\":\""+appId+"\",\n" +
//                " \"req_data\":{\n" +
//                "  \"merchant_no\":\""+merchant_no+"\",\n" +
//                "  \"term_no\":\""+termNo+"\",\n" +
//                "  \"out_refund_order_no\":\"lkl_20230608094942\"\n" +
//                " }\n" +
//                "}\n" +
//                "\n";
//        mothod="api/v3/labs/query/idmrefundquery";

        //开通主动结算业务
//        String body="{\n" +
//                "\"reqData\":{\n" +
//                "    \"version\":\"1.0\",\n" +
//                "\"orderNo\":\""+req_time+"\",\n" +
//                "\"orgCode\":\"1\",\n" +
//                "\"merCupNo\":\""+merchant_no+"\"\n" +
//                "},\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"timestamp\":\""+System.currentTimeMillis()+"\",\n" +
//                "\"reqId\":\""+req_time+"\"\n" +
//                "}\n";
//        mothod="api/v2/mms/openApi/activeSettle/apply";

        //账户余额查询
//        String body="{\n" +
//                "\"timestamp\":"+System.currentTimeMillis()+",\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"reqId\":\""+req_time+"\",\n" +
//                "\"reqData\":{\n" +
//                "\"orgNo\":\"1\",\n" +
//                "\"merchantNo\":\""+merchant_no+"\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v2/laep/industry/ewalletBalanceQuery";

        //提现
//        String body="{\n" +
//                "\"timestamp\":\""+System.currentTimeMillis()+"\",\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"reqId\":\""+req_time+"\",\n" +
//                "\"reqData\":{\n" +
//                "\"orgNo\":\"1\",\n" +
//                "\"merchantNo\":\""+merchant_no+"\",\n" +
//                "\"drawAmt\":\"1.1\",\n" +
//                "\"drawMode\":\"D0\",\n" +
//                "\"notifyUrl\":\"test\",\n" +
//                "\"merOrderNo\":\""+req_time+"\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v2/laep/industry/ewalletWithdraw";

//         提现查询
//        String body="{\n" +
//                "\"timestamp\":"+System.currentTimeMillis()+",\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"reqId\":\""+req_time+"\",\n" +
//                "\"reqData\":{\n" +
//                "\"orgNo\":\"1\",\n" +
//                "\"merchantNo\":\""+merchant_no+"\",\n" +
//                "\"drawJnl\":\"230608102913202588627814\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v2/laep/industry/ewalletWithdrawQuery";

        //账管家提现模式设置
//        String body="{\n" +
//                "\"timestamp\":"+System.currentTimeMillis()+",\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"reqId\":\""+req_time+"\",\n" +
//                "\"reqData\":{\n" +
//                "\"bmcpNo\":\"1\",\n" +
//                "\"mercId\":\""+merchant_no+"\",\n" +
//                "\"settleType\":\"01\",\n" +
//                "\"settleTime\":\"06\",\n" +
//                "        \"notifyUrl\":\"https://127.0.0.1/notify\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v2/laep/industry/ewallet/settleProfile";

        //模式设置查询
//        String body="{\n" +
//                "\"timestamp\":"+System.currentTimeMillis()+",\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"reqId\":\""+req_time+"\",\n" +
//                "\"reqData\":{\n" +
//                "\"bmcpNo\":\"1\",\n" +
//                "\"mercId\":\""+merchant_no+"\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v2/laep/industry/ewallet/settleQuery";

//        String body="{\n" +
//                "\"ver\":\"1.0.0\",\n" +
//                "\"timestamp\":\""+System.currentTimeMillis()+"\",\n" +
//                "\"reqId\":\""+req_time+"\",\n" +
//                "\"reqData\":{\n" +
//                "\"mercId\":\""+merchant_no+"\",\n" +
//                "\"termNo\":\""+termNo+"\",\n" +
//                "\"authCode\":\"134459859251822980\",\n" +
//                "\"tradeCode\":\"010304\"\n" +
//                "}\n" +
//                "}\n";
//        mothod="api/v2/saas/query/wx_openid_query";

//
        String body="{\n" +
                "    \"ver\":\"1.0.0\",\n" +
                "    \"timestamp\":\""+req_time+"\",\n" +
                "    \"reqId\":\""+req_time+"\",\n" +
                "    \"reqData\":{\n" +
                "         \"merId\":\"82279105094089M\",\n" +
                "         \"termId\":\"E6260896\",\n" +
                "         \"sn\":\"QR939000089076\",\n" +
                "         \"businessType\":\"1\",\n" +
                "         \"shopName\":\"小汪的专属小店\",\n" +
                "         \"source\":\"LOAP\",\n" +
                "         \"merOrgNo\":\"966805\"\n" +
                "    }\n" +
                "}";

        mothod="api/v2/iot/cloud/device/activate";

//
//        String body="{\n" +
//                "    \"ver\":\"1.0.0\",\n" +
//                "    \"timestamp\":\""+req_time+"\",\n" +
//                "    \"reqId\":\""+req_time+"\",\n" +
//                "    \"reqData\":{\n" +
//                "        \"merId\":\"82279105094088V\",\n" +
//                "        \"termId\":\"E6435787\",\n" +
//                "        \"sn\":\"QR939000089076\",\n" +
//                "        \"source\":\"KSAAS\"\n" +
//                "    }\n" +
//                "}";
//        mothod="api/v2/iot/cloud/device/deactivate";


        String authorization = getAuthorization(body, appId, mchSerialNo, privateKeyPath);
        HttpResponse lakalaResponse = post(apiUrl+ mothod, body, authorization, "utf-8");
        if (lakalaResponse.getStatusLine().getStatusCode() != 200) {
            log.error("请求失败,statusCode:{},message:{}", lakalaResponse.getStatusLine(), IOUtils.toString(lakalaResponse.getEntity().getContent(), "utf-8"));
            MsgException.throwException(IOUtils.toString(lakalaResponse.getEntity().getContent(), "utf-8"));
        }

        String appid = getHeadValue(lakalaResponse, "Lklapi-Appid");
        String lklapiSerial = getHeadValue(lakalaResponse, "Lklapi-Serial");
        String timestamp = getHeadValue(lakalaResponse, "Lklapi-Timestamp");
        String nonce = getHeadValue(lakalaResponse, "Lklapi-Nonce");
        String signature = getHeadValue(lakalaResponse, "Lklapi-Signature");
        String responseStr = IOUtils.toString(lakalaResponse.getEntity().getContent(), "utf-8");
        System.out.println("返回的信息为 responseStr:"+responseStr);

        String source = appid + "\n" + lklapiSerial + "\n" + timestamp + "\n" + nonce + "\n" + responseStr + "\n";
        X509Certificate lklCertificate = loadCertificate(new FileInputStream(new File(certificatePath)));
        boolean verify = verify(lklCertificate, source.getBytes("utf-8"), signature);

        if (verify) {
            log.info("验签通过");
            System.out.println(responseStr);
        } else {
        }
    }


}
