package com.cpxt.web.controller.biz.orderutil;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.cpxt.common.annotation.Anonymous;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Security;
import java.util.*;

/**
 * @Author Ly
 * @Create 2024/12/4 18:57
 * @Desc
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class cityDelivery {
    private static final  char[] specialChars = {'\n', '\r', '\t', '\f','\b',' '};

    // test
    String clientKey ="7480617400984563";//accessKey
    String clientSecret = "91wCEvn82CeyMg3k";
    String sm4Key = "MJy05dcI4mPbGB61";
    String appType = "wxmp";
    String client_type = "other";
    String version = "1.0.0";

    /*static{
        Security.addProvider(new BouncyCastleProvider());
    }*/

    /**
     * 同城急送平台工具，post接口
     */
    @Anonymous
    @GetMapping("/getOrder")
    public void cityDelivery_signBody22(){
        Long timeStamp = System.currentTimeMillis();
        String nonce = UUID.randomUUID().toString().replace("-","");
        System.out.println("nonce:"+nonce );
        System.out.println("timeStamp:"+timeStamp );
        //签名
        Map<String,Object> sortedMap = new TreeMap<>();
        //下单接口
        String body = "{\n" +
                "    \"customerCode\": \"HFCP\",\n" +
                "    \"payTypeFirst\": \"03\",\n" +
                "    \"channelOrderNo\": \"Y202501021005-1\",\n" +
                "    \"platformOrderNo\": \"\",\n" +
                "    \"expressNbr\": \"\",\n" +
                "    \"coordinateTransformType\": \"02\",\n" +
                "    \"weight\": \"501\",\n" +
                "    \"expectedTime\": \"2025-01-22,18:12:00\",\n" +
                "    \"postageFee\": \"2000\",\n" +
//                "    \"convertFlag\": false,\n" +
                "    \"orderSource\": \"other\",\n" +
                "    \"orderSourcePlatform\": \"其他\",\n" +
                "    \"costFee\": \"0\",\n" +
                "    \"tipFee\": \"0\",\n" +
                "    \"insuredFee\": \"0\",\n" +
                "    \"otherFee1\": \"0\",\n" +
                "    \"otherFee2\": \"0\",\n" +
                "    \"packageDesc\": \"药品\",\n" +
                "    \"remark\": \"手机尾号1234\",\n" +
                "    \"addressFirst\": {\n" +
                "        \"senderProviceCode\": \"340000\",\n" +
                "        \"senderProviceName\": \"安徽省\",\n" +
                "        \"senderCityCode\": \"340100\",\n" +
                "        \"senderCityName\": \"合肥市\",\n" +
                "        \"senderCountyCode\": \"340102\",\n" +
                "        \"senderCountyName\": \"瑶海区\",\n" +
                "        \"senderContactName\": \"中山三院\",\n" +
                "        \"senderContactPhone\": \"17523029470\",\n" +
                "        \"senderLongitude\": \"117.307179\",\n" +
                "        \"senderLatitude\": \"31.856484\",\n" +
                "        \"senderStreetCode\": \"001\",\n" +
                "        \"senderStreetName\": \"明光路街道\",\n" +
                "        \"senderAddr\": \"明光路188号\",\n" +
                "        \"receiverProviceCode\": \"340000\",\n" +
                "        \"receiverProviceName\": \"安徽省\",\n" +
                "        \"receiverCityCode\": \"340100\",\n" +
                "        \"receiverCityName\": \"合肥市\",\n" +
                "        \"receiverCountyCode\": \"340103\",\n" +
                "        \"receiverCountyName\": \"庐阳区\",\n" +
                "        \"receiverContactName\": \"陈先生\",\n" +
                "        \"receiverContactPhone\": \"13711511111\",\n" +
                "        \"receiverAddr\": \"信源大厦20楼2007\",\n" +
                "        \"receiverLongitude\": \"117.285075\",\n" +
                "        \"receiverLatitude\": \"31.882703\",\n" +
                "        \"receiverStreetCode\": \"002\",\n" +
                "        \"receiverStreetName\": \"双岗街道\"\n" +
                "    },\n" +
                "    \"businessJson\": {\n" +
//                "        \"a\": \"a\",\n" +
//                "        \"b\": \"b\"\n" +
                "    }\n" +
                "}";
        //查询物流轨迹
//        String body = "{\n" +
//                "    \"expressNbr\": \"1158114584567\",\n" +
//                "    \"channelOrderNo\": \"\"\n" +
//                "}";
        //get请求，组装成 k v类型
//        sortedMap.put(paramName,request.getParameter(paramName));
        /**
         * post请求，需要放data
         */
        String bodyjson = JSON.toJSONString(StrUtil.removeAll(body, specialChars));
        System.out.println("bodyjson: " + bodyjson);

        sortedMap.put("data", JSON.toJSONString(StrUtil.removeAll(body, specialChars)));
        sortedMap.put("access_id",clientKey);
        sortedMap.put("nonce", nonce);
        sortedMap.put("timestamp",timeStamp);
        //排序
        Map<String,Object> sortedParams = new TreeMap<>(sortedMap);
        Set<Map.Entry<String,Object>> entrySet = sortedParams.entrySet();
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder stringToSign = new StringBuilder();
        for (Map.Entry<String,Object> param : entrySet) {
            stringToSign.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }
        stringToSign.append("accessSecret").append("=").append(clientSecret);
        String genSign = cityDelivery_SM4Util.encryptCBC(stringToSign.toString(),clientSecret,sm4Key);
        System.out.println("sign:" + genSign);
    }

    public void cityDelivery_signBody2(){
        Long timeStamp = System.currentTimeMillis();
        String nonce = UUID.randomUUID().toString().replace("-","");
        System.out.println("nonce:"+nonce );
        System.out.println("timeStamp:"+timeStamp );
        //签名
        Map<String,Object> sortedMap = new TreeMap<>();
        //下单接口
        String body = "{\n" +
                "    \"customerCode\": \"HFCP\",\n" +
                "    \"payTypeFirst\": \"03\",\n" +
                "    \"convertFlag\": false,\n" +
                "    \"weight\": \"501\",\n" +
                "    \"expectedTime\": \"2025-01-22 18:12:00\",\n" +
                "    \"platformOrderNo\": \"\",\n" +
                "    \"channelOrderNo\": \"\",\n" +
                "    \"orderSource\": \"meituan\",\n" +
                "    \"orderSourcePlatform\": \"01\",\n" +
                "    \"costFee\": \"100\",\n" +
                "    \"packageDesc\": \"药品\",\n" +
                "    \"remark\": \"手机尾号1234\",\n" +
                "    \"expressNbr\": \"\",\n" +
                "    \"insuredFee\": \"1\",\n" +
                "    \"otherFee1\": \"2\",\n" +
                "    \"otherFee2\": \"3\",\n" +
                "    \"addressFirst\": {\n" +
                "        \"senderProviceCode\": \"440000\",\n" +
                "        \"senderProviceName\": \"广东省\",\n" +
                "        \"senderCityCode\": \"440100\",\n" +
                "        \"senderCityName\": \"广州市\",\n" +
                "        \"senderCountyCode\": \"440106\",\n" +
                "        \"senderCountyName\": \"天河区\",\n" +
                "        \"senderContactName\": \"中山三院\",\n" +
                "        \"senderContactPhone\": \"17523029470\",\n" +
                "        \"senderLongitude\": \"113.264000\",\n" +
                "        \"senderLatitude\": \"23.129101\",\n" +
                "        \"senderStreetCode\": \"001\",\n" +
                "        \"senderStreetName\": \"林和街道1\",\n" +
                "        \"senderAddr\": \"天河北路188号\",\n" +
                "        \"receiverProviceCode\": \"440000\",\n" +
                "        \"receiverProviceName\": \"广东省\",\n" +
                "        \"receiverCityCode\": \"440100\",\n" +
                "        \"receiverCityName\": \"广州市\",\n" +
                "        \"receiverCountyCode\": \"440106\",\n" +
                "        \"receiverCountyName\": \"天河区\",\n" +
                "        \"receiverContactName\": \"陈先生\",\n" +
                "        \"receiverContactPhone\": \"13711511111\",\n" +
                "        \"receiverAddr\": \"信源大厦20楼2007\",\n" +
                "        \"receiverLongitude\": \"113.265000\",\n" +
                "        \"receiverLatitude\": \"23.129101\",\n" +
                "        \"receiverStreetCode\": \"002\",\n" +
                "        \"receiverStreetName\": \"林和街道2\"\n" +
                "    },\n" +
                "    \"businessJson\": {\n" +
                "        \"a\": \"asd\",\n" +
                "        \"b\": \"asd\"\n" +
                "    }\n" +
                "}";
        //查询物流轨迹
//        String body = "{\n" +
//                "    \"expressNbr\": \"1158114584567\",\n" +
//                "    \"channelOrderNo\": \"\"\n" +
//                "}";
        //get请求，组装成 k v类型
//        sortedMap.put(paramName,request.getParameter(paramName));
        /**
         * post请求，需要放data
         */
        String bodyjson = JSON.toJSONString(StrUtil.removeAll(body, specialChars));
        System.out.println("bodyjson :" + bodyjson);
        sortedMap.put("data", JSON.toJSONString(StrUtil.removeAll(body, specialChars)));
        sortedMap.put("access_id",clientKey);
        sortedMap.put("nonce", nonce);
        sortedMap.put("timestamp",timeStamp);
        //排序
        Map<String,Object> sortedParams = new TreeMap<>(sortedMap);
        Set<Map.Entry<String,Object>> entrySet = sortedParams.entrySet();
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder stringToSign = new StringBuilder();
        for (Map.Entry<String,Object> param : entrySet) {
            stringToSign.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }
        stringToSign.append("accessSecret").append("=").append(clientSecret);
        String genSign = cityDelivery_SM4Util.encryptCBC(stringToSign.toString(),clientSecret,sm4Key);
        System.out.println("sign:" + genSign);
    }

    /**
     * 同城急送平台工具，获取token
     */
    @Anonymous
    @GetMapping("/getToken2")
    public void getTokenPostMan(){
        Long timeStamp = System.currentTimeMillis();
        String nonce = UUID.randomUUID().toString().replace("-","");
        System.out.println("timeStamp：" + timeStamp);
        System.out.println("nonce：" + nonce);
        //body
        Map map = new HashMap();
        map.put("clientKey",clientKey);
        map.put("clientSecret",clientSecret);
        map.put("appType",appType);
        map.put("clientType",client_type);
        map.put("version",version);

        Map<String, Object> sortedParams1 = new TreeMap<>(map);
        Set<Map.Entry<String, Object>> entrySet1 = sortedParams1.entrySet();
        StringBuilder stringToSign = new StringBuilder();
        for (Map.Entry<String, Object> param : entrySet1) {
            stringToSign.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }

        String encryptBase64 = cityDelivery_SM4Util.encryptCBC(stringToSign.toString(),clientSecret,sm4Key);
        System.out.println("body:" + encryptBase64);
        //签名
        Map<String,Object> sortedMap2 = new TreeMap<>();

        //get请求，组装成 k v类型
//        sortedMap2.put(paramName,request.getParameter(paramName));
        /**
         * post请求，需要放data
         */
        Map bodyMap = new HashMap();
        bodyMap.put("body",encryptBase64);
        String bodyJson = JSON.toJSONString(bodyMap);
        sortedMap2.put("data", JSON.toJSONString(bodyJson));
        sortedMap2.put("access_id",clientKey);
        sortedMap2.put("nonce", nonce);
        sortedMap2.put("timestamp",timeStamp);
        //排序
        Map<String,Object> sortedParams2 = new TreeMap<>(sortedMap2);
        Set<Map.Entry<String,Object>> entrySet2 = sortedParams2.entrySet();
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder stringToSign2 = new StringBuilder();
        for (Map.Entry<String,Object> param : entrySet2) {
            stringToSign2.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }
        stringToSign2.append("accessSecret").append("=").append(clientSecret);
//        String genSign = DigestUtils.md5Hex(stringToSign2.toString());
        String genSign = cityDelivery_SM4Util.encryptCBC(stringToSign2.toString(),clientSecret,sm4Key);
        System.out.println("------------");
        System.out.println("sign:" + genSign);
    }

    //获取token
    @Anonymous
    @GetMapping("/getToken")
    public void getToken(){
        System.out.println("获取token");
        String url = "https://wyjcs.gdwyj.cn/szelec/city-delivery-api/api/mini/app/login/token";
        String nonce = UUID.randomUUID().toString().replace("-", "");
        Long timestamp = System.currentTimeMillis();
        //body
        Map map = new HashMap();
        map.put("clientKey",clientKey);
        map.put("clientSecret",clientSecret);
        map.put("appType",appType);
        map.put("clientType",client_type);
        map.put("version",version);

        Map<String, Object> sortedParams1 = new TreeMap<>(map);
        Set<Map.Entry<String, Object>> entrySet1 = sortedParams1.entrySet();
        StringBuilder stringToSign = new StringBuilder();
        for (Map.Entry<String, Object> param : entrySet1) {
            stringToSign.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }

        String encryptBase64 = cityDelivery_SM4Util.encryptCBC(stringToSign.toString(),clientSecret,sm4Key);
        System.out.println("body:" + encryptBase64);
        //签名
        Map<String,Object> sortedMap2 = new TreeMap<>();

        //get请求，组装成 k v类型
//        sortedMap2.put(paramName,request.getParameter(paramName));
        /**
         * post请求，需要放data
         */
        Map bodyMap = new HashMap();
        bodyMap.put("body",encryptBase64);
        String bodyJson = JSON.toJSONString(bodyMap);
        sortedMap2.put("data", JSON.toJSONString(bodyJson));
        sortedMap2.put("access_id",clientKey);
        sortedMap2.put("nonce", nonce);
        sortedMap2.put("timestamp",timestamp);
        //排序
        Map<String,Object> sortedParams2 = new TreeMap<>(sortedMap2);
        Set<Map.Entry<String,Object>> entrySet2 = sortedParams2.entrySet();
        // 遍历排序后的字典，将所有参数按"key=value"格式拼接在一起
        StringBuilder stringToSign2 = new StringBuilder();
        for (Map.Entry<String,Object> param : entrySet2) {
            stringToSign2.append(param.getKey()).append("=").append(param.getValue()).append(",");
        }
        stringToSign2.append("accessSecret").append("=").append(clientSecret);
//        String genSign = DigestUtils.md5Hex(stringToSign2.toString());
        String genSign = cityDelivery_SM4Util.encryptCBC(stringToSign2.toString(),clientSecret,sm4Key);
        System.out.println("------------");
        System.out.println("sign:" + genSign);


        HttpResponse response = HttpRequest.post(url)
                .body(JSON.toJSONString(bodyMap))
                .header("Content-Type", "application/json")
                .header("client_type", client_type)
                .header("app_type", appType)
                .header("access_id", clientKey)
                .header("nonce", nonce)
                .header("timestamp", timestamp.toString())
                .header("sign", genSign)
                .execute();
        System.out.println(response);
    }
}
