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.dto.WakeUpInfoDto;
import com.pcloud.book.guide.mapper.PcloudRobotSilenceMapper;
import com.pcloud.book.keywords.biz.BookGuideBiz;
import com.pcloud.book.keywords.biz.BookKeywordBiz;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotDao;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.personalstage.constant.PersonalStageConstant;
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.DateUtils;
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.AgreeAddUserDTO;
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;
import static com.pcloud.book.guide.constant.PcloudGuideRedisConstant.PCLOUD_ROBOT_WAKE_UP_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 BookGuideBiz bookGuideBiz;

    /**
     * 接收微信用户进群消息
     */
    @ParamLog("接收用户发送文本消息")
    @RabbitHandler
    public void onMessage(SendTextDTO sendTextDTO) throws BizException {
        try {
            if (sendTextDTO == null || sendTextDTO.getWechatGroupId() == null || sendTextDTO.getTextContent() == null)
                return;
            String wechatUserId = sendTextDTO.getWechatUserId();
            // TODO
            //入口，监听内容如果是重置，记录当前时间存入缓存，并调用统一加好友发送欢迎语接口
            /*这里这要过滤掉阶段消息吗？因为延迟队列里面已经有了上次加好友的一些待发送的阶段消息，
            在掉一遍这个接口又会产生新的阶段消息，所以要过滤掉之前的阶段消息，需要在队列的消息里面加上一个创建时间
            根据缓存的这个时间去过滤，如果队列的这个人的阶段消息的创建时间在缓存的时间之前，则不发送
            ，如果之后或者相等则发送



             */
            if("重置体验".equals(sendTextDTO.getTextContent())){
                Date date=new Date();
                String dateStr = DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss");
                //把这个时间存入缓存

                String key= PersonalStageConstant.PERSONAL_STAGE_SEND_TIME+sendTextDTO.getWxId();
                JedisClusterUtils.set(key,dateStr);
                AgreeAddUserDTO agreeAddUserDTO=new AgreeAddUserDTO();
                agreeAddUserDTO.setIp(sendTextDTO.getIp());
                //agreeAddUserDTO.setNickName(sendTextDTO.get);
                agreeAddUserDTO.setRobotWxId( sendTextDTO.getWxId());
                agreeAddUserDTO.setUserWxId(sendTextDTO.getWechatGroupId());
                agreeAddUserDTO.setFirst(false);
                bookGuideBiz.sendGuideNew(agreeAddUserDTO);
                return;
            }
            // 更新群人数和群名称
            changeGroupInfo(sendTextDTO);
            // 缄默设置处理
            bookKeywordBiz.silenceProcess(sendTextDTO.getWechatUserId(), sendTextDTO.getCode(), sendTextDTO.getWxId());
            // 机器人自动唤醒
            bookKeywordBiz.robotWakeUp(sendTextDTO.getWechatUserId(), sendTextDTO.getIp(), sendTextDTO.getCode(), sendTextDTO.getWxId());
            //校验是否机器人账号
            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);
        }
    }


    /**
     * 更新群人数和群名称
     * @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);
        });
    }


}
