package cn.quantgroup.xyqb.util;

import cn.quantgroup.xyqb.Constants;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import org.apache.commons.lang.StringUtils;

import java.security.MessageDigest;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;

/**
 * Created by Miraculous on 15/7/5.
 */
public class PasswordUtil {
    private static final String PASSWORD_SALT = "_lkb";
    public static final String PASSWORD_DEFAULT = "123456";
    public static final String TOAST_MSG = "8~20位，须包含字母，数字，符号至少两种";

    private static final char[] HEX_DIGITS = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };

    private static final char[] PWD_BASE = {
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
            'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';',
            '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'
    };

    public final static String MD5WithSalt(String s){
        if(Objects.isNull(s)){
            return null;
        }
        return MD5(s.toLowerCase() + PASSWORD_SALT);
    }

    public final static String MD5(String s) {
        if(Objects.isNull(s)){
            return null;
        }
        try {
            byte[] strTemp = s.getBytes("utf-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] str = new char[j << 1];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = HEX_DIGITS[byte0 >>> 4 & 0xf];
                str[k++] = HEX_DIGITS[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成随机密码
     *
     * @param pwdLen 密码长度，必须大于0
     * @return
     */
    public static String generateRandomPwd(int pwdLen) {
        Preconditions.checkArgument(pwdLen > 0);
        StringBuilder pwd = new StringBuilder();
        while (pwd.length() < pwdLen) {
            // 随机整数区间: [0, PWD_BASE.length - 1)
            int index = ThreadLocalRandom.current().nextInt(0, PWD_BASE.length);
            pwd.append(PWD_BASE[index]);
        }
        return pwd.toString();
    }

    /**
     * 校验密码是否合法 - 不允许空密码
     *
     * @param password 请求密码
     * @param targetPassword 参照密码
     * @return
     */
    public static boolean validatePassword(String password, String targetPassword) {
        if(StringUtils.isBlank(password)){
            return false;
        }
        String thePassword = MD5WithSalt(password);
        return Objects.equals(thePassword, targetPassword);
    }

    public static String filterPasswordToString(Map<String, String> info) {
        if (null == info) {
            return null;
        }
        if(!info.containsKey(Constants.PASSWORD)){
            return JSON.toJSONString(info);
        }
        String password = info.get(Constants.PASSWORD);
        // 先删掉
        info.remove(Constants.PASSWORD);
        String infoString = JSON.toJSONString(info);
        // 再回填
        info.put(Constants.PASSWORD, password);
        return infoString;
    }

}
