package cn.com.ty.lift.ud.neety.support;

import java.util.Iterator;
import java.util.Set;

import cn.com.ty.lift.ud.utils.ApplicationContextUtil;
import cn.com.ty.lift.ud.sensitivewords.service.ISensitiveWordsService;
import cn.com.ty.lift.ud.sensitivewords.service.impl.SensitiveWordsServiceImpl;

/**
 * 敏感词过滤
 * 
 * @author sKing
 * @Date 2020年6月17日
 */
public class SensitivewordFilter {

    private static ISensitiveWordsService liftCaseService =
        ApplicationContextUtil.getBean(SensitiveWordsServiceImpl.class);

    /**
     * 替换敏感字字符
     * 
     * @param txt
     * @param matchType
     * @param replaceChar
     *            替换字符，默认*
     * @version 1.0
     */
    public static String replaceSensitiveWord(String txt, int matchType, String replaceChar) {
        String resultTxt = txt;
        Set<String> set = liftCaseService.changText(txt, matchType); // 获取所有的敏感词
        Iterator<String> iterator = set.iterator();
        String word = null;
        String replaceString = null;
        while (iterator.hasNext()) {
            word = iterator.next();
            replaceString = getReplaceChars(replaceChar, word.length());
            resultTxt = resultTxt.replaceAll(word, replaceString);
        }
        return resultTxt;
    }

    /**
     * 获取替换字符串
     * 
     * @author chenming
     * @param replaceChar
     * @param length
     * @return
     * @version 1.0
     */
    private static String getReplaceChars(String replaceChar, int length) {
        String resultReplace = replaceChar;
        for (int i = 1; i < length; i++) {
            resultReplace += replaceChar;
        }

        return resultReplace;
    }
}
