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 me.chanjar.weixin.mp.config.WxMpConfigStorage;

import java.util.Map;

/**
 * @desc 订阅处理
 */

public class SubscribeHandler extends AbstractHandler {

    IWxReplyService wxReplyService;

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

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map,
                                    WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        WxMpConfigStorage wxMpConfigStorage = wxMpService.getWxMpConfigStorage();
        this.logger.info("当前公众号AppId:[{}]；新关注用户 OPENID: [{}]", wxMpConfigStorage.getAppId(), wxMessage.getFromUser());
        //公众号对话处理

        WxReply subscribeReply = wxReplyService.getKeyWordsReplyListBySubscribe();
        if (subscribeReply == null) {
            return null;
        }
        wxReplyService.countLookNumber(subscribeReply);
        return WxMpXmlOutMessage
                .TEXT()
                .content(subscribeReply.getPicTextDetailContent())
                .fromUser(wxMessage.getToUser())
                .toUser(wxMessage.getFromUser())
                .build();
    }
}