package com.yiqi.crm.handle;

import com.yiqi.crm.domain.WxReply;
import com.yiqi.crm.service.IWxReplyService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

import java.util.Map;

public class EventMsgHandler extends AbstractHandler{
    IWxReplyService wxReplyService;

    public static EventMsgHandler build(IWxReplyService wxReplyService) {
        EventMsgHandler handler = new EventMsgHandler();
        handler.wxReplyService = wxReplyService;
        return handler;
    }


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map,
                                    WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        String keyWords = wxMessage.getEventKey();

        WxReply wxReply = wxReplyService.handleKeyWordsText(keyWords);
        if (wxReply == null) {
            logger.warn("没有查到匹配的关键字回复");
            WxReply defaultReply = wxReplyService.getKeyWordsReplyListByDefault();
            if (defaultReply == null) {
                return null;
            }
            wxReplyService.countLookNumber(defaultReply);
            return WxMpXmlOutMessage
                    .TEXT()
                    .content(defaultReply.getPicTextDetailContent())
                    .fromUser(wxMessage.getToUser())
                    .toUser(wxMessage.getFromUser())
                    .build();
        }
        wxReplyService.countLookNumber(wxReply);
        return wxReplyService.getWxReplyInfo(wxReply, wxMessage, wxMpService);
    }


}
