package com.njzscloud.common.security.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.njzscloud.common.security.contant.Constants;
import com.njzscloud.common.security.support.VerificationCodeService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 加密工具
 */
public class EncryptUtil {
    /**
     * 加密器
     */
    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

    /**
     * 加密
     *
     * @param password 密码(明文)
     * @return 密码(密文)
     */
    public static String encrypt(String password) {
        if (StrUtil.isBlank(password)) return null;
        return ENCODER.encode(password);
    }

    /**
     * 匹配密码
     *
     * @param rawPassword     密码(明文)
     * @param encodedPassword 密码(密文)
     * @return 匹配结果, true: 成功
     */
    public static boolean matches(String rawPassword, String encodedPassword) {
        return ENCODER.matches(rawPassword, encodedPassword);
    }

    /**
     * 获取随机密码, 默认长度为 6
     *
     * @return String[ ] 0-->密码(原文), 1-->密码(密文)
     */
    public static String[] randomPassword() {
        return randomPassword(6);
    }

    /**
     * 获取随机密码
     *
     * @param len 密码长度
     * @return String[ ] 0-->密码(原文), 1-->密码(密文)
     */
    public static String[] randomPassword(int len) {
        String password = RandomUtil.randomString(Constants.RANDOM_BASE_STRING, len);
        String encryptedPassword = encrypt(password);
        return new String[]{password, encryptedPassword};
    }

    public static boolean checkCode(String codeId, String code) {
        VerificationCodeService verificationCodeService = SpringUtil.getBean(VerificationCodeService.class);
        return verificationCodeService.checkCode(codeId, code);
    }


    public static void main(String[] args) {
        System.out.println(encrypt("admin"));
    }
}
