package com.wechat.callback.processors;

import java.util.List;

import javax.annotation.Resource;

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.Value;
import org.springframework.stereotype.Component;

import com.wechat.callback.passiveresponses.NewsResponse;
import com.wechat.callback.passiveresponses.TextResponse;
import com.wechat.callback.tencentrequests.UserSentTextRequest;
import com.wechat.common.CommonHelper;
import com.wechat.common.Constants;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.TdtgFaqInfo;
import com.wechat.service.FaqService;

/**
 * FAQ问答回复
 *
 * @author la-lin
 */
@Component
public class FaqAnswerProcessor {
    //faq 内容
    @Value("#{configProperties['url.client.faqContent']}")
    private String             urlFaqContent;
    
    //根域名
    @Value("#{configProperties['url.base']}")
    private String             urlBase;
    
    //图片根目录
    @Value("#{configProperties['url.img.base']}")
    private String             urlImgBase;
  
    @Autowired
    private CommonHelper         commonHelper;
    
    @Resource
    private FaqService faqService;

    protected static final Log log = LogFactory.getLog(FaqAnswerProcessor.class);


    public TextResponse getFAQTextResponse(UserSentTextRequest req) {
        TextResponse rsp = new TextResponse();
        try {
            String resContent = ""; // 回复用户的信息 
            
    		//通过用户发送的信息，检索FAQ内容
            TdtgFaqInfo faqInfo = faqService.getInfoByKeyWord(req.getContent());
            if (faqInfo == null) {
                // 没有抽取到FAQ数据
                return null;
            }
            else {
                StringBuffer sb = new StringBuffer();
                // FAQ标题
                sb.append(faqInfo.getTitle());
                // 换行
                sb.append(Constants.NEXT_LINE);
                // FAQ内容
                // 将回车变成换行，腾讯不接收回车。
                sb.append(faqInfo.getContent().replaceAll(Constants.ENTER_LINE, Constants.NEXT_LINE));

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


                // 返回文字长度超出时需要截取文字(),截取文字后需要增加查看更多链接
                if (sb.toString().getBytes("UTF-8").length > 2048) {
                    sb = sb.delete(599, sb.length()).append("......");
                }
                resContent = sb.toString();
            }

            rsp.setContent(resContent);
        }
        catch (Exception e) {
            log.error(e);
            rsp.setContent(InfoMsg.ERROR_SYSTEM_ERROR.getMsg());//系统异常
        }
        return rsp;
    }

    
    /**
     * 通过用户发送的信息,取得FAQ的问题
     * 
     * @param userSentTextRequest 用户发送的信息
     * @return
     */
    public List<TdtgFaqInfo> getAllInfoByKeyWord(UserSentTextRequest userSentTextRequest) throws Exception {
	    //通过用户发送的信息，检索FAQ内容
	    List<TdtgFaqInfo> faqInfoList = faqService.getAllInfoByKeyWord(userSentTextRequest.getContent());
	    return faqInfoList;    
    }

    /**
     * 获取图文消息
     * @param faqListResponse
     * @return
     */
    public NewsResponse getFAQNewsResponse(List<TdtgFaqInfo> faqListResponse) {
        try {
            NewsResponse newsResponse = new NewsResponse();

            for (TdtgFaqInfo faqInfo : faqListResponse) {
                if (newsResponse.getArticleCount() < 10) {
                    if (faqInfo.getMsgType() == 1) {
                        String sNewsUrl;
                        if (StringsUtils.isEmpty(faqInfo.getNewsUrl())) {
                            sNewsUrl = urlFaqContent + "?id=" + faqInfo.getFaqId().toString();
                        } else {
                            sNewsUrl = faqInfo.getNewsUrl();
                        }
                        newsResponse.appendArticle(faqInfo.getTitle(), faqInfo.getNewsDesc(),  commonHelper.getImgUrl(faqInfo.getNewsPicurl()), sNewsUrl);
                    }
                }
            }
            return newsResponse;
        } catch (Exception e) {
            log.error("message", e);
            return new NewsResponse();
        }
    }
}