package com.pcloud.book.mq.topic;

import com.pcloud.book.clock.biz.BookClockKeywordBiz;
import com.pcloud.book.clock.check.BookClockCheck;
import com.pcloud.book.clock.dto.BookClockInfoDTO;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.keywords.biz.BookKeywordBiz;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.wechatgroup.message.dto.SendTextDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lily
 * @date 2019/5/6 11:01
 */
@Slf4j
@Component("wxGroupSendTextListener")
@RabbitListener(queues = MQTopicConumer.WXGROUP_SEND_TEXT)
public class WxGroupSendTextListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(WxGroupSendTextListener.class);


    @Autowired
    private BookKeywordBiz bookKeywordBiz;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private BookClockKeywordBiz bookClockKeywordBiz;
    @Autowired
    private BookClockCheck bookClockCheck;

    /**
     * 接收微信用户进群消息
     */
    @ParamLog("接收用户发送文本消息")
    @RabbitHandler
    public void onMessage(SendTextDTO sendTextDTO) throws BizException {
        try {
            if (sendTextDTO == null || sendTextDTO.getWechatGroupId() == null || sendTextDTO.getTextContent() == null)
                return;
            String wechatUserId = sendTextDTO.getWechatUserId();
            //校验是否机器人账号
            List<String> allRobotWxIds = wechatGroupConsr.listAllRobotWxId();
            if (!ListUtils.isEmpty(allRobotWxIds) && !allRobotWxIds.contains(wechatUserId) && !StringUtil.isEmpty(sendTextDTO.getTextContent())) {
                BookClockInfoDTO bookClockInfoDTO = bookClockCheck.checkKeywordIsClock(sendTextDTO.getTextContent().trim(), sendTextDTO.getWechatGroupId());
                if(null != bookClockInfoDTO){
                    bookClockKeywordBiz.sendKeywordMessage(bookClockInfoDTO, wechatUserId,sendTextDTO.getWechatGroupId(),sendTextDTO.getWxId(),sendTextDTO.getIp());
                }else{
                    final long l = System.currentTimeMillis();
                    bookKeywordBiz.sendKeywordMessage(sendTextDTO.getTextContent().trim(), sendTextDTO.getWechatGroupId(), wechatUserId, sendTextDTO.getWxId(), sendTextDTO.getIp());
                    log.info("[接收用户发送文本消息] 总耗时:{}ms ", System.currentTimeMillis() - l);
                }
            }
        } catch (Exception e) {
            LOGGER.error("接收用户发送文本消息失败" + e.getMessage(), e);
        }
    }
}
