package com.wechat.common.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wechat.model.dto.BaiDuFilterDto;
import com.wechat.model.dto.BaiDuTokenDto;
import com.wechat.service.AuthorizedService;
import com.wechat.service.BaiDuTokenService;

@Component
public class BaiDuKeyWordFilerUtils {

	@Value("#{configProperties['baidu.keyWord.filer.url']}")
	private String filerUrl;

	@Autowired
	private BaiDuTokenService baiDuTokenService;

	private StringBuilder replaceAll;// 初始化
	private String replceStr = "*";
	private int replceSize = 20000;
	private List<String> arrayList = Lists.newArrayList();
	private Set<String> sensitiveWordSet;// 包含的敏感词列表，过滤掉重复项
	private List<String> sensitiveWordList;// 包含的敏感词列表，包括重复项，统计次数

	public String filterKeWord(String context) {
		if (StringsUtils.isEmpty(context)) {
			return context;
		}
		String filterContext = context;
		BaiDuTokenDto tokenDto = baiDuTokenService.getBaiDuAccessToken();
		String url = filerUrl + "access_token=" + tokenDto.getAccess_token();
		Map<String, String> req = Maps.newHashMap();
		req.put("content", context);
		HttpClientUtils httpClientUtils = new HttpClientUtils();
		String json = httpClientUtils.doPost(url, req, "UTF-8");
		JSONObject parseObject = JSONObject.parseObject(json);
		String result = parseObject.getString("result");
		JSONObject parseObject1 = JSONObject.parseObject(result);
		String reject = parseObject1.getString("reject");
		List<BaiDuFilterDto> list = JSONObject.parseArray(reject, BaiDuFilterDto.class);
		for (BaiDuFilterDto baiDuFilterDto : list) {
			arrayList.addAll(baiDuFilterDto.getHit());
		}
		replaceAll = new StringBuilder(replceSize);
		for (int x = 0; x < replceSize; x++) {
			replaceAll.append(replceStr);
		}
		filterContext = filterInfo(context);
		return filterContext;
	}

	/**
	 * @param str
	 *            将要被过滤信息
	 * @return 过滤后的信息
	 */
	private String filterInfo(String str) {
		sensitiveWordSet = new HashSet<String>();
		sensitiveWordList = new ArrayList<>();
		StringBuilder buffer = new StringBuilder(str);
		HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>(arrayList.size());
		String temp;
		for (int x = 0; x < arrayList.size(); x++) {
			temp = arrayList.get(x);
			int findIndexSize = 0;
			for (int start = -1; (start = buffer.indexOf(temp, findIndexSize)) > -1;) {
				// System.out.println("###replace="+temp);
				findIndexSize = start + temp.length();// 从已找到的后面开始找
				Integer mapStart = hash.get(start);// 起始位置
				if (mapStart == null || (mapStart != null && findIndexSize > mapStart))// 满足1个，即可更新map
				{
					hash.put(start, findIndexSize);
					// System.out.println("###敏感词："+buffer.substring(start, findIndexSize));
				}
			}
		}
		Collection<Integer> values = hash.keySet();
		for (Integer startIndex : values) {
			Integer endIndex = hash.get(startIndex);
			// 获取敏感词，并加入列表，用来统计数量
			String sensitive = buffer.substring(startIndex, endIndex);
			// System.out.println("###敏感词："+sensitive);
			if (!sensitive.contains("*")) {// 添加敏感词到集合
				sensitiveWordSet.add(sensitive);
				sensitiveWordList.add(sensitive);
			}
			buffer.replace(startIndex, endIndex, replaceAll.substring(0, endIndex - startIndex));
		}
		hash.clear();
		return buffer.toString();
	}

}
