package com.wechat.callback.handlers.event;

import javax.annotation.Resource;

import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.wechat.callback.handlers.ITencentRequestHandler;
import com.wechat.callback.passiveresponses.TextResponse;
import com.wechat.callback.tencentrequests.events.TBaseEventRequest;
import com.wechat.common.Constants;
import com.wechat.common.utils.XmlUtils;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.TdtgFoucsView;
import com.wechat.service.SubscribeService;

@Component("subscribeEvent")
public class SubscribeEventHandler implements ITencentRequestHandler {
    //订阅信息
    @Value("#{messageProperties['tmpl.subscribe']}")
    private String             tmplSubscribe;

    @Resource
    private SubscribeService subscribeService;
    
    @Override
    public TextResponse handle(String xml, Object obj) {
        TextResponse textResponse = new TextResponse();
        try {
            TBaseEventRequest req = XmlUtils.xml2obj(xml, TBaseEventRequest.class);
            if (req == null) {
                textResponse.setContent(InfoMsg.ERROR_SYSTEM_ERROR.getMsg());
            }
            else {
            	
            	//通过用户发送的信息，检索FAQ内容
                TdtgFoucsView contentDto = subscribeService.selectTxt();
                if (contentDto == null) {
                    // 没有抽取到数据
                    return null;
                }
                else {
                    StringBuffer sb = new StringBuffer();

                    // 将回车变成换行，腾讯不接收回车。
                    sb.append(contentDto.getFocusText().replaceAll(Constants.ENTER_LINE, Constants.NEXT_LINE));

                    StringBuffer sTemp = new StringBuffer(); 
                    sTemp.append(sb.toString());

                    textResponse.setContent(sb.toString()); 
                }          
            }
        }
        catch (Exception ex) {
            textResponse.setContent(InfoMsg.ERROR_SYSTEM_ERROR.getMsg());
            LogFactory.getLog(SubscribeEventHandler.class).error(ex);
        }
        return textResponse;
    }
    
    
}
