package com.ltgk.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class PasswordValidator {
    @Autowired
    private SensitiveWordsProperties sensitiveWordsProperties;
    // 敏感词集合（人名+公司词）
    private final Set<String> WEAK_PATTERNS = new HashSet<>();
    // 匹配连续数字（至少4位）的正则表达式
    private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d{4,}");

    // 匹配连续字母（至少4位，不区分大小写）的正则表达式
    private static final Pattern LETTER_PATTERN = Pattern.compile("[a-zA-Z]{4,}");

    @PostConstruct
    public void init() {
        WEAK_PATTERNS.addAll(sensitiveWordsProperties.getChineseNames());
        WEAK_PATTERNS.addAll(sensitiveWordsProperties.getEnglishNames());
        WEAK_PATTERNS.addAll(sensitiveWordsProperties.getCompanyNames());
        WEAK_PATTERNS.addAll(sensitiveWordsProperties.getSystemWords());
        WEAK_PATTERNS.addAll(sensitiveWordsProperties.getOtherSensitive());
    }
    // 检查是否为弱密码
    public boolean isWeakPassword(String password) {
        // 检查是否包含简单序列
        for (String pattern : WEAK_PATTERNS) {
            if (password.contains(pattern)) {
                return true;
            }
        }
        // 检查是否为连续数字（如123456）
        if (hasConsecutiveSequence(password)) {
            return true;
        }
        return false;
    }

    /**
     * 检查字符串是否包含连续递增/递减的数字（长度≥4）
     * 例如：1234、23456、7654、98765等
     */
    public static boolean hasConsecutiveNumbers(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }

        Matcher matcher = NUMBER_PATTERN.matcher(str);
        while (matcher.find()) {
            String numberSeq = matcher.group();
            if (isConsecutiveSequence(numberSeq, true)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查字符串是否包含连续递增/递减的字母（长度≥4）
     * 例如：abcd、bcdef、fedcba、dcba等
     */
    public static boolean hasConsecutiveLetters(String str) {
        if (str == null || str.isEmpty()) {
            return false;
        }

        Matcher matcher = LETTER_PATTERN.matcher(str);
        while (matcher.find()) {
            String letterSeq = matcher.group().toLowerCase(); // 统一转为小写处理
            if (isConsecutiveSequence(letterSeq, false)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 核心检测逻辑：判断字符序列是否为连续递增或递减
     */
    private static boolean isConsecutiveSequence(String sequence, boolean isNumber) {
        // 长度不足4的直接排除（因为正则已经确保≥4，这里做双重保险）
        if (sequence.length() < 4) {
            return false;
        }

        boolean isIncreasing = true;  // 是否递增
        boolean isDecreasing = true;  // 是否递减

        for (int i = 1; i < sequence.length(); i++) {
            char prev = sequence.charAt(i - 1);
            char curr = sequence.charAt(i);
            int diff = curr - prev;

            // 数字和字母的连续差值都是1
            if (diff != 1) {
                isIncreasing = false;
            }
            if (diff != -1) {
                isDecreasing = false;
            }

            // 既不递增也不递减，提前退出
            if (!isIncreasing && !isDecreasing) {
                return false;
            }
        }

        // 只要满足递增或递减其中一种即可
        return isIncreasing || isDecreasing;
    }

    /**
     * 综合检测：是否包含连续数字或字母组合
     */
    public static boolean hasConsecutiveSequence(String str) {
        return hasConsecutiveNumbers(str) || hasConsecutiveLetters(str);
    }
}
