package com.pcloud.book.keywords.biz.impl;

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.clock.check.BookClockCheck;
import com.pcloud.book.clock.dao.BookClockKeywordDao;
import com.pcloud.book.clock.dto.BookClockKeywordDTO;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.dao.AppTouchRecordDao;
import com.pcloud.book.group.dao.BookGroupClassifyDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.GroupQrcodeDao;
import com.pcloud.book.group.dao.JoinGroupCipherDao;
import com.pcloud.book.group.dto.*;
import com.pcloud.book.group.entity.AppTouchRecord;
import com.pcloud.book.group.entity.GroupQrcode;
import com.pcloud.book.group.enums.TouchTypeEnum;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.group.vo.GroupQrcodeBaseInfoVO;
import com.pcloud.book.keywords.biz.BookGuideBiz;
import com.pcloud.book.keywords.biz.BookKeywordBiz;
import com.pcloud.book.keywords.dao.BookGuideDao;
import com.pcloud.book.keywords.dao.BookGuideReplyDao;
import com.pcloud.book.keywords.dao.KeywordDao;
import com.pcloud.book.keywords.dto.GuideDTO;
import com.pcloud.book.keywords.dto.KeywordDTO;
import com.pcloud.book.keywords.dto.ReplyKeywordDTO;
import com.pcloud.book.keywords.entity.BookGuide;
import com.pcloud.book.keywords.entity.BookGuideReply;
import com.pcloud.book.keywords.entity.Keyword;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.keywords.vo.GuideVO;
import com.pcloud.book.keywords.vo.ReplyMessageVO;
import com.pcloud.book.keywords.vo.SetGuideVO;
import com.pcloud.book.keywords.vo.UpdateGuideVO;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.book.weixinclock.dao.WeixinClockGroupClassifyDao;
import com.pcloud.book.weixinclock.dto.WeixinClockDto;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
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.sdk.wxgroup.AddToGroupVO;
import com.sdk.wxgroup.SendGroupInviteVO;
import com.sdk.wxgroup.SendMessageTypeEnum;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lily
 * @date 2019/4/23 15:47
 */
@Slf4j
@Component("bookGuideBiz")
public class BookGuideBizImpl implements BookGuideBiz {
    @Autowired
    private BookGuideDao bookGuideDao;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private BookGuideReplyDao bookGuideReplyDao;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private BookKeywordBiz bookKeywordBiz;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private GroupQrcodeBiz groupQrcodeBiz;
    @Autowired
    private AppTouchRecordDao appTouchRecordDao;
    @Autowired
    private BookClockCheck bookClockCheck;
    @Autowired
    private BookClockKeywordDao bookClockKeywordDao;
    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;
    @Autowired
    private JoinGroupCipherDao joinGroupCipherDao;
    @Autowired
    private KeywordDao keywordDao;
    @Autowired
    private WeixinClockGroupClassifyDao weixinClockGroupClassifyDao;

    @ParamLog("同意加好友发送欢迎语")
    @Override
    public void sendGuide(AgreeAddUserDTO agreeAddUserDTO) {
        if(null == agreeAddUserDTO || StringUtil.isBlank(agreeAddUserDTO.getRobotWxId()) || StringUtil.isBlank(agreeAddUserDTO.getUserWxId())) {
            log.info("[同意加好友发送欢迎语] 参数为空 agreeAddUserDTO：{}", agreeAddUserDTO);
            return;
        }
        String cipher = agreeAddUserDTO.getCipher();
        if (StringUtil.isBlank(cipher)) {
            cipher = wechatGroupConsr.getCipherByRobotAndUserWxId(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId());
        }
        if (StringUtil.isBlank(cipher)) {
            log.info("[同意加好友发送欢迎语] 暗号为空 agreeAddUserDTO：{}", agreeAddUserDTO);
            return;
        }
        final JoinGroupCipherDTO dto = joinGroupCipherDao.getDTOByCipher(cipher);
        //获取群
        final String wxGroupId = bookGroupClassifyBiz.getWxGroupIdByClassifyIdAndWechatId(dto.getClassifyId(), dto.getWechatUserId());
        if (agreeAddUserDTO.getFirst() != null && agreeAddUserDTO.getFirst()) {
            // 如果是第一次就只发欢迎文案
            SendTextMessageVO vo = new SendTextMessageVO();
//            vo.setContent("你好，我是本书智能小助手，请回复你的进群暗号，获取本书资源服务，以及入群链接如果忘了进群暗号，请重新扫描书上的二维码，点击入群即可获取");
            vo.setContent("你好，我是本书智能小助手。请输入关键词获取本书相应的资源服务。");
            vo.setCode(SendMessageTypeEnum.SELF.getCode());
            vo.setWxId(agreeAddUserDTO.getRobotWxId());
            vo.setAltId(agreeAddUserDTO.getRobotWxId());
            vo.setWxGroupId(agreeAddUserDTO.getUserWxId());
            vo.setIp(agreeAddUserDTO.getIp());
            log.info("[同意加好友发送欢迎语] : {}", vo);
            WxGroupSDK.sendTextMessage(vo);
        }
        // 如果不是第一次就发关键词
        // 根据暗号获取分类id和bookGroupId推送关键词欢迎语
        List<KeywordDTO> keywords = bookKeywordBiz.listFiveKeyword(dto.getClassifyId(), dto.getBookGroupId());
        //发主打资源
        sendMainKeyword(keywords,agreeAddUserDTO,dto,wxGroupId);
        //发关键词列表
        SendWeixinRequestTools.sendKeywordsInfoToSelf(keywords, agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp());
        // 拉群
        final Integer peopleCounts = WxGroupSDK.getPeopleCounts(wxGroupId, agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getIp());
        // 邀请好友进群有次数限制，目前测试为每天只能拉30-40人就操作频繁，所以在此加判断，超过30人或者群人数超过30人就发送邀请链接
        final String num = JedisClusterUtils.get(BookConstant.WXGROUP_ADD_USER_NUM + agreeAddUserDTO.getRobotWxId());
        log.info("[同意加好友发送欢迎语] 拉群 agreeAddUserDTO:{}, wxGroupId:{}, peopleCounts:{}, num:{}", agreeAddUserDTO, wxGroupId, peopleCounts, num);
        if (StringUtil.isBlank(wxGroupId)) {
            log.info("[同意加好友发送欢迎语] 拉群 没有找到群 bookGroupClassifyBiz.getGroupQrcode4ClassifyWechat JoinGroupCipherDTO :{}", dto);
            return;
        }
        // 生产环境限制30，其它5和10，全部使用群链接
        final boolean isPro = "pro".equalsIgnoreCase(BookProps.getSystemEnv());
        if ((!StringUtil.isBlank(num) && Integer.parseInt(num) >= (isPro ? 30 : 5)) || peopleCounts >= (isPro ? 30 : 10)) {
            SendGroupInviteVO sendGroupInviteVO = new SendGroupInviteVO();
            sendGroupInviteVO.setAltId(agreeAddUserDTO.getRobotWxId());
            sendGroupInviteVO.setWxId(agreeAddUserDTO.getUserWxId());
            sendGroupInviteVO.setWxGroupId(wxGroupId);
            sendGroupInviteVO.setIp(agreeAddUserDTO.getIp());
            WxGroupSDK.sendGroupInvite(sendGroupInviteVO);
            log.info("[同意加好友发送欢迎语] 发送进群链接 sendGroupInviteVO：{}", sendGroupInviteVO);
            // 进群之后更新群qrCodeId
            updateQrcodeForCipher(wxGroupId, cipher, agreeAddUserDTO.getUserWxId());
            return;
        }
        AddToGroupVO vo1 = new AddToGroupVO();
        vo1.setWxGroupId(wxGroupId);
        vo1.setWxId(agreeAddUserDTO.getUserWxId());
        vo1.setAltId(agreeAddUserDTO.getRobotWxId());
        vo1.setIp(agreeAddUserDTO.getIp());
        log.info("[同意加好友发送欢迎语 拉群] AddToGroupVO ：{}", vo1);
        WxGroupSDK.addToGroup(vo1);
        // 进群之后更新群qrCodeId
        updateQrcodeForCipher(wxGroupId, cipher, agreeAddUserDTO.getUserWxId());
        // 拉一次+1
        if (StringUtil.isBlank(num)) {
            JedisClusterUtils.getSet(BookConstant.WXGROUP_ADD_USER_NUM + agreeAddUserDTO.getRobotWxId(), "1", 3600 * 24);
        } else {
            JedisClusterUtils.incr(BookConstant.WXGROUP_ADD_USER_NUM + agreeAddUserDTO.getRobotWxId());
        }
    }

    @ParamLog("进群之后更新群qrCodeId")
    private void updateQrcodeForCipher(String wxGroupId, String cipher, String userWxId){
        log.info("根据群id查询群信息wxGroupId", wxGroupId);
        GroupQrcodeDTO groupQrcodeInfo = groupQrcodeDao.getGroupQrcodeInfo(wxGroupId);
        log.info("根据群id查询群信息groupQrcodeInfo", groupQrcodeInfo.toString());
        log.info("更新暗号的群cipher=" + cipher + "wxId=" + userWxId + "qrcodeId=" + groupQrcodeInfo.getId());
        joinGroupCipherDao.updateQrcodeId(cipher, userWxId, groupQrcodeInfo.getId());
    }

    @ParamLog("发送主打资源")
    private void sendMainKeyword(List<KeywordDTO> keywords, AgreeAddUserDTO agreeAddUserDTO, JoinGroupCipherDTO dto, String wxGroupId) {
        if (!ListUtils.isEmpty(keywords)) {
            KeywordDTO keywordDTO = keywords.get(0);
            Keyword keyword = keywordDao.getById(keywordDTO.getKeywordId());
            GroupQrcodeDTO groupQrcodeInfo = groupQrcodeDao.getGroupQrcodeInfo(wxGroupId);
            if (keyword != null && groupQrcodeInfo != null) {
                ReplyKeywordDTO replyKeywordDTO = new ReplyKeywordDTO();
                BeanUtils.copyProperties(keyword, replyKeywordDTO);
                if (ReplyTypeEnum.APP.value.equals(replyKeywordDTO.getReplyType()) || ReplyTypeEnum.LINK.value.equals(replyKeywordDTO.getReplyType())) {
                    BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(dto.getBookGroupId());
                    AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(bookGroupDTO.getChannelId());
                    String linkUrl = SendWeixinRequestTools.splitUrlNew(accountSettingDto, replyKeywordDTO.getLinkUrl(), dto.getBookGroupId(), dto.getClassifyId(), groupQrcodeInfo.getId());
                    replyKeywordDTO.setLinkUrl(linkUrl);
                }
                SendWeixinRequestTools.sendKeywordMessage(replyKeywordDTO, agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp(), SendMessageTypeEnum.SELF.getCode());
            }
        }
    }

    @Override
    @ParamLog("新增欢迎语")
    @Transactional(rollbackFor = Exception.class)
    public void insertGuide(SetGuideVO setGuideVO, Long partyId) {
        if (setGuideVO.getClassifyId() == null) {
            setGuideVO.setClassifyId(0L);
        }
        checkReplyParam(setGuideVO.getReplyMessages());
        //获取图书相关信息
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(setGuideVO.getBookGroupId());
        if (bookGroupDTO == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "该社群码不存在！");
        }
        BookGuide bookGuide = new BookGuide();
        BeanUtils.copyProperties(setGuideVO, bookGuide);
        // 如果设置类型为按书设置则讲分类信息置空
        if (0 == setGuideVO.getSetType()) {
            setGuideVO.setClassifyId(0L);
        }
        bookGuide.setBookId(bookGroupDTO.getBookId());
        bookGuide.setChannelId(bookGroupDTO.getChannelId());
        bookGuide.setCreateUser(partyId);
        try {
            bookGuideDao.insert(bookGuide);
        } catch (DataIntegrityViolationException e) {
            throw new BookBizException(BookBizException.DB_DML_FAIL, "请勿重复设置！");
        }
        List<BookGuideReply> bookGuideReplies = setToBookGuideReply(setGuideVO.getReplyMessages(), bookGuide.getId(), partyId, bookGroupDTO.getChannelId());
        bookGuideReplyDao.insert(bookGuideReplies);
    }

    @ParamLog("设置回复参数")
    private List<BookGuideReply> setToBookGuideReply(List<ReplyMessageVO> replyMessages, Long bookGuideId, Long createUser, Long channelId) {
        List<BookGuideReply> bookGuideReplies = new ArrayList<>();
        List<Long> productIds = new ArrayList<>();
        for (ReplyMessageVO replyMessageVO : replyMessages) {
            BookGuideReply bookGuideReply = new BookGuideReply();
            BeanUtils.copyProperties(replyMessageVO, bookGuideReply);
            bookGuideReply.setBookGuideId(bookGuideId);
            bookGuideReply.setCreateUser(createUser);
            bookGuideReplies.add(bookGuideReply);
            if(ReplyTypeEnum.APP.value.equals(replyMessageVO.getReplyType()) && "PRODUCT".equalsIgnoreCase(replyMessageVO.getServeType())){
                productIds.add(replyMessageVO.getServeId());
            }
        }
        productConsr.productAutoOnShelves(channelId, productIds);
        return bookGuideReplies;
    }

    @ParamLog("校验参数")
    private void checkReplyParam(List<ReplyMessageVO> replyMessages) {
        if (ListUtils.isEmpty(replyMessages)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "请设置入群欢迎语");
        }
        if (replyMessages.size() > 5) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "入群欢迎语超出5个限制");
        }
    }

    @Override
    @ParamLog("更新欢迎语")
    @Transactional(rollbackFor = Exception.class)
    public void updateGuide(UpdateGuideVO updateGuideVO, Long partyId) {
        List<ReplyMessageVO> replyMessages = updateGuideVO.getReplyMessages();
        if (ListUtils.isEmpty(replyMessages)) {
            //删除欢迎语回复
            bookGuideReplyDao.deleteByGuideId(updateGuideVO.getId());
            //删除欢迎语
            bookGuideDao.deleteById(updateGuideVO.getId());
        }else{
            if (replyMessages.size() > 5) {
                throw new BookBizException(BookBizException.PARAM_IS_NULL, "入群欢迎语超出5个限制");
            }
            checkReplyParam(updateGuideVO.getReplyMessages());
            //获取欢迎语基本信息
            BookGuide bookGuideOld = bookGuideDao.getById(updateGuideVO.getId());
            if(bookGuideOld == null){
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "欢迎语不存在");
            }
            BookGuide bookGuide = new BookGuide();
            BeanUtils.copyProperties(updateGuideVO, bookGuide);
            bookGuideDao.update(bookGuide);
            //更新回复消息
            bookGuideReplyDao.deleteByGuideId(updateGuideVO.getId());
            List<BookGuideReply> bookGuideReplies = setToBookGuideReply(updateGuideVO.getReplyMessages(), bookGuide.getId(), partyId, bookGuideOld.getChannelId());
            bookGuideReplyDao.insert(bookGuideReplies);
        }
    }

    @Override
    @ParamLog("根据社群码获取欢迎语")
    public GuideVO getGuideByBookGroup(Long bookGroupId) {
        GuideVO guideVO = bookGuideDao.getGuideByBookGroup(bookGroupId);
        if (guideVO == null) {
            return new GuideVO();
        }
        //获取社群码回复内容
        List<ReplyMessageVO> messages = bookGuideReplyDao.getReplyMessage(guideVO.getId());
        guideVO.setReplyMessages(messages);
        return guideVO;
    }

    @Override
    @ParamLog("根据分类获取欢迎语")
    public GuideVO getGuideByClassify(Long classifyId) {
        GuideVO guideVO = bookGuideDao.getGuideByClassify(classifyId);
        if (guideVO == null) {
            return new GuideVO();
        }
        //获取社群码回复内容
        List<ReplyMessageVO> messages = bookGuideReplyDao.getReplyMessage(guideVO.getId());
        guideVO.setReplyMessages(messages);
        return guideVO;
    }


    @Override
    @ParamLog("推送欢迎语消息")
    public void sendGuideMessage(PushAddUserMessageDTO pushAddUserMessageDTO) {
        final String weixinGroupId = pushAddUserMessageDTO.getWeixinGroupId();
        //通过群id获取对应基本信息
        GroupClassifyQrcodeDTO classifyQrcodeInfo = bookGroupClassifyBiz.getClassifyQrcodeInfo(weixinGroupId);
        if(classifyQrcodeInfo == null){
            return;
        }
        //获取该书是否设置推送公众号
        GuideDTO bookGuide = getBaseInfo(null, classifyQrcodeInfo.getBookGroupId());
        //获取该分类是否设置过欢迎语
        GuideDTO classifyGuide = getBaseInfo(classifyQrcodeInfo.getClassifyId(), classifyQrcodeInfo.getBookGroupId());
        //获取推送消息机器人
        String robotId = pushAddUserMessageDTO.getRobotId();
        if(StringUtil.isBlank(robotId)) {
            log.info("[关键词消息回复] robotId is null robotId:{},weixinGroupId:{}", robotId, weixinGroupId);
            robotId = wechatGroupConsr.getRobotIdByGroupId(weixinGroupId);
        }
        // 判断是否黑名单
        final Boolean kickUser = wechatGroupConsr.isKickUser(pushAddUserMessageDTO.getNickName(), weixinGroupId);
        log.info("[推送欢迎语消息]:pushAddUserMessageDTO:{},kickUser：{}", pushAddUserMessageDTO, kickUser);
        // 在群，且非黑名单
//        canSend = canSend && !kickUser;
        if (null != kickUser && kickUser) {
            log.info("[推送欢迎语消息]:不推送");
            return;
        }
        List<ReplyMessageVO> replyMessages = null;
        if (classifyGuide != null) {
            replyMessages = bookGuideReplyDao.getReplyMessage(classifyGuide.getId());
        } else if (bookGuide != null) {
            replyMessages = bookGuideReplyDao.getReplyMessage(bookGuide.getId());
        }
        //获取公众号基本信息
        AccountSettingDto wechatInfo = qrcodeSceneConsr.getWechatInfo(classifyQrcodeInfo.getChannelId());
        //获取关键词信息（改成10个了） 刘娜需求 1001282 群不推送关键词
        List<KeywordDTO> keywords = bookKeywordBiz.listFiveKeyword(classifyQrcodeInfo.getClassifyId(), classifyQrcodeInfo.getBookGroupId());
        Boolean isHaveKeywords = !ListUtils.isEmpty(keywords);
        final Boolean groupRobot = wechatGroupConsr.isGroupRobot(robotId);
        log.info("[wechatGroupConsr.isGroupRobot] robotId:{} groupRobot:{}", robotId, groupRobot);
        if (ListUtils.isEmpty(replyMessages)) {
            //获取群名称
            GroupQrcodeBaseInfoVO groupInfo = groupQrcodeBiz.getBaseById(classifyQrcodeInfo.getGroupQrcodeId());
            //推送消息 刘娜需求 1001282 群不推送关键词
            // 若非之前的机器人则不回复普通关键词
            SendWeixinRequestTools.sendDefaultMessage(groupInfo == null ? "" : groupInfo.getGroupName(), robotId, weixinGroupId, isHaveKeywords, pushAddUserMessageDTO.getIp());
        } else {
            //处理链接
            handleUrl(replyMessages, wechatInfo, classifyQrcodeInfo);
            //推送消息
            SendWeixinRequestTools.sendGuideMessage(replyMessages, robotId, weixinGroupId, pushAddUserMessageDTO.getIp(), SendMessageTypeEnum.GROUP.getCode());
            //新增欢迎语应用触发记录
            addGuideAppTouchRecord(replyMessages,weixinGroupId,classifyQrcodeInfo.getBookGroupId(),classifyQrcodeInfo.getClassifyId());
        }
        //获取关键词信息（改成10个了）刘娜需求 1001282 群不推送关键词
        if (groupRobot) {
            SendWeixinRequestTools.sendKeywordsInfo(keywords, robotId, weixinGroupId, pushAddUserMessageDTO.getIp());
        }
        //如果设置了群学习报告，加一个群学习报告的关键词
        pushLearningReport(classifyQrcodeInfo,robotId, weixinGroupId, pushAddUserMessageDTO.getIp());
        if (bookGuide != null && bookGuide.getIsRecommend() != null && bookGuide.getIsRecommend() == 1) {
            //推送公众号消息
            SendWeixinRequestTools.sendAccountMessage(weixinGroupId, bookGuide.getRecommendLanguage(), robotId, wechatInfo, pushAddUserMessageDTO.getIp());
        }
        //校验该群是否与微信群打卡有关
        /*List<Long> bookClockInfoIdList = bookClockCheck.checkGroupIsClock(classifyQrcodeInfo);
        if(!ListUtils.isEmpty(bookClockInfoIdList)){
            Map<String,Object> paramMap = new HashMap<>();
            int i = 0;
            List<BookClockKeywordDTO> bookClockKeywordDTOList = new ArrayList<>();
            for (Long bookClockInfoId:bookClockInfoIdList) {
                i++;
                if(i >= 5){
                    break;
                }
                paramMap.put("bookClockInfoId",bookClockInfoId);
                List<BookClockKeywordDTO> bookClockKeywordDTOS = bookClockKeywordDao.getKeywordsByInfoId(paramMap);
                bookClockKeywordDTOList.addAll(bookClockKeywordDTOS);
                if(i%2 == 0){
                    log.info("欢迎语中推送关键词信息,bookClockKeywordDTOList="+bookClockKeywordDTOList);
                    SendWeixinRequestTools.sendClockKeywordsInfo(bookClockKeywordDTOList, robotId, weixinGroupId, pushAddUserMessageDTO.getIp());
                    bookClockKeywordDTOList.clear();
                }else if(i == bookClockInfoIdList.size()){
                    SendWeixinRequestTools.sendClockKeywordsInfo(bookClockKeywordDTOList, robotId, weixinGroupId, pushAddUserMessageDTO.getIp());
                    bookClockKeywordDTOList.clear();
                }

            }
        }*/
    }

    @ParamLog("推关学习报告/猜谜语关键词消息")
    private void pushLearningReport(GroupClassifyQrcodeDTO classifyQrcodeInfo, String robotId, String weixinGroupId, String ip) {
        Boolean reportOpen = false;
        Boolean riddleOpen = false;
        Boolean clockOpen = false;
        if (classifyQrcodeInfo.getHasOpenLearningReport() != null && classifyQrcodeInfo.getHasOpenLearningReport()) {
            reportOpen = true;
        }
        GroupQrcode groupQrcode = groupQrcodeDao.getGroupQrcodeByGroupId(weixinGroupId);
        if (null != groupQrcode && groupQrcode.getRiddleOpen()) {
            riddleOpen = true;
        }
        WeixinClockDto weixinClockDto = weixinClockGroupClassifyDao.getClockBaseInfoByClassify(classifyQrcodeInfo.getClassifyId());
        if (null != weixinClockDto && !StringUtil.isEmpty(weixinClockDto.getClockGuide()) && !StringUtil.isEmpty(weixinClockDto.getClockKeyword())) {
            clockOpen = true;
        }
        if (reportOpen && riddleOpen && clockOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【学习报告】\n    获取个人专属学习报告，与群成员PK元气值\n" +
                    "关键词【猜谜语】\n    猜谜语，大家一起玩，看谁666\n" +
                    "关键词【" + weixinClockDto.getClockKeyword() + "】\n    " + weixinClockDto.getClockGuide(), robotId, weixinGroupId, ip);
        } else if (reportOpen && riddleOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【学习报告】\n    获取个人专属学习报告，与群成员PK元气值\n" +
                    "关键词【猜谜语】\n    猜谜语，大家一起玩，看谁666", robotId, weixinGroupId, ip);
        } else if (reportOpen && clockOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【学习报告】\n    获取个人专属学习报告，与群成员PK元气值\n" +
                    "关键词【" + weixinClockDto.getClockKeyword() + "】\n    " + weixinClockDto.getClockGuide(), robotId, weixinGroupId, ip);
        } else if (riddleOpen && clockOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【猜谜语】\n    猜谜语，大家一起玩，看谁666" +
                    "关键词【" + weixinClockDto.getClockKeyword() + "】\n    " + weixinClockDto.getClockGuide(), robotId, weixinGroupId, ip);
        } else if (clockOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【" + weixinClockDto.getClockKeyword() + "】\n    " + weixinClockDto.getClockGuide(), robotId, weixinGroupId, ip);
        } else if (reportOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【学习报告】\n    获取个人专属学习报告，与群成员PK元气值", robotId, weixinGroupId, ip);
        } else if (riddleOpen) {
            SendWeixinRequestTools.sendTextMessage("关键词【猜谜语】\n    猜谜语，大家一起玩，看谁666", robotId, weixinGroupId, ip);
        }
    }

    @Override
    public Map<String, Object> getGuideMessage(String weixinGroupId, String wexinGroupName) {
        Map<String, Object> map = new HashMap<>();
        List<ReplyMessageVO> replyMessages = new ArrayList<>();
        //通过群id获取对应基本信息
        GroupClassifyQrcodeDTO classifyQrcodeInfo = bookGroupClassifyBiz.getClassifyQrcodeInfo(weixinGroupId);
        if (classifyQrcodeInfo == null && !StringUtil.isEmpty(wexinGroupName)) {
            classifyQrcodeInfo = bookGroupClassifyDao.getClassifyQrcodeInfoByName(wexinGroupName);
        }
        if (null == classifyQrcodeInfo) {
            return map;
        }
        map.put("qrCodeUrl", classifyQrcodeInfo.getQrCodeUrl());
        //获取该书是否设置推送公众号
        GuideDTO bookGuide = getBaseInfo(null, classifyQrcodeInfo.getBookGroupId());
        //获取该分类是否设置过欢迎语
        GuideDTO classifyGuide = getBaseInfo(classifyQrcodeInfo.getClassifyId(), classifyQrcodeInfo.getBookGroupId());
        if (classifyGuide != null) {
            replyMessages = bookGuideReplyDao.getReplyMessage(classifyGuide.getId());
        } else if (bookGuide != null) {
            replyMessages = bookGuideReplyDao.getReplyMessage(bookGuide.getId());
        }
        //获取公众号基本信息
        AccountSettingDto wechatInfo = qrcodeSceneConsr.getWechatInfo(classifyQrcodeInfo.getChannelId());
        //获取关键词信息（改成10个了）
        List<KeywordDTO> keywords = bookKeywordBiz.listFiveKeyword(classifyQrcodeInfo.getClassifyId(), classifyQrcodeInfo.getBookGroupId());
        map.put("keywords", keywords);
        Boolean isHaveKeywords = !ListUtils.isEmpty(keywords);
        if (ListUtils.isEmpty(replyMessages)) {
            replyMessages = new ArrayList<>();
            ReplyMessageVO replyMessageVO = new ReplyMessageVO();
            String content = "";
            //获取群名称
            GroupQrcodeBaseInfoVO groupInfo = groupQrcodeBiz.getBaseById(classifyQrcodeInfo.getGroupQrcodeId());
            String groupName = groupInfo.getGroupName();
            if (StringUtil.isEmpty(groupName)) {
                content += " 欢迎加入本群!";
            } else {
                content += " 欢迎加入" + groupName + "！";
            }
            if (isHaveKeywords) {
                content = content + "本群目的为学习交流和学习辅导，线上资源和工具为图书的增值服务，可根据实际情况配合图书一起使用。凭以下关键词领取任务或资源：";
            }
            replyMessageVO.setContent(content);
            replyMessages.add(replyMessageVO);
        } else {
            //处理链接
            handleUrl(replyMessages, wechatInfo, classifyQrcodeInfo);
        }
        map.put("reply", replyMessages);
        return map;
    }

    /**
     * 新增欢迎语应用触发记录
     */
    private void addGuideAppTouchRecord(List<ReplyMessageVO> replyMessages, String weixinGroupId, Long bookGroupId, Long classifyId) {
        for (ReplyMessageVO replyMessageVO:replyMessages){
            if (ReplyTypeEnum.APP.value.equals(replyMessageVO.getReplyType())){
                AppTouchRecord appTouchRecord = new AppTouchRecord();
                appTouchRecord.setServeId(replyMessageVO.getServeId());
                appTouchRecord.setServeType(replyMessageVO.getServeType());
                appTouchRecord.setTouchType(TouchTypeEnum.GUIDE.value);
                appTouchRecord.setBookGroupId(bookGroupId);
                appTouchRecord.setClassifyId(classifyId);
                GroupQrcode groupQrcode = groupQrcodeDao.getGroupQrcodeByGroupId(weixinGroupId);
                if (groupQrcode != null) {
                    appTouchRecord.setQrcodeId(groupQrcode.getId());
                }
                appTouchRecord.setWeixinGroupId(weixinGroupId);
                appTouchRecordDao.insert(appTouchRecord);
            }
        }
    }

    @ParamLog("处理地址")
    private void handleUrl(List<ReplyMessageVO> replyMessages, AccountSettingDto accountSettingDto, GroupClassifyQrcodeDTO groupClassifyQrcodeDTO) {
        if (ListUtils.isEmpty(replyMessages)) {
            return;
        }
        for (ReplyMessageVO replyMessageVO : replyMessages) {
            if (ReplyTypeEnum.APP.value.equals(replyMessageVO.getReplyType()) || ReplyTypeEnum.LINK.value.equals(replyMessageVO.getReplyType())) {
                String linkUrl = SendWeixinRequestTools.splitUrlNew(accountSettingDto, replyMessageVO.getLinkUrl(), groupClassifyQrcodeDTO.getBookGroupId(), groupClassifyQrcodeDTO.getClassifyId(), groupClassifyQrcodeDTO.getGroupQrcodeId());
                replyMessageVO.setLinkUrl(linkUrl);
            }
        }
    }

    @ParamLog("获取欢迎设置基本信息")
    private GuideDTO getBaseInfo(Long classifyId, Long bookGroupId) {
        if (classifyId == null) {
            classifyId = 0L;
        }
        return bookGuideDao.getBaseInfo(classifyId, bookGroupId);
    }
}
