package org.jeecg.common.util;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @author wangshuaichao
 * @Description: 随机产生唯一的app_key和app_secret
 */
@Slf4j
public class AppUtils {
    //生成 app_secret 密钥
    private final static String SERVER_NAME = "tax_abc123";
    /**
     * 获取32位uuid的appKey
     *
     */
    public static String getAppKey() {
        return IdWorker.get32UUID();
    }

    /**
     * 通过appKey和内置关键词生成APP Secret
     *
     */
    public static String getAppSecret(String appId) {
        try {
            String[] array = new String[]{appId, SERVER_NAME};
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < array.length; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();

            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
            log.error(e.getMessage(), e);
            throw new RuntimeException();
        }
    }

    public static void main(String[] args) {
        String appKey =getAppKey();
        String appSecret = getAppSecret(appKey);
        System.out.println("appKey: "+appKey);
        System.out.println("appSecret: "+appSecret);
    }
}
