package com.iamberry.wechat.handles.wechat.event;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.iamberry.wechat.face.wechat.WeChatService;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.SignUtil;

/**
 * @company	深圳爱贝源科技有限公司
 * @website www.iamberry.com
 * @author 	献
 * @tel		18271840547
 * @date	2016年11月3日
 * @explain	微信相关handler
 */
@Controller
@RequestMapping(value="/wechatBinding")
public class WeChatHandler {
	
	private static Logger logger = LoggerFactory.getLogger(WeChatHandler.class);
	
	@Autowired
	private WeChatService weChatService;

	@RequestMapping(method=RequestMethod.GET)
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 微信加密签名,必须非空
		String signature = request.getParameter("signature");
		if (signature == null) {
			response.getWriter().print("connect Server! signature Error!");
			return;
		}
		// 时间戳,必须非空
		String timestamp = request.getParameter("timestamp");
		if (timestamp == null) {
			response.getWriter().print("connect Server! timestamp Error!");
			return;
		}
		// 随机数,必须非空
		String nonce = request.getParameter("nonce");
		if (nonce == null) {
			response.getWriter().print("connect Server! nonce Error!");
			return;
		}
		// 随机字符串,必须非空
		String echostr = request.getParameter("echostr");
		if (echostr == null) {
			response.getWriter().print("connect Server! echostr Error!");
			return;
		}
		String token = NameUtils.token;
		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce, token)) {
			out.print(echostr);
		} else {
			response.getWriter().print("connect Server! check signature Error!");
			return;
		}
		out.close();
	}
	
	@RequestMapping(method=RequestMethod.POST)
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        
        String respMessage = "哎呀 ~ 服务器开小差啦！";
        try {
        	Map<String, String> requestMap = com.iamberry.wechat.utils.MessageUtil.parseXml(request);
			respMessage = weChatService.processRequest(requestMap.get("FromUserName"), 
					requestMap.get("ToUserName"), requestMap.get("MsgType"), 
					requestMap.get("CreateTime"), requestMap.get("Content"), 
					requestMap.get("Event"), requestMap.get("Ticket"), 
					requestMap.get("EventKey"));
		} catch (Exception e) {
			logger.error(e.getMessage() + "," + e.getLocalizedMessage());
		}
        // 响应消息
        PrintWriter out = response.getWriter();
        out.print(respMessage);
        out.close();
	}
}