package com.pcloud.book.mq.topic;

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.dto.GroupClassifyQrcodeDTO;
import com.pcloud.book.guide.dto.PcloudGuideDelayDto;
import com.pcloud.book.guide.mapper.PcloudRobotSilenceMapper;
import com.pcloud.book.keywords.biz.BookKeywordBiz;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.book.reading.biz.ReadingActivityBiz;
import com.pcloud.book.riddle.biz.RiddleRecordBiz;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.book.weixinclock.biz.WeixinClockBiz;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.wechatgroup.message.dto.SendTextDTO;
import com.sdk.wxgroup.SendMessageTypeEnum;
import lombok.extern.slf4j.Slf4j;
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.Date;
import java.util.List;

import static com.pcloud.book.guide.constant.PcloudGuideRedisConstant.PCLOUD_GUIDE_SUFFIX;

/**
 * @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 RiddleRecordBiz riddleRecordBiz;
    @Autowired
    private WeixinClockBiz weixinClockBiz;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;
    @Autowired
    private ReadingActivityBiz readingActivityBiz;
    @Autowired
    private PcloudRobotSilenceMapper pcloudRobotSilenceMapper;

    /**
     * 接收微信用户进群消息
     */
    @ParamLog("接收用户发送文本消息")
    @RabbitHandler
    public void onMessage(SendTextDTO sendTextDTO) throws BizException {
        try {
            if (sendTextDTO == null || sendTextDTO.getWechatGroupId() == null || sendTextDTO.getTextContent() == null)
                return;
            String wechatUserId = sendTextDTO.getWechatUserId();
            // 更新群人数和群名称
            changeGroupInfo(sendTextDTO);
            // 缄默设置处理
            silenceProcess(sendTextDTO);
            //校验是否机器人账号
            List<String> allRobotWxIds = wechatGroupConsr.listAllRobotWxId();
            if (!ListUtils.isEmpty(allRobotWxIds) && !allRobotWxIds.contains(wechatUserId) && !StringUtil.isEmpty(sendTextDTO.getTextContent())) {
                Boolean flag = weixinClockBiz.checkWeixinClockKeyword(sendTextDTO.getTextContent().trim(), sendTextDTO.getWechatGroupId());
                if(flag && SendMessageTypeEnum.GROUP.getCode().equals(sendTextDTO.getCode())){
                    weixinClockBiz.sendKeywordMessage(sendTextDTO.getTextContent().trim(), wechatUserId, sendTextDTO.getWechatGroupId(), sendTextDTO.getWxId(), sendTextDTO.getIp());
                } else {
                    bookKeywordBiz.sendKeywordMessage(sendTextDTO);
                }
                //猜谜语
                riddleRecordBiz.riddleProcess(sendTextDTO);
                //共读活动
                readingActivityBiz.receiveKeyWord(sendTextDTO);
            }
        } catch (Exception e) {
            LOGGER.error("接收用户发送文本消息失败" + e.getMessage(), e);
        }
    }

    /**
     * 机器人缄默设置处理
     */
    private void silenceProcess(SendTextDTO sendTextDTO) {
        // 个人号消息 用户发送:wechatCreateUser!=wxId,小号发送wechatCreateUser=wxId
        if (SendMessageTypeEnum.SELF.getCode().equals(sendTextDTO.getCode()) && !sendTextDTO.getWechatUserId().equals(sendTextDTO.getWxId())) {
            // 从缓存中获取缄默信息
            if(JedisClusterUtils.hexists(sendTextDTO.getWxId()+PCLOUD_GUIDE_SUFFIX,sendTextDTO.getWechatUserId())){
                Integer duration = pcloudRobotSilenceMapper.getSilenceDurationByRobotWxId(sendTextDTO.getWxId());
                if (duration == null) {
                    duration = 0;
                }
                String hget = JedisClusterUtils.hget(sendTextDTO.getWxId() + PCLOUD_GUIDE_SUFFIX, sendTextDTO.getWechatUserId());
                PcloudGuideDelayDto pcloudGuideDelayDto = JSONObject.parseObject(hget, PcloudGuideDelayDto.class);
                pcloudGuideDelayDto.setSendTime(new Date());
                // duration
                pcloudGuideDelayDto.setDuration(duration);
                JedisClusterUtils.hset(sendTextDTO.getWxId()+PCLOUD_GUIDE_SUFFIX,sendTextDTO.getWechatUserId(),JSONObject.toJSONString(pcloudGuideDelayDto));
            }
        }
    }

    /**
     * 更新群人数和群名称
     * @param sendTextDTO 群消息DTO
     */
    private void changeGroupInfo(SendTextDTO sendTextDTO){
        // 异步修改群名称
        String finalRobotId = sendTextDTO.getWxId();
        ThreadPoolUtils.OTHER_THREAD_POOL.execute(() -> {
            final String weixinGroupId = sendTextDTO.getWechatGroupId();
            final String ip = sendTextDTO.getIp();
            GroupClassifyQrcodeDTO classifyQrcodeInfo = bookGroupClassifyBiz.getClassifyQrcodeInfo(weixinGroupId);
            // 处理更新群人数
            bookKeywordBiz.updateGroupPeopleCount(weixinGroupId, sendTextDTO.getMemberCount(), classifyQrcodeInfo);
            bookKeywordBiz.checkGroupName(weixinGroupId, classifyQrcodeInfo.getGroupName(), finalRobotId, ip);
        });
    }


}
