package com.wechat.callback.controller;

import java.io.IOException;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wechat.callback.handlers.ITencentRequestHandler;
import com.wechat.callback.passiveresponses.BasePassiveResponse;
import com.wechat.callback.passiveresponses.TextResponse;
import com.wechat.callback.tencentrequests.BaseRequest;
import com.wechat.callback.tencentrequests.TBaseRequest;
import com.wechat.common.utils.DateUtils;
import com.wechat.common.utils.JacksonUtils;
import com.wechat.common.utils.SignUtils;
import com.wechat.common.utils.StringsUtils;
import com.wechat.common.utils.XmlUtils;
import com.wechat.global.base.BaseController;
import com.wechat.global.message.InfoMsg;

/**
 * 核心请求处理类 
 * @author jt-wu
 */
@Controller
@RequestMapping("weChatCallBack")
public class MasterRequestController extends BaseController {
    @Autowired
    @Qualifier("eventHandler")
    ITencentRequestHandler eventHandler;

    @Autowired
    @Qualifier("textHandler")
    ITencentRequestHandler textHandler;

    
    // 与接口配置信息中的Token一致
    @Value("#{configProperties['token']}")
    private  String    token;


    @RequestMapping(value = "main", method = RequestMethod.GET)
    @ResponseBody
    protected String doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");
        
        /** 判断是否是微信接入激活验证，只有首次接入验证时才会收到echostr参数，此时需要验证后把它返回 */  
        // 随机字符串  
        String echostr = request.getParameter("echostr");  
        if (echostr != null && echostr.length() > 1) {  
            // 微信加密签名  
            String signature = request.getParameter("signature");  
            // 时间戳  
            String timestamp = request.getParameter("timestamp");  
            // 随机数  
            String nonce = request.getParameter("nonce");  

            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
            if (SignUtils.checkSignature(token, signature, timestamp, nonce)) {  
                return echostr;  
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }
    
    
    /**
     * 回调主接口
     */
    @RequestMapping(value = "main", method = RequestMethod.POST)
    @ResponseBody
    public BasePassiveResponse callbackEntrance(@RequestBody String xml) {
        try {
            log.info("*********↓回调主入口XML↓*********");
            log.info(xml);
            log.info("*********↑回调主入口XML↑*********");
            if (xml.trim().length() == 0) {
                return new TextResponse(InfoMsg.ERROR_EMPTY_REQUEST.getMsg());
            }
            TBaseRequest req = XmlUtils.xml2obj(xml, TBaseRequest.class);
            if (req == null) throw new RuntimeException("Xml parse error");
            BaseRequest.MsgTypeEnum msgType = req.getMsgType();
            BasePassiveResponse rsp = null;
            switch (msgType) {
                case TEXT: {
                    rsp = textHandler.handle(xml, null);
                    break;
                }
                case EVENT: {
                    rsp = eventHandler.handle(xml, null);
                    break;
                }
                default: {
                	log.warn("未定义的入口消息类型:[" + msgType + "]");
                    return TextResponse.NULL_RESPONSE;
                }
            }
            
            if (rsp == BasePassiveResponse.NULL_RESPONSE)
            {
            	return null;
            }

            if (rsp == null)
            {
            	rsp = TextResponse.SERVER_ERROR();
            }
                
            rsp.setFromUserName(req.getToUserName());
            rsp.setToUserName(req.getFromUserName());
            rsp.setCreateTime(StringsUtils.parseLong(DateUtils.getCurrentDate().getTime()));
            log.debug("Responded: " + JacksonUtils.beautifulSerialize(rsp));
            return rsp;
        } catch (Exception ex) {
            log.error("腾讯回调入口解析异常：", ex);
            return TextResponse.SERVER_ERROR();
        }
    }
}
