package com.wechat.callback.handlers.text;

import java.util.List;

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.processors.CustomerServiceProcessor;
import com.wechat.callback.processors.FaqAnswerProcessor;
import com.wechat.callback.tencentrequests.UserSentTextRequest;
import com.wechat.common.utils.XmlUtils;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.TdtgFaqInfo;

@Component
@Qualifier("textHandler")
public class TextMessageReceivedHandler implements ITencentRequestHandler {
    protected static final Log log = LogFactory.getLog(TextMessageReceivedHandler.class);

    @Autowired
    FaqAnswerProcessor faqProcessor;
    
    
    @Autowired
    CustomerServiceProcessor         serviceProcessor;
    
    @Override
    public BasePassiveResponse handle(String xml, Object obj) {
        UserSentTextRequest req = XmlUtils.xml2obj(xml, UserSentTextRequest.class);
        try {
	        if (req == null) {
	            log.error("*********文本反馈XML解析异常********");
	            return new TextResponse(InfoMsg.ERROR_SYSTEM_ERROR.getMsg());
	        }
	        else {
				log.info("Text Input:[" + req.getContent() + "]");
				List<TdtgFaqInfo> faqInfoList = faqProcessor.getAllInfoByKeyWord(req);
				
				if(faqInfoList.size() > 0)
				{
					boolean isNewsMsg = false;
					for (TdtgFaqInfo faqInfo : faqInfoList) {
						if (faqInfo.getMsgType() == 1) {
							isNewsMsg = true;
							break;
						}
					}
					if (faqInfoList.size() == 0 || isNewsMsg == false) {
						// 返回文本消息
						log.info("Return text response");
						return faqProcessor.getFAQTextResponse(req);
					} else {
						// 返回图文消息
						log.info("Return news response");
						return faqProcessor.getFAQNewsResponse(faqInfoList);
					}
				}
				else
				{
					//faq查不到发送给客服
	                return serviceProcessor.getCustomerService(req.getFromUserName());
				}

			}
		}
	   catch (Exception e) {
		   return new TextResponse(InfoMsg.ERROR_SYSTEM_ERROR.getMsg());
		}
    }
}
