AutoreplyService.java 9.7 KB
/******************************************************************
 *
 *    Java Lib For JavaWeb, Powered By Shenzhen WEI YI KE JI .
 *
 *    Copyright (c) 2017-2027 Digital Telemedia Co.,Ltd
 *    http://www.d-telemedia.com/
 *
 *    Package:     com.w1hd.zzhnc.service.impl
 *
 *    Filename:    ProjectServiceImpl.java
 *
 *    Description: TODO(用一句话描述该文件做什么)
 *
 *    Copyright:   Copyright (c) 2017-2027
 *
 *    Company:     Theyeasy Telemedia Co.,Ltd
 *
 *    @author:     hm
 *
 *    @version:    1.0.0
 *
 *    Create at:   2017年10月22日 下午5:53:36
 *
 *    Revision:
 *
 *    2017年10月22日 下午5:53:36
 *        - first revision
 *
 *****************************************************************/
package com.w1hd.zzhnc.service;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.RandomUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.testng.util.Strings;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.w1hd.zzhnc.dao.AutoreplyDao;
import com.w1hd.zzhnc.model.Autoreply;
import com.w1hd.zzhnc.util.CommonUtil;
import com.w1hd.zzhnc.util.KeywordUtil;
import com.w1hd.zzhnc.util.PageResults;
import com.w1hd.zzhnc.util.StringUtil;
import com.w1hd.zzhnc.util.TulingUtil;
import com.w1hd.zzhnc.util.keyword.RegexKeywordFilter;
import com.w1hd.zzhnc.util.keyword.ReplaceStrategy;
import com.w1hd.zzhnc.vo.Vo_msg;

import tk.mybatis.mapper.entity.Example;

/**
 * @ClassName ProjectServiceImpl
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hm
 * @Date 2017年10月22日 下午5:53:36
 * @version 1.0.0
 */
@Service
public class AutoreplyService {

	Logger log = LoggerFactory.getLogger(AutoreplyService.class);
	@Autowired
	AutoreplyDao autoreplyDao;
	List<RegexKeywordFilter> filterList;

	static boolean inited = false;

	public void init(boolean hard) {
		if (hard) {
			inited = false;

		}
		init();
	}

	public void init() {
		if (inited) {
			return;
		}
		filterList = Lists.newArrayList();
		System.out.println("强制重新获得关键词");
		Example example = new Example(Autoreply.class);
		example.createCriteria().andEqualTo("deleted", 0);
		List<Autoreply> autoreplyList = autoreplyDao.selectByExample(example);
		autoreplyList.stream().forEach(e -> {
			String[] keys = e.getKeywords().split("\\|");
			RegexKeywordFilter filter = new RegexKeywordFilter();
			for (String key : keys) {
				System.out.println("keys" + key);
				filter.add(key);
			}
			filter.compile();
			filterList.add(filter);
		});
		inited = true;
	}

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	public Autoreply autoreply(String string) {

		System.out.println("关键字查找 ————>" + string);
		List<Set> sets = Lists.newArrayList();

		for (RegexKeywordFilter filter : filterList) {
			Set<String> keys = Sets.newHashSet();
			filter.replace(string, new ReplaceStrategy() {

				public String replaceWith(String keyword) {
					keys.add(keyword);
					sets.add(keys);

					return "";
				}
			});
		}

		Collections.sort(sets, new Comparator<Set>() {

			public int compare(Set o1, Set o2) {
				if (o1.size() > o2.size()) {
					return -1;
				}
				if (o1.size() == o2.size()) {
					return 0;
				}
				return 1;
			}
		});
		boolean eques = false;
		log.info("sets:{}", sets);
		
		if (sets.isEmpty()) {
			return null;
		}
		
		for (Set s : sets) {
			if (s.contains(string)) {
				eques = true;
			}
		}
		
		List<String> list = Lists.newArrayList();
		Set<String> set = sets.get(0);
		if (!eques) {
			list.addAll(sets.get(0));
		} else {
			list.add(string);
		}

		List<Autoreply> autoreplys = autoreplyDao.findByKeys(list, null);
		if (autoreplys.isEmpty()) {
			return null;
		}

		if (autoreplys.size() == 1) {
			return autoreplys.get(0);
		}

		Collections.sort(autoreplys, new Comparator<Autoreply>() {

			public int compare(Autoreply o1, Autoreply o2) {
				if (o1.getSort() < o2.getSort()) {
					return -1;
				}
				if (o1.getSort() == o2.getSort()) {
					return RandomUtils.nextInt(0, 2) - 1;
				}
				return 1;
			}
		});

		return autoreplys.get(0);

	}

	public PageResults<Autoreply> getAutoReplyList(Integer page, String keyword, Boolean isRedirectStaff,
			Integer projectId) {
		Example example = new Example(Autoreply.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("deleted", false);
		if (!Strings.isNullOrEmpty(keyword)) {
			criteria.andCondition(" (contents like \"%" + keyword + "%\" or keyWords like \"%" + keyword + "%\")");
		}
		if (projectId != null && projectId >= 0) {
			criteria.andEqualTo("projectId", projectId);
		}

		if (isRedirectStaff != null) {
			criteria.andEqualTo("isredirectstaff", isRedirectStaff);
		}

		RowBounds row = new RowBounds((page - 1) * 10, 10);
		example.setOrderByClause(" id desc ");
		List<Autoreply> list = autoreplyDao.selectByExampleAndRowBounds(example, row);
		int total = autoreplyDao.selectCountByExample(example);
		PageResults<Autoreply> pageresult = new PageResults<>();
		pageresult.setPage(page);
		pageresult.setPageSize(10);
		pageresult.setRows(list);
		pageresult.setTotal(total);
		return pageresult;
	}

	public String addAutoReply(String keywords, boolean isRedirectStaff, String content, Integer projectId,
			String projectName, Integer sort) {
		if (Strings.isNullOrEmpty(keywords))
			return "关键字设置不能为空";
		int row = 0;
		try {
			Autoreply reply = new Autoreply();
			reply.setContents(content);
			reply.setKeywords(keywords);
			reply.setDeleted(false);
			reply.setIsredirectstaff(isRedirectStaff);
			reply.setUpdatedtime(CommonUtil.getTime());
			reply.setProjectId(projectId);
			reply.setSort(sort);
			reply.setProjectName(projectName);
			row = autoreplyDao.insertSelective(reply);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("error:" + e.getMessage());
		}
		return row > 0 ? "ok" : "添加失败,数据异常";
	}

	public String updateAutoReply(Integer id, String keywords, boolean isRedirectStaff, String content,
			Integer projectId, String projectName, Integer sort) {
		if (StringUtil.isZearoOrNull(id))
			return "id 不能为空";
		if (Strings.isNullOrEmpty(keywords))
			return "关键字设置不能为空";
		Autoreply reply = autoreplyDao.selectByPrimaryKey(id);
		if (reply == null)
			return "修改失败,数据为空";
		reply.setContents(content);
		reply.setKeywords(keywords);
		reply.setIsredirectstaff(isRedirectStaff);
		reply.setUpdatedtime(CommonUtil.getTime());
		reply.setProjectId(projectId);
		reply.setProjectName(projectName);
		reply.setSort(sort);
		int row = autoreplyDao.updateByPrimaryKeySelective(reply);
		return row > 0 ? "ok" : "修改失败,数据异常";
	}

	public String deleteAutoReply(Integer id) {
		if (StringUtil.isZearoOrNull(id))
			return "id 不能为空";
		Autoreply reply = autoreplyDao.selectByPrimaryKey(id);
		if (reply == null)
			return "删除失败,数据为空";
		reply.setDeleted(true);
		int row = autoreplyDao.updateByPrimaryKeySelective(reply);
		return row > 0 ? "ok" : "删除失败,数据异常";
	}

	public Autoreply getAutoReply(Integer id) {
		if (StringUtil.isZearoOrNull(id))
			return null;
		return autoreplyDao.selectByPrimaryKey(id);
	}

	public String KeywordsToString() {
		Example example = new Example(Autoreply.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("deleted", false);
		List<Autoreply> list = autoreplyDao.selectByExample(example);

		// String
		// regex="(?<no1>[23|2莞|2]+)|(?<no2>[买房|东莞|万科]+)|(?<no3>[a|b|cc]+)|(?<no4>[客服|房价|咨询]+)";
		String result = "";
		StringBuffer sb = new StringBuffer();
		if (list != null && list.size() > 0) {
			// List<String> keywordsStr=list.stream().map(e -> new String(
			// (e.getKeywords() == null ? "" :
			// e.getKeywords()+"|"))).collect(Collectors.toList());
			for (Autoreply auto : list) {
				String group = "(?<no_" + auto.getId() + ">[" + auto.getKeywords() + "])" + ",";
				sb.append(group);
			}
			result = sb.toString().replaceAll(",|,", "|");
			if (result.endsWith("|")) {
				result = result.substring(0, result.length() - 1);
			}
			System.out.println(result);

		}
		KeywordUtil.setKeywordStr(result);
		return result;
	}

	public HashMap<Object, Object> autoreply(String content, Integer projectId, String fromUserName) {

		Autoreply autoreply = null;
		if (autoreply == null) {
			autoreply = autoreply(content);
		}

		HashMap<Object, Object> result = Maps.newHashMap();
		result.put("type", 2);
		if (autoreply == null) {
			Vo_msg answer = TulingUtil.getAnswer(content, fromUserName);
			autoreply = new Autoreply();
			if (answer != null && answer.code == 0) {
				String contents = answer.msg;
				autoreply.setContents(contents);
			} else {
				autoreply.setContents(getLastReply());
				;
			}
			autoreply.setIsredirectstaff(false);
			result.put("type", 3);
		}
		result.put("autoreply", autoreply);
		return result;
	}

	public static String getLastReply() {
		String allMsg = "你难住我了。。。/难过/大哭|世界那么大,我要出去走走/奋斗/奋斗/奋斗|....|今天天气真好呀!/龇牙/龇牙|让我想想.../阴险|我要提高下智商了/拳头/拳头/拳头|/抠鼻|/睡着|/睡着/睡着|skdfiqwkmqwemlqwdkl 哎呀,碰到键盘了。。。";
		String[] randomMsg = allMsg.split("\\|");
		int index = RandomUtils.nextInt(0, randomMsg.length - 1);
		return randomMsg[index];
	}

}