package cn.com.shdmt.service;
import cn.com.shdmt.BizConstants;
import cn.com.shdmt.entity.*;
import cn.com.shdmt.framework.util.MessageUtil;
import cn.com.shdmt.framework.util.weXinUtil;
import cn.com.shdmt.framework.wexinmessage.Article;
import cn.com.shdmt.framework.wexinmessage.NewsMessage;
import cn.com.shdmt.framework.wexinmessage.TextMessage;
import cn.com.shdmt.repository.ConcernedCustomerDao;
import cn.com.shdmt.repository.CustomDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by yaoyao on 2015/3/13.
*/
@Component
@Transactional
public class WeXinCoreService {
@Autowired
private ConcernedCustomerDao concernedCustomerDao;
@Autowired
private AccessTokenService accessTokenService;
@Autowired
private CustomDao customDao;
@Autowired
private WeXinEventService weXinEventService;
@Autowired
private CodeService codeService;
@Autowired
private SmsService smsService;
@Autowired
private WelMsgService welMsgService;
@Autowired
private OnlineOrderFilesService onlineOrderFilesService;
@Autowired
private KeyReplyService keyReplyService;
@Value("#{appProperties[‘wexin.config.service.app_id‘]}")
private String serviceAppId;
@Value("#{appProperties[‘wexin.config.service.secret‘]}")
private String serviceSecret;
@Value("#{appProperties[‘upload.config.uploadPath‘]}")
private String uploadPath;
@Value("#{appProperties[‘upload.config.fileURLPrefix‘]}")
private String fileURLPrefix;
public String processRequest(String msg) {
String respMessage = null;
try {
// 默认返回的文本消息内容
String respContent = "请求处理异常,请稍候尝试!";
// xml请求解析
Map<String, String> requestMap = MessageUtil.parseXml(msg);
System.out.println("Event==" + requestMap.get("Event"));
// 发送方帐号(open_id)
String open_id = requestMap.get("FromUserName");
// 公众帐号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
// 回复文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(open_id);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setFuncFlag(0);
// 文本消息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
String content = requestMap.get("Content");
respContent = "欢迎关注地面通";
//得到他发送的消息
String c = content.toLowerCase();
KeyReplyEntity keyReplyEntity =keyReplyService.findByKeyAndIsDeleted(c,Boolean.FALSE);
if(keyReplyEntity!=null){
respContent = keyReplyEntity.getReply();
}
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// 图片消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
//如果绑定了 则上传该工单
List<ConcernedCustomerEntity> concernedCustomerEntities = concernedCustomerDao.findByOpenidAndType(open_id, 1);
if (concernedCustomerEntities.size() > 0) {
ConcernedCustomerEntity concernedCustomerEntity = concernedCustomerEntities.get(0);
List<CustomerEntity> customerEntities = customDao.findByConcernedCustomer(concernedCustomerEntity);
if (customerEntities.size() > 0) {
//保存这张图片
String fileDate = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTimeInMillis());
File dir = new File(uploadPath + "/wexin/" + fileDate + "/");
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
System.out.println("创建路径失败");
}
}
String mediaId = requestMap.get("MediaId");
weXinUtil.downloadMedia(getServiceToken(), mediaId, uploadPath + "/wexin/" + fileDate + "/");
String imageUrl = "wexin/"+fileDate+"/"+mediaId+".jpg";
OnlineOrderFilesEntity onlineOrderFilesEntity =new OnlineOrderFilesEntity();
onlineOrderFilesEntity.setProductId(imageUrl);
onlineOrderFilesEntity.setCustomerId(customerEntities.get(0).getId());
onlineOrderFilesService.save(onlineOrderFilesEntity);
respContent = "上传工单成功";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}else{
respContent = "<a href=\"http://yaoyao66123.eicp.net/customCenter/tologin?openid="+open_id+"/\">请点击绑定</a>";
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
}
}
// 地理位置消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
}
// 链接消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";
}
// 音频消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是音频消息!";
}
// 事件推送
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
// 事件类型
String eventType = requestMap.get("Event");
// 自定义菜单点击事件
if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {
attention(open_id);
NewsMessage newsMessage = buildmessage(open_id, toUserName, 0);
// 将图文消息对象转换成xml字符串
respMessage = MessageUtil.newsMessageToXml(newsMessage);
} else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
// 取消关注,用户接受不到我们发送的消息了,可以在这里记录用户取消关注的日志信息
canelAttention(open_id);
} else if (eventType.equalsIgnoreCase(MessageUtil.EVENT_TYPE_CLICK)) {
// 事件KEY值,与创建自定义菜单时指定的KEY值对应
String eventKey = requestMap.get("EventKey");
/* if (eventKey.equals("CONTACT_US")) {
NewsMessage newsMessage = buildmessage(open_id, toUserName, 1);
// 将图文消息对象转换成xml字符串
respMessage = MessageUtil.newsMessageToXml(newsMessage);
}*/
}
/*else if (eventType.equalsIgnoreCase("VIEW")) {
// 事件KEY值,与创建自定义菜单时指定的KEY值对应
String eventKey = requestMap.get("EventKey");
String e = "EventKey=https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx186f9fb0382ee5c5&redirect_uri=http://yaoyao66123.eicp.net/customCenter/ordersearch&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
if (eventKey.equals(e)) {
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
}
}*/
}
} catch (Exception e) {
e.printStackTrace();
respMessage = "有异常了。。。";
}
return respMessage;
}
private void attention(String open_id) {
List<ConcernedCustomerEntity> list = concernedCustomerDao.findByOpenid(open_id);
if (list.size() > 0) {
//之前关注过
ConcernedCustomerEntity concernedCustomerEntity = list.get(0);
concernedCustomerEntity.setCancelledtime(null);
concernedCustomerEntity.setIsconcerned(Boolean.TRUE);
}
}
private NewsMessage buildmessage(String open_id, String toUserName, Integer type) {
// 创建图文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(open_id);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
List<WelMsgEntity> welMsgEntities = welMsgService.findAll(type);
List<WelMsgEntity> needlist = new ArrayList<WelMsgEntity>();
if (welMsgEntities.size() > 0) {
for (WelMsgEntity welMsgEntity : welMsgEntities) {
if (needlist.size() < 8) {
needlist.add(welMsgEntity);
}
}
}
List<Article> articleList = new ArrayList<Article>();
for (WelMsgEntity welMsgEntity : needlist) {
Article article = new Article();
article.setTitle(welMsgEntity.getTitle());
article.setDescription(welMsgEntity.getDescription());
article.setPicUrl(fileURLPrefix + welMsgEntity.getPicurl());
article.setUrl(welMsgEntity.getUrl());
articleList.add(article);
}
// 设置图文消息个数
newsMessage.setArticleCount(articleList.size());
// 设置图文消息包含的图文集合
newsMessage.setArticles(articleList);
return newsMessage;
}
private void canelAttention(String open_id) {
List<ConcernedCustomerEntity> list = concernedCustomerDao.findByOpenid(open_id);
if (list.size() > 0) {
ConcernedCustomerEntity concernedCustomerEntity = list.get(0);
concernedCustomerEntity.setCancelledtime(new Timestamp(System.currentTimeMillis()));
concernedCustomerEntity.setIsconcerned(Boolean.FALSE);
concernedCustomerDao.save(concernedCustomerEntity);
}
}
public String getServiceToken() {
AccessTokenEntity accessTokenEntity = accessTokenService.findByType(BizConstants.WEXIN_SERVICE_NUM);
//如果没有查到 则 创建 获取token
if (accessTokenEntity == null) {
accessTokenEntity = new AccessTokenEntity();
Map result = weXinUtil.getAccessToken(serviceAppId, serviceSecret, null);
if (!result.containsKey("no-change")) {
accessTokenEntity.setType(BizConstants.WEXIN_SERVICE_NUM);
accessTokenEntity.setAccessToken(result.get("token").toString());
accessTokenEntity.setExceedTime(Timestamp.valueOf(result.get("exceedTime").toString()));
accessTokenService.save(accessTokenEntity);
}
} else {
Map result = weXinUtil.getAccessToken(serviceAppId, serviceSecret, accessTokenEntity.getExceedTime());
if (!result.containsKey("no-change")) {
//去更新
accessTokenEntity.setAccessToken(result.get("token").toString());
accessTokenEntity.setExceedTime(Timestamp.valueOf(result.get("exceedTime").toString()));
accessTokenService.save(accessTokenEntity);
}
}
return accessTokenEntity.getAccessToken();
}
}