package com.yeejoin.amos.api.householdapi.Utils;

import com.yeejoin.amos.api.householdapi.face.model.HouseholdPvApiDto;
import com.yeejoin.amos.openapi.enums.PVProducerInfoEnum;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
//锦浪云 header处理类
public class GoLangHeaderUtils {
    public static String HmacSHA1Encrypt(String encryptText, String KeySecret) throws Exception
    {
        byte[] data=KeySecret.getBytes("UTF-8");
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] text = encryptText.getBytes("UTF-8");
        byte[] result = mac.doFinal(text);
        return Base64.encodeBase64String(result);
    }

    public static String  getGMTTime(){
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String str = sdf.format(cd.getTime());
        return  str;
    }

    //获取header中的 Content-MD5
    public static String getDigest(String test) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(test.getBytes());
            byte[] b = md.digest();
            result = java.util.Base64.getEncoder().encodeToString(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
    /***
     *
     * @param params 参数字符窜
     * @param householdPvApiDto apidto
     * @param headMap header头
     * @param orginalAuthorization 原始的orginalAuthorization
     * @param appsecret  appsecret
     * @param cacheParams  缓存的参数值
     * @desc 锦浪云请求参数及head头处理
     */
    public void JLYHeaderMapHandler(String params, HouseholdPvApiDto householdPvApiDto, HashMap<String, String> headMap, String orginalAuthorization, String appsecret, String cacheParams) {
        if (PVProducerInfoEnum.JLY.getCode().equals(householdPvApiDto.getProducerId())) {
            String contentMD5 = GoLangHeaderUtils.getDigest(params);
            headMap.put("Date", GoLangHeaderUtils.getGMTTime());
            String param = "POST" + "\n" + contentMD5 + "\n" + "application/json" + "\n" + headMap.get("Date") + "\n" + householdPvApiDto.getApiUrl();
            String sign = "";
            try {
                sign = GoLangHeaderUtils.HmacSHA1Encrypt(param, appsecret);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            headMap.put("Content-MD5", contentMD5);
            headMap.put("Authorization", orginalAuthorization + sign);
        }
    }
}
