package com.qmth.jkserver.util;

import com.qmth.jkserver.enums.BlurryQueryTypeEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

/**
 * @Description: 模糊查询处理类
 * @Author: CaoZixuan
 * @Date: 2021-11-16
 */
public class BlurryQueryUtil {

    /**
     * regex对输入特殊字符转义
     * @param keyword 关键字
     * @return 转译处理后的关键字
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (StringUtils.isNotBlank(keyword)) {
            String[] fbsArr = { "\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|" };
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\" + key);
                }
            }
        }
        return keyword;
    }

    /**
     * 构造模糊查询元素
     * @param keyword 关键字
     * @param type 模糊查询策略
     * @return 构建好的模糊查询匹配元素
     */
    public static Pattern buildBlurryElement(String keyword, BlurryQueryTypeEnum type){
        keyword = escapeExprSpecialWord(keyword);
        Pattern pattern;
        switch (type){
            case COMPLETE_MATCHING:
                //完全匹配
                pattern = Pattern.compile("^"+ keyword + "$", Pattern.CASE_INSENSITIVE);
                break;
            case LEFT_MATCHING:
                //左匹配
                pattern = Pattern.compile("^"+ keyword + ".*$", Pattern.CASE_INSENSITIVE);
                break;
            case RIGHT_MATCHING:
                //右匹配
                pattern = Pattern.compile("^.*"+ keyword + "$", Pattern.CASE_INSENSITIVE);
                break;
            default:
                //模糊匹配
                pattern = Pattern.compile("^.*"+ keyword + ".*$", Pattern.CASE_INSENSITIVE);
        }
        return pattern;
    }
}
