package com.epalmpay.controller.apiweixin;

import com.epalmpay.commom.BaseController;
import com.epalmpay.entity.GroupWxKeyword;
import com.epalmpay.entity.GroupWxconfig;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.mapper.GroupWxconfigMapper;
import com.epalmpay.plugin.MyWxMpConfigStorage;
import com.epalmpay.service.group.IGroupService;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.weixin.IWxApiMemberService;
import com.epalmpay.service.weixin.IWxBaseService;
import com.epalmpay.service.weixin.impl.WxService;
import com.epalmpay.util.PageData;
import me.chanjar.weixin.common.util.crypto.SHA1;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
* 类名称:WechatController.java
* 类描述: 微信公众号开发入口
*
* @author zsj
* 创建时间:2017年5月18日
*/
@Controller
@RequestMapping(value = "/wechat")
public class WechatController extends BaseController {


@Autowired
protected WxService wxService;

@Autowired
protected IWxBaseService wxBaseService;

@Autowired
private IGroupService groupService;

@Autowired
private GroupWxconfigMapper groupWxconfigMapper;

@Autowired
@Lazy
private ITemplateMailSendService templateMailSendService;

@Resource
private IWxApiMemberService wxApiMemberService;

@RequestMapping(value = "serverno", method = {RequestMethod.GET, RequestMethod.POST})
public void index(HttpServletRequest request, HttpServletResponse response
) throws Exception {
logBefore(logger, "------------------------------------微信入口------------------------------------");
PageData pd = new PageData();
response.setContentType("text/html;charset=UTF-8");
pd = this.getPageData();
String signature = pd.getString("signature"); //微信加密签名
String timestamp = pd.getString("timestamp"); //时间戳
String nonce = pd.getString("nonce"); //随机数
String echostr = pd.getString("echostr"); //字符串
String groupId = pd.getString("groupId");
//所有使用wxService 前 设置 WxMpInMemoryConfigStorage
if (StringUtils.isBlank(groupId)) {
return;
}
logger.info("校验开始=======================");

try {
GroupWxconfig groupWxconfig = groupWxconfigMapper.selectByGroupId(Long.parseLong(groupId));
if(groupWxconfig != null){
logger.info("获取到配置了+==============================");
String desSignature = SHA1.gen(groupWxconfig.getAccessToken(), timestamp, nonce);
if(StringUtils.isNotEmpty(desSignature) && desSignature.equals(signature) && StringUtils.isNotEmpty(echostr)){
logger.info("进入返回阶段");
OutputStream os=response.getOutputStream();
os.write(URLEncoder.encode(echostr,"UTF-8").getBytes());
os.flush();
os.close();
}else{
logger.info("进入关键字____________________________________________");

MyWxMpConfigStorage wxMpConfigStorage= wxBaseService.getTokenByGroupId(Long.parseLong(groupId));
if(wxMpConfigStorage==null){
return ;
}else{
logger.info("已从缓存中获取到token");
}
wxService.setWxMpConfigStorage(wxMpConfigStorage);

String encryptType = StringUtils.isBlank(pd.getString("encrypt_type"))
? "raw"
: request.getParameter("encrypt_type");
request.getInputStream();

if ("raw".equals(encryptType)) {
// 明文传输的消息
String inMessageXml = readContent(request);
WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(inMessageXml);
String toUser = inMessage.getToUser();
String content = inMessage.getContent();
String fromUser = inMessage.getFromUser();
GroupWxconfig groupWxconfig2 = groupService.selectByTxidKey(toUser);
WxMpXmlOutMessage outMessage = this.wxService.route(inMessage);
if(outMessage!=null){
logger.info(outMessage+"------------"+"这是outMessage");
}else{
logger.info("------------"+"这是outMessage空");
}
if (groupWxconfig2 != null) {
Long groupid = groupWxconfig2.getGroupId();
GroupWxKeyword groupWxKeyword = new GroupWxKeyword();
groupWxKeyword.setGroupId(groupid);
groupWxKeyword.setKeyword(content);
GroupWxKeyword groupWxKeyword1 = groupService.getWxKeywordByKey(groupWxKeyword);
if (groupWxKeyword1 != null) {//如果该关键字有对应的回复
int replytype = groupWxKeyword1.getReplyType();
if (replytype == 0) {//文本回复
outMessage = WxMpXmlOutMessage.TEXT().content(groupWxKeyword1.getReply())
.fromUser(toUser)
.toUser(fromUser)
.build();
} else if (replytype == 1) {//图片回复
outMessage = WxMpXmlOutMessage.IMAGE().mediaId(groupWxKeyword1.getReply())
.fromUser(toUser)
.toUser(fromUser)
.build();
} else if (replytype == 2) {//图文消息
outMessage = WxMpXmlOutMessage.NEWS().addArticle(wxApiMemberService.sendArticlesMessage(groupWxKeyword1.getReply(), groupid))
.fromUser(toUser)
.toUser(fromUser)
.build();
}
}
}
String outXml = outMessage.toXml();
System.out.println(outXml);
response.getWriter().write(outXml);
return;
}
if ("aes".equals(encryptType)) {
// 是aes加密的消息
String msgSignature = pd.getString("msg_signature");
String inMessageXml = readContent(request);
WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(
inMessageXml, wxService.getWxMpConfigStorage(), timestamp, nonce,
msgSignature);
logBefore(logger, "消息解密后内容为" + inMessage.toString());
WxMpXmlOutMessage outMessage = this.wxService.route(inMessage);
response.getWriter().write(outMessage.toEncryptedXml(wxService.getWxMpConfigStorage()));
return;
}
logger.info("开发入口=======================");
}
}
logger.info("校验结束=======================");
} catch (Exception e) {
e.printStackTrace();
logger.info("这是异常消息"+e);
}

response.getWriter().println("不可识别的加密类型");
return;
}


private String readContent(HttpServletRequest request) throws IOException {
ServletInputStream sis = request.getInputStream();
// 取HTTP请求流长度
int size = request.getContentLength();
// 用于缓存每次读取的数据
byte[] buffer = new byte[size];
// 用于存放结果的数组
byte[] xmldataByte = new byte[size];
int count = 0;
int rbyte = 0;
// 循环读取
while (count < size) {
// 每次实际读取长度存于rbyte中
rbyte = sis.read(buffer);
for (int i = 0; i < rbyte; i++) {
xmldataByte[count + i] = buffer[i];
}
count += rbyte;
}
return new String(xmldataByte, "UTF-8");
}


@RequestMapping(value = "test", method = {RequestMethod.GET, RequestMethod.POST})
public void test(HttpServletRequest request, HttpServletResponse response, String memberId) throws Exception {

try {
templateMailSendService.sendMemberTemplate(Long.valueOf(memberId), BizEnum.WebTemplateType.template1.getType(), ROOT_HOME_URL, null);
} catch (Exception e) {
System.out.println("模板消息发送失败" + e);
e.printStackTrace();
}
return;
}


}