package io.hmit.modules.zlb.utils;

import io.hmit.modules.zlb.constants.Constants;
import javafx.util.Pair;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jie.chen
 * @date 2022-03-30 15:28
 */
public class IrsUtils {


    @SneakyThrows
    public static IrsSignRes sign(String url, String method) {
        UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).build();
        uriComponents = uriComponents.encode();
        List<String> queryArr = new ArrayList<>();
        MultiValueMap<String, String> queryParams = uriComponents.getQueryParams();
        for (Map.Entry<String, List<String>> next : queryParams.entrySet()) {
            for (String va : next.getValue()) {
                if (va == null) {
                    queryArr.add(next.getKey() + "=");
                } else {
                    queryArr.add(next.getKey() + "=" + va);
                }
            }
        }
        //按照字典排序
        Collections.sort(queryArr);
        ///Tue, 09 Nov 2021 08:49:20 GMT
        DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String dateTime = dateFormat.format(new Date());

        String signStr = method.toUpperCase() + "\n" +
                //拼接url path
                uriComponents.getPath() + "\n" +
                //拼接url query
                String.join("&", queryArr) + "\n" +
                Constants.IRS_AK + "\n" +
                dateTime + "\n";

        String sign = hmacSha256Base64(signStr, Constants.IRS_SK);

        IrsSignRes res = new IrsSignRes();

        res.setSignature(sign);
        res.setAccessKey(Constants.IRS_AK);
        res.setDateTime(dateTime);
        res.setAlgorithm(Constants.DEFAULT_HMAC_SIGNATURE);
        return res;
    }


    @SneakyThrows
    private static String hmacSha256Base64(String content, String key) {
        Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmacSHA256.init(secretKey);
        byte[] bytes = hmacSHA256.doFinal(content.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(bytes);
    }



    /**
     * 构造请求 header
     * @paramurlStr 请求 url，全路径格式，比如：
    https://bcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220905000004/uc/auth/verify/sendMessage
     * @paramrequestMethod 请求方法,大写格式，如：GET,POST
     * @paramaccessKey 应用的 AK
     * @paramsecretKey 应用的 SK
     * @return
     */
    public static HttpHeaders generateHeader(String urlStr, String requestMethod, String accessKey, String secretKey) {
//        log.info("params,urlStr={},requestMethod={},accessKey={},secretKey={}",urlStr,requestMethod,accessKey,secretKey);
        HttpHeaders headers = new HttpHeaders();
//        Map<String, String> header = new HashMap<>();
        try {
            DateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = dateFormat.format(new Date());
            URL url = new URL(urlStr);
            URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
            String canonicalQueryString = getCanonicalQueryString(uri.getQuery());
            String message = requestMethod.toUpperCase() + "\n" + uri.getPath() + "\n" +
                    canonicalQueryString + "\n" + accessKey + "\n" + date + "\n";
            Mac hasher = Mac.getInstance("HmacSHA256");
            hasher.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"));
            byte[] hash = hasher.doFinal(message.getBytes());
            // to lowercase hexits
            DatatypeConverter.printHexBinary(hash);
            // to base64
            String sign = DatatypeConverter.printBase64Binary(hash);
            headers.add("X-BG-HMAC-SIGNATURE", sign);
            headers.add("X-BG-HMAC-ALGORITHM", "hmac-sha256");
            headers.add("X-BG-HMAC-ACCESS-KEY", accessKey);
            headers.add("X-BG-DATE-TIME", date);
        } catch (Exception e) {
//            log.error("generate error",e);
            throw new RuntimeException("generate header error");
        }
//        log.info("header info,{}",header);
        return headers;
    }
    private static String getCanonicalQueryString(String query) {
        if (query == null || query.trim().length() == 0) {
            return "";
        }
        List<Pair<String, String>> queryParamList = new ArrayList<>();
        String[] params = query.split("&");
        for (String param : params) {
            int eqIndex = param.indexOf("=");
            String key = param.substring(0, eqIndex);
            String value = param.substring(eqIndex+1);
            Pair<String, String> pair = new Pair<String, String>(key,value);
            queryParamList.add(pair);
        }
        List<Pair<String,String>> sortedParamList =
                queryParamList.stream().sorted(Comparator.comparing(param -> param.getKey() +"=" +
                        Optional.ofNullable(param.getValue()).orElse(""))).collect(Collectors.toList());
        List<Pair<String, String>> encodeParamList = new ArrayList<>();
        sortedParamList.stream().forEach(param-> {
            try {
                String key = URLEncoder.encode(param.getKey(), "utf-8");
                String value = URLEncoder.encode(Optional.ofNullable(param.getValue()).orElse(""), "utf-8")
                        .replaceAll("\\%2B","%20")
                        .replaceAll("\\+","%20")
                        .replaceAll("\\%21","!")
                        .replaceAll("\\%27","'")
                        .replaceAll("\\%28","(")
                        .replaceAll("\\%29",")")
                        .replaceAll("\\%7E","~")
                        .replaceAll("\\%25","%")
                        ;
                encodeParamList.add(new Pair<>(key, value));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("encoding error");
            }
        });
        StringBuilder queryParamString = new StringBuilder(64);
        for (Pair<String, String> encodeParam : encodeParamList) {
            queryParamString.append(encodeParam.getKey()).append("=").append(Optional.ofNullable(encodeParam.getValue()).orElse(""));
            queryParamString.append("&");
        }
        return queryParamString.substring(0, queryParamString.length()- 1);
    }


    public static void main(String[] args) {

        System.out.println(sign("https://bcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220329000007/uc/sso/getUserInfo", "POST"));
    }

}
