package cn.com.tenlion.configcontent.util;

import cn.com.tenlion.configcontent.pojo.dtos.contentantistop.ContentAntistopDTO;
import cn.com.tenlion.configcontent.service.contentantistop.IContentAntistopService;
import com.github.binarywang.java.emoji.EmojiConverter;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 系统敏刚词识别工具类
 * ClassName: AntistopUtil
 * @Description: TODO
 * 创建工具: MyEclipse2014
 * 运行环境: [Tomcat7以上,MySql5.6以上,JDK7以上]
 * @author 崔宝铖 / 纯手打,2019年8月4日01:05:16
 * @date 2019年8月2日
 */
@Component
public class AntistopUtil implements Serializable {


	private static final long serialVersionUID = 1L;
	/**
	 * 存放敏感词
	 */
	private static final Map<String, String> antistopMap = new HashMap<String, String>();

	private static Logger logger= LoggerFactory.getLogger(AntistopUtil.class);
	
	public static void deleteAntistop(String antistopId) {
		antistopMap.remove(antistopId);
	}

	public static EmojiConverter emojiConverter = EmojiConverter.getInstance();

	@Autowired
	private IContentAntistopService iContentAntistopService;

	private static IContentAntistopService iContentAntistopStaticService;

	@PostConstruct
	public void init() {
		iContentAntistopStaticService = this.iContentAntistopService;
		Map<String, Object> params = new HashMap<String, Object>();
		List<ContentAntistopDTO> antistopList = this.iContentAntistopService.listContentAntistop(params);
		for (ContentAntistopDTO antistop : antistopList) {
			AntistopUtil.push(antistop.getContentAntistopId(), antistop.getContentAntistopName());
		}
	}

	public static void push(String antistopId, String content) {
		antistopMap.put(antistopId, content);
	}
	
	public static ArrayList<String> getList() {
		ArrayList<String> list = new ArrayList<String>();
		Iterator<String> iterator = antistopMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			String value = antistopMap.get(key);
			list.add(value.replaceAll("#", ""));
		}
		return list;
	}
	
	/**
	 * 找出涉及到的拼音敏感词
	 * @Description: TODO
	 * @param @param recordContent
	 * @param @return   
	 * @return TreeMap<Integer,String>  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月5日
	 */
	public static TreeMap<Integer,String> buiderPinyin(String recordContent) {
		char[] charArr = recordContent.toCharArray();
		TreeMap<Integer,String> indexTree = new TreeMap<Integer,String>();
		String[] temp = Pinyin4jUtils.stringToPinyin(recordContent);
		String content = "#" + StringUtils.join(temp, "#") + "#";
		Iterator<String> iterator = antistopMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			String value = antistopMap.get(key);
			String[] arr = content.split(value);
			if(arr.length > 0 && content.contains(value)) {
				for (int i = 0; i < arr.length-1; i++) {
					// 算出当前前面有多少个字母(除了#号的)
					int startIndex = getPinyinIndex(arr, i, value);
					String viewContent = getPinyinIndex(charArr, startIndex, value);
					indexTree.put(startIndex, viewContent);
				}
			}
		}
		return indexTree;
	}
	
	/**
	 * 获取当前敏感词的索引值 [拼音]
	 * @Description: TODO
	 * @param @param arr
	 * @param @param i
	 * @param @param value
	 * @param @return   
	 * @return int  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static int getPinyinIndex(String[] arr, int i, String value) {
		int strIndex = 0;
		for (int j = 0; j <= i; j++) {
			strIndex += ( arr[j].length() - arr[j].replaceAll("#", "").length());
			int beginFlag = value.length() - value.replaceAll("#", "").length();
			if(beginFlag > 0 && j > 0) {
				strIndex += (beginFlag * j);
			}
		}
		return strIndex;
	}
	
	/**
	 * 获取当前敏感词的值 [拼音]
	 * @Description: TODO
	 * @param @param arr
	 * @param @param i
	 * @param @param value
	 * @param @return   
	 * @return int  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static String getPinyinIndex(char[] charArr, int i, String value) {
		StringBuffer buffer = new StringBuffer();
		int valueLength = i - 1 + ( value.length() - (value.replaceAll("#", "").length()) ) ;
		for (int j = (i-1); j <= valueLength; j++) {
			buffer.append(charArr[j]);
		}
		return buffer.toString();
	}

	/**
	 * 将评论中的表情进行替换为特定字符
	 * @param source
	 * @return
	 */
	public static String replaceEmoji(String source) {
		if (source != null) {
			Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
					Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
			Matcher emojiMatcher = emoji.matcher(source);
			if (emojiMatcher.find()) {
				source = emojiMatcher.replaceAll("*");
				return source;
			}
			return source;
		}
		return source;
	}
	
	/**
	 * 敏感词识别并且加红 、 入口方法
	 * @Description: TODO
	 * @param @param recordContent
	 * @param @return   
	 * @return String  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static String buiderView(String recordContent) {
		if(StringUtil.isEmpty(recordContent) || antistopMap.size() < 1) return "";
		String newRecordContent = "&" + recordContent + "&";
		// 文字判断
		TreeMap<Integer,String> indexTree = new TreeMap<Integer,String>();
		Iterator<String> iterator = antistopMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = (String) iterator.next();
			String value = antistopMap.get(key);
			String[] arr = newRecordContent.split(value);
			if(arr.length > 0 && newRecordContent.contains(value)) {
				for (int i = 0; i < arr.length-1; i++) {
					int startIndex = getIndex(arr, i, value);
					indexTree.put(startIndex, value);
				}
			}
		}
		// 拼音判断
		TreeMap<Integer,String> pinyinTree = buiderPinyin(recordContent);
		for(Entry<Integer, String> m : pinyinTree.entrySet()) {
			String value = indexTree.get(m.getKey());
			if( value != null){
				if(m.getValue().length() > value.length() ) {
					indexTree.put(m.getKey(), m.getValue());
				}
			}else{
				indexTree.put(m.getKey(), m.getValue());
			}
		}
		// 敏感词去重
		NavigableMap<Integer,String> treeMap = indexTree.descendingMap();
		Iterator<Integer> iteratorTree = indexTree.keySet().iterator();
		while (iteratorTree.hasNext()) {
			Integer key = (Integer) iteratorTree.next();
			int index = getThePrevious(treeMap, key);
			if(index > 0) {
				iteratorTree.remove();
			}
		}
		return repliceFront(newRecordContent, indexTree);
	}
	
	/**
	 * 将所有的敏感词进行加红
	 * @Description: TODO
	 * @param @param recordContent
	 * @param @param indexTree
	 * @param @return   
	 * @return String  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static String repliceFront(String recordContent, TreeMap<Integer,String> indexTree) {
		StringBuffer buffer = new StringBuffer();
		char[] arr = recordContent.toCharArray();
		for (int i = 0; i < arr.length; i++) {
			String value = indexTree.get(i);
			if(value != null) {
				i = (i + (value.length()-1));
				buffer.append("<font class='antistopColor'>").append(value).append("</font>");
				continue;
			}
			buffer.append(arr[i]);
		}
		return buffer.toString().replaceAll("&", "");
	}
	
	/**
	 * 防止出现包含词 , 例如 张三三 [即有张三,又有三]
	 * @Description: TODO
	 * @param @param treeMap
	 * @param @param startIndex
	 * @param @return   
	 * @return Integer  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static Integer getThePrevious(NavigableMap<Integer,String> treeMap, int startIndex) {
		Iterator<Integer> iterator = treeMap.keySet().iterator();
		while (iterator.hasNext()) {
			Integer key = (Integer) iterator.next();
			String value = treeMap.get(key);
			if(key < startIndex) {
				if(key + value.length() > startIndex) {
					return key;
				}
			}
		}
		return -1;
	}
	
	/**
	 * 获取当前敏感词的索引值 [中文]
	 * @Description: TODO
	 * @param @param arr
	 * @param @param i
	 * @param @param value
	 * @param @return   
	 * @return int  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static int getIndex(String[] arr, int i, String value) {
		int count = 0;
		for (int j = 0; j <= i; j++) {
			count += (arr[j].length());
		}
		return count + (i * value.length());
	}
	
	/**
	 * 获得包含的敏感词数量
	 * @Description: TODO
	 * @param @param recordContent
	 * @param @return   
	 * @return int  
	 * @throws
	 * @author 崔宝铖
	 * @date 2019年8月4日
	 */
	public static int getCount(String recordContent) {
		if(StringUtil.isEmpty(recordContent) || antistopMap.size() < 1 || !recordContent.contains("</font>")) return 0;
		String[] array = recordContent.split("</font>");
		if(array == null || array.length == 0) {
			return 0;
		}else{
			if(recordContent.endsWith("</font>")) {
				return array.length;
			}else{
				return array.length - 1;
			}
		}
	}
	
	public static int getAntistopSize() {
		return antistopMap.size();
	}
	
}
