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.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;

/**
 * description ： 微信交互handler
 * @author 何秀刚
 * create date：2016年3月10日
 */
@Controller
@RequestMapping(value="/wechatBinding")
public class WeChatHandler {
	@Autowired
	private WeChatService weChatService;
	public void setWeChatService(WeChatService weChatService) {
		this.weChatService = weChatService;
	}

	@RequestMapping(method=RequestMethod.GET)
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String echostr = request.getParameter("echostr");
		if (echostr == null) {
			response.getWriter().print("connect Server! echostr Error!");
			return;
		}
		PrintWriter out = response.getWriter();
		out.print(echostr);
		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) {
			e.printStackTrace();
		}
        // 响应消息
        PrintWriter out = response.getWriter();
        out.print(respMessage);
        out.close();
	}
}