package com.lerx.v6.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Formatter;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ReflectionUtils;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.lerx.entities.SearchTotalModel;
import com.lerx.sys.util.StringUtil;

public class SearchUtil {
	
	
	/**
	 * 高亮显示文章
	 * 
	 * @param query
	 *            {@link org.apache.lucene.search.Query}
	 * @param data
	 *            未高亮的数据
	 * @param fields
	 *            需要高亮的字段
	 * @return 高亮数据
	 */
	public static List<SearchTotalModel> hightLight(Query query, List<SearchTotalModel> data, String... fields) {
		List<SearchTotalModel> result = new ArrayList<SearchTotalModel>();
		Formatter formatter = new SimpleHTMLFormatter("_lerx_search_key_s_", "_lerx_search_key_e_");
		QueryScorer queryScorer = new QueryScorer(query);
		Fragmenter fragmenter = new SimpleSpanFragmenter(queryScorer);
		Highlighter highlighter = new Highlighter(formatter, queryScorer);
		highlighter.setTextFragmenter(fragmenter);// 设置成高亮
		// 使用IK中文分词
		Analyzer analyzer = new IKAnalyzer();
		String content;
		for (SearchTotalModel s : data) {
			// 构建新的对象进行返回，避免页面错乱（我的页面有错乱）
//			s.setContent(StringUtil.nullAndHtmlFilter(s.getContent()));
			for (String fieldName : fields) {
				// 获得字段值，并给新的文章对象赋值
				Object fieldValue = ReflectionUtils
						.invokeMethod(BeanUtils.getPropertyDescriptor(SearchTotalModel.class, fieldName).getReadMethod(), s);
				ReflectionUtils.invokeMethod(BeanUtils.getPropertyDescriptor(SearchTotalModel.class, fieldName).getWriteMethod(),
						s, fieldValue);
				String hightLightFieldValue = null;
				try {
					hightLightFieldValue = highlighter.getBestFragment(analyzer, fieldName, String.valueOf(fieldValue));
				} catch (Exception e) {
					throw new RuntimeException("高亮显示关键字失败", e);
				}
				// 如果高亮成功则重新赋值
				if (hightLightFieldValue != null) {
					hightLightFieldValue=StringUtil.nullAndHtmlFilter(hightLightFieldValue);
					hightLightFieldValue=StringUtil.strReplace(hightLightFieldValue, "_lerx_search_key_s_", "<b style=\"color:red\">");
					hightLightFieldValue=StringUtil.strReplace(hightLightFieldValue, "_lerx_search_key_e_", "</b>");
					ReflectionUtils.invokeMethod(
							BeanUtils.getPropertyDescriptor(SearchTotalModel.class, fieldName).getWriteMethod(), s,
							hightLightFieldValue);
				}
			}
			// 赋值ID
			ReflectionUtils.invokeMethod(BeanUtils.getPropertyDescriptor(SearchTotalModel.class, "id").getWriteMethod(), s,
					s.getId());
			
			content = s.getContent();
			Pattern pattern = Pattern.compile("</p>(&nbsp;*)<p>");
			Matcher matcher = pattern.matcher(content);
			content = matcher.replaceAll(" ");

			// 任意空白字符
			pattern = Pattern.compile("</p>(\\s*)<p>");
			matcher = pattern.matcher(content);
			content = matcher.replaceAll(" ");
			
			content=StringUtil.htmlBlankTrim(content);
			s.setContent(content);
			
			String subject=s.getSubject();
			subject=StringUtil.htmlBlankTrim(subject);
			s.setSubject(subject);
			
			result.add(s);
		}
		return result;
	}
	

}
