package com.search.supersearch.controller;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author 喜欢番茄火锅
 * @date 2023/12/4 18:30
 */
public class Test {
    static  String  appKey= "0b9b2ceb93cc4ec4b23b68ed1c4685ce";
    static  String  appSecret= "ff3278a08ad80b9e4f00879ce82912631a03ddc7";
    static  String  openApiUrl= "http://jmxt.bip.spic";
    public static void main(String[] args) throws Exception{
//        String accessTokenResponse = getAccessTokenResponse();
        getUrl("d067bacf4448a7da897874e3c3f9982826196a45e829e9152f3096bcc7a6aca5");
    }
    private static String getUrl(String token) throws Exception{
        String id = "5a529a01-13c3-451e-a69e-4bf46e00ac54";
        String service = openApiUrl+"/iuap-data-common/ucf-wh/intelliv/index.html#/data_set_edit/create/%s?&serviceCode=intellivworkbenchplatform-21&locale=zh_CN&systenant=U8C3";
        String encode = URLEncoder.encode(String.format(service, id), String.valueOf(StandardCharsets.UTF_8));
//        System.out.println("encode=" + encode);
        String service2 = openApiUrl+"/login?service=%s";
        String encode2 = URLEncoder.encode(String.format(service2, encode), String.valueOf(StandardCharsets.UTF_8));
//        System.out.println("encode=" + encode2);
        String url =openApiUrl+ "/cas/login?sysid=yht&service=%s&token=%s";
        String format = String.format(url, encode2, token);
        System.out.println("format=" + format);
        return format;
    }
    private static String getAccessTokenResponse() throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("appKey", appKey);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        System.out.println(String.valueOf(System.currentTimeMillis()));
        // 计算签名
        String signature = sign(params, appSecret);
        params.put("signature", signature);
        System.out.println(signature);
//        // 请求
//        String requestUrl = openApiUrl + "/open-auth/selfAppAuth/getAccessToken";
//        System.out.println("请求url=" + requestUrl + ",参数=" + JSONUtil.toJsonStr(params));
//        String post = RequestTool.doGet(requestUrl, params);
//        GenericResponse response = JSONUtil.toBean(post, GenericResponse.class);
//        System.out.println("请求结果=" + JSONUtil.toJsonStr(response));
//
//        if (response.isSuccess()) {
//            JSONObject jsonObject = JSONUtil.parseObj(response.getData() + "");
//            return jsonObject.getStr("access_token");
//        }
//        throw new RuntimeException("请求开放平台接口失败, code: " + response.getCode() + ", message: " + response.getMessage());
        return null;
    }

    /**
     * 按参数名排序后依次拼接参数名称与数值，之后对该字符串使用 HmacSHA256 加签，加签结果进行 base 64 返回
     * @param params 请求参数 map
     * @param suiteSecret 套件密钥，用作 mac key
     * @return 签名
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static String sign(Map<String, String> params, String suiteSecret) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        // use tree map to sort params by name
        Map<String, String> treeMap;
        if (params instanceof TreeMap) {
            treeMap = params;
        } else {
            treeMap = new TreeMap<>(params);
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (Map.Entry<String, String> entry : treeMap.entrySet()) {
            stringBuilder.append(entry.getKey()).append(entry.getValue());
        }

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(suiteSecret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
        String base64String = Base64.getEncoder().encodeToString(signData);
        return URLEncoder.encode(base64String, "UTF-8");
    }
}
