//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.chushang.common.core.util;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.chushang.common.core.text.ToolUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MD5Util extends MD5 {

    public static String md5Sign(String jsonStr, String keyStr) throws Exception {
        Map<String, Object> mapTemp = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(JSON.parseObject(jsonStr), JSONWriter.Feature.MapSortField));
        Set<Map.Entry<String, Object>> objs = jsonObject.entrySet();

        for (Map.Entry<String, Object> stringObjectEntry : objs) {
            if (!(stringObjectEntry.getKey().equals("sign") && !ToolUtils.isBlank(stringObjectEntry.getValue()))) {
                mapTemp.put((stringObjectEntry).getKey(), stringObjectEntry.getValue());
            }
        }
        String strValue = genString(mapTemp, keyStr);
        log.debug("signStr:" + strValue);
        return calcValidateSign(strValue);
    }
    private static String genString(Map<String, Object> mapTmp, String keyStr) {
        ArrayList<String> arrayTmp = new ArrayList<>();

        for (Map.Entry<String, Object> stringObjectEntry : mapTmp.entrySet()) {
            String strValue = stringObjectEntry.getValue().toString();
            if (!ToolUtils.isBlank(strValue)) {
                arrayTmp.add((stringObjectEntry).getKey() + "=" + stringObjectEntry.getValue() + "&");
            }
        }

        String[] strArray = arrayTmp.toArray(new String[0]);
        Arrays.sort(strArray);
        StringBuilder strBuf = new StringBuilder();

        for (String s : strArray) {
            strBuf.append(s);
        }
        strBuf.append("key=").append(keyStr);
        return strBuf.toString();
    }

    private static String calcValidateSign(String strValue) throws UnsupportedEncodingException {
        byte[] byteString = strValue.getBytes(StandardCharsets.UTF_8);

        byte[] result;
        try {
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(byteString);
            result = mdInst.digest();
        } catch (NoSuchAlgorithmException var4) {
            return null;
        }

        return binaryToHexString(result).toUpperCase();
    }
    private static String binaryToHexString(byte[] result) {
        StringBuilder digestHexStr = new StringBuilder();

        for(int i = 0; i < 16; ++i) {
            char[] Digit = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
            char[] ob = new char[]{Digit[result[i] >>> 4 & 15], Digit[result[i] & 15]};
            String s = new String(ob);
            digestHexStr.append(s);
        }

        return digestHexStr.toString();
    }

    public static String getMD5Encrypt(String strSrc) {
        return encodeEncrypt(strSrc, "MD5");
    }

    public static String encodeEncrypt(String strSrc, String encName) {
        MessageDigest md;
        String strDes;
        byte[] bt = strSrc.getBytes();

        try {
            if (encName == null || encName.isEmpty()) {
                encName = "MD5";
            }

            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest());
            return strDes;
        } catch (NoSuchAlgorithmException var6) {
            log.error("Invalid algorithm.");
            return null;
        }
    }
    public static String bytes2Hex(byte[] bts) {
        StringBuilder des = new StringBuilder();
        String tmp;
        for (byte bt : bts) {
            tmp = Integer.toHexString(bt & 255);
            if (tmp.length() == 1) {
                des.append("0");
            }
            des.append(tmp);
        }
        return des.toString();
    }
}
