package com.wechat.callback.handlers.event;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.wechat.callback.handlers.ITencentRequestHandler;
import com.wechat.callback.passiveresponses.BasePassiveResponse;
import com.wechat.callback.passiveresponses.TextResponse;
import com.wechat.callback.tencentrequests.events.BaseEventRequest;
import com.wechat.callback.tencentrequests.events.TBaseEventRequest;
import com.wechat.common.utils.XmlUtils;

/**
 * 事件处理类
 */
@Component("eventHandler")
public class EventReceivedHandler implements ITencentRequestHandler {
    @Autowired
    @Qualifier("clickEvent")
    ITencentRequestHandler clickEventHandler;
    
//    @Autowired
//    @Qualifier("unSubscribeEvent")
//    ITencentRequestHandler unSubscribeHandler;
//    
    @Autowired
    @Qualifier("subscribeEvent")
    ITencentRequestHandler subscribeHandler;
    
    @Autowired
    @Qualifier("templateSendFinishEvent")
    ITencentRequestHandler templateSendFinishHandler;

    //log
    protected static final Log log = LogFactory.getLog(EventReceivedHandler.class);
    
    @Override
    public BasePassiveResponse handle(String xml, Object obj) {
        try {
            BaseEventRequest.EventType eventType = XmlUtils.xml2obj(xml, TBaseEventRequest.class).getEventType();
            //事件类型为空时
            if (eventType == null) {
                log.warn("事件类型为空!");
                return BasePassiveResponse.NULL_RESPONSE;
            }
            
            switch (eventType) {
                //按钮处理
                case CLICK: {
                    return clickEventHandler.handle(xml, null);
                }
                //取消关注事件
//                case UNSUBSCRIBE:{
//                    return unSubscribeHandler.handle(xml,null);
//                }
                //关注事件
                case SUBSCRIBE:{
                    return subscribeHandler.handle(xml,null);
                }
                //模板消息发送回执事件
                case TEMPLATESENDJOBFINISH:{
                    return templateSendFinishHandler.handle(xml,null);
                }

                default: {
                    log.warn("未定义的事件类型:[" + eventType + "]");
                    return TextResponse.NULL_RESPONSE;
                }
            }
        } catch (Exception ex) {
            log.error("事件分发处理异常");
            log.error(ex);
            return TextResponse.SERVER_ERROR();
        }
    }
}
