package com.yiqi.crm.handle;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
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.bean.message.WxMpXmlOutNewsMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @desc: 文本类型消息处理-TEXT
 */

public class TextMsgHandler extends AbstractHandler {

    IWxReplyService wxReplyService;

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

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> map,
                                    WxMpService wxMpService,
                                    WxSessionManager sessionManager) throws WxErrorException {
        //公众号对话处理
        String keyWords = wxMessage.getContent();

        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);
    }


}