namespace IRaCIS.Core.Application.Helper;

public static class IRCEmailPasswordHelper
{
    private static readonly Random Random = new Random();

    //显示位数：3分之2的位数，向上取整
    //取哪几个个值：最后一位和前面几位
    //其他：3个***。
    //比如：hlj23@126.com
    //为：hlj***3@126.com

    //he@126.com
    //为：h*** e@126.com

    public static string MaskEmail(string email)
    {

        // 找到 "@" 符号的位置
        int atIndex = email.IndexOf('@');

        string visiblePartBefore = email.Substring(0, atIndex);

        string afterAt = email.Substring(atIndex + 1);

        int visibleLength = (int)Math.Ceiling((double)visiblePartBefore.Length * 2 / 3);

        // 替换中间两位字符为星号
        string hiddenPartBeforeAt = visiblePartBefore.Substring(0, visibleLength - 1) + "***" + visiblePartBefore.Last();


        // 组合隐藏和可见部分
        string hiddenEmail = hiddenPartBeforeAt + "@" + afterAt;

        return hiddenEmail;
    }

    /// <summary>
    /// 密码必须包含：1）8 – 32 个字符；2）至少1个数字；3) 至少1个大写字母；4）至少1个小写字母；5）至少1个特殊字符 (~!-@#$%^&*_+?)
    /// </summary>
    /// <returns></returns>
    public static string GenerateRandomPassword(int length)
    {
        // 必须包含的字符组
        const string numbers = "0123456789";
        const string upperCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        const string lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz";
        const string specialCharacters = "~!-@#$%^&*_+?";

        // 随机选择至少一个字符
        char[] requiredCharacters =
        {
        numbers[Random.Next(numbers.Length)],
        upperCaseLetters[Random.Next(upperCaseLetters.Length)],
        lowerCaseLetters[Random.Next(lowerCaseLetters.Length)],
        specialCharacters[Random.Next(specialCharacters.Length)]
        };

        // 构建剩余的字符集，用于填充密码的其余部分
        string allCharacters = numbers + upperCaseLetters + lowerCaseLetters + specialCharacters;

        // 确保密码长度满足用户要求
        char[] password = new char[length];

        // 将必须包含的字符放入密码中
        requiredCharacters.CopyTo(password, 0);

        // 填充剩余的字符
        for (int i = requiredCharacters.Length; i < length; i++)
        {
            password[i] = allCharacters[Random.Next(allCharacters.Length)];
        }

        // 随机打乱密码字符顺序
        return new string(password.OrderBy(_ => Random.Next()).ToArray());
    }
}
