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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupAppBiz;
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.BookGroupFriendGuideDao;
import com.pcloud.book.group.dao.GroupQrcodeDao;
import com.pcloud.book.group.dao.JoinGroupCipherDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.GroupClassifyQrcodeDTO;
import com.pcloud.book.group.dto.GroupQrcodeDTO;
import com.pcloud.book.group.dto.JoinGroupCipherDTO;
import com.pcloud.book.group.dto.PushAddUserMessageDTO;
import com.pcloud.book.group.dto.SendDefaultGuideMessageDTO;
import com.pcloud.book.group.dto.SendGuideMessageDTO;
import com.pcloud.book.group.entity.AppTouchRecord;
import com.pcloud.book.group.entity.BookGroupFriendGuide;
import com.pcloud.book.group.entity.GroupQrcode;
import com.pcloud.book.group.entity.JoinGroupCipher;
import com.pcloud.book.group.enums.CipherTypeEnum;
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.guide.dto.PcloudGuideDelayDto;
import com.pcloud.book.guide.entity.PcloudGuide;
import com.pcloud.book.guide.mapper.PcloudGuideMapper;
import com.pcloud.book.guide.mapper.PcloudGuideMessageMapper;
import com.pcloud.book.guide.vo.PcloudGuideMessageVO;
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.KeywordStatusDTO;
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.pcloudkeyword.biz.PcloudRobotBiz;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotDao;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotWelcomeDao;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobotWelcome;
import com.pcloud.book.personalstage.biz.PersonalStageBiz;
import com.pcloud.book.personalstage.biz.PersonalStageJumpBiz;
import com.pcloud.book.personalstage.constant.PersonalStageConstant;
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.httpclient.UrlUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.wechatgroup.message.dto.AgreeAddUserDTO;
import com.sdk.wxgroup.RobotProcessTypeEnum;
import com.sdk.wxgroup.SendArticleMessageVO;
import com.sdk.wxgroup.SendFileVO;
import com.sdk.wxgroup.SendGroupInviteVO;
import com.sdk.wxgroup.SendMessageTypeEnum;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

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

/**
 * @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 GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;
    @Autowired
    private JoinGroupCipherDao joinGroupCipherDao;
    @Autowired
    private KeywordDao keywordDao;
    @Autowired
    private WeixinClockGroupClassifyDao weixinClockGroupClassifyDao;
    @Autowired
    private BookGroupAppBiz bookGroupAppBiz;
    @Autowired
    private BookGroupFriendGuideDao bookGroupFriendGuideDao;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private PcloudRobotBiz pcloudRobotBiz;
    @Autowired
    private PcloudGuideMessageMapper pcloudGuideMessageMapper;
    @Autowired
    private PcloudRobotDao pcloudRobotDao;
    @Autowired
    private PcloudGuideMapper pcloudGuideMapper;
    @Autowired
    private PersonalStageBiz personalStageBiz;

    @Autowired
    private PcloudRobotWelcomeDao pcloudRobotWelcomeDao;



    @Value("${wechat.group.link.prefix}")
    private String wechatGroupLinkPrefix;
    @Autowired
    private PersonalStageJumpBiz personalStageJumpBiz;
    @Autowired
    private SendWeixinRequestTools sendWeixinRequestTools;

    @ParamLog("同意加好友发送欢迎语")
    @Override
    public void sendGuide(AgreeAddUserDTO agreeAddUserDTO) {
        if(agreeAddUserDTO.getRobotType()==null||agreeAddUserDTO.getRobotType()==1) {
            if (null == agreeAddUserDTO || StringUtil.isBlank(agreeAddUserDTO.getRobotWxId()) || StringUtil.isBlank(agreeAddUserDTO.getUserWxId())) {
                log.info("[同意加好友发送欢迎语] 参数为空 agreeAddUserDTO：{}", agreeAddUserDTO);
                return;
            }
            String cipher = agreeAddUserDTO.getCipher();
            //如果暗号为空，表示直接加好友，需要发送统一欢迎语
            if (cipher == null) {
                //发送配置欢迎语 create by lihao 2020.2.7
                //判断是否是平台端小号
                PcloudRobot pcloudRobot = pcloudRobotDao.getByWxId(agreeAddUserDTO.getRobotWxId());
                if (pcloudRobot != null) {
                    //删除需求单记录
                    personalStageJumpBiz.deletePaperRecord(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId());
                    pcloudRobotBiz.sendWelcomeReply(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp());
                    //好友引导语
                    sendFriendGuide(null, agreeAddUserDTO);
                    if (personalStageBiz.isPersonalStageUser(agreeAddUserDTO.getRobotWxId())) {
                        personalStageBiz.createAddUserStageUser(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp());
                    }
                    return;
                }
                SendTextMessageVO vo = new SendTextMessageVO();
                vo.setContent("终于和您见面了!\n请告诉我您在读哪本书？\n如果您在上一步中复制了暗号，\n您可以把暗号粘贴在下方对话框内，以微信聊天的形式发给我。" +
                        "\n如果在上一步中，没有提示您复制暗号，\n您可以在【书中二维码旁】找到本书的简称及年份，\n在下方对话框内输入本书简称及年份，以微信聊天的形式发给我。");
                vo.setCode(SendMessageTypeEnum.SELF.getCode());
                vo.setWxId(agreeAddUserDTO.getRobotWxId());
                vo.setAltId(agreeAddUserDTO.getRobotWxId());
                vo.setWxGroupId(agreeAddUserDTO.getUserWxId());
                vo.setIp(agreeAddUserDTO.getIp());
                vo.setRobotProcessType(RobotProcessTypeEnum.WELCOME);
                vo.setCounts(1);
                vo.setIndex(0);
                vo.setMessageGroupId(UUID.randomUUID().toString());
                wechatGroupConsr.sendMessage(JSON.toJSONString(vo));
                return;
            }
            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);
            //获取群
            GroupQrcodeBaseInfoVO wxGroup = bookGroupClassifyBiz.getWxGroupIdByClassifyIdAndWechatId(dto.getClassifyId(), dto.getWechatUserId());
            //判断是否是品牌方进具体群，如果是，从暗号表获取已经定好的群
            if ((!StringUtil.isEmpty(agreeAddUserDTO.getCipher())) && agreeAddUserDTO.getCipher().contains("RAYS_")) {
                JoinGroupCipher jgc = joinGroupCipherDao.getByCipher(agreeAddUserDTO.getCipher());
                if (CipherTypeEnum.QRCODE_CIPHER.code.equals(jgc.getType())) {
                    wxGroup = groupQrcodeDao.getBaseById(jgc.getQrcodeId());
                }
            }
            if (null == wxGroup) {
                log.error("[同意加好友发送欢迎语] : bookGroupClassifyBiz.getWxGroupIdByClassifyIdAndWechatId dto:{}");
                throw new BookBizException(BookBizException.ID_NOT_EXIST, "群不存在");
            }
            String wxGroupId = wxGroup.getWeixinGroupId();
            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);
                vo.setRobotProcessType(RobotProcessTypeEnum.WELCOME);
                vo.setCounts(1);
                vo.setIndex(0);
                vo.setMessageGroupId(UUID.randomUUID().toString());
                wechatGroupConsr.sendMessage(JSON.toJSONString(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 = wxGroup.getUserNumber();
            // 邀请好友进群有次数限制，目前测试为每天只能拉30-40人就操作频繁，所以在此加判断，超过30人或者群人数超过30人就发送邀请链接
            final String num = JedisClusterUtils.get(BookConstant.WXGROUP_ADD_USER_NUM + agreeAddUserDTO.getRobotWxId());
            log.info("[同意加好友发送欢迎语] 拉群 agreeAddUserDTO:{}, wxGroup:{}, num:{}", agreeAddUserDTO, wxGroup, num);
            if (StringUtil.isBlank(wxGroupId)) {
                log.info("[同意加好友发送欢迎语] 拉群 没有找到群 bookGroupClassifyBiz.getGroupQrcode4ClassifyWechat JoinGroupCipherDTO :{}", dto);
                return;
            }
            // 1001666 刘娜需求-1v1客服机器人，不直接拉人，30人以下也发邀请链接
            // 生产环境限制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());
            }
        }else{
            //qq同意加好友 并发送欢迎语
            PcloudRobot pcloudRobot = pcloudRobotDao.getByWxId(agreeAddUserDTO.getReceiverId().toString());
            if (pcloudRobot!=null){
                //删除需求单记录
                //TODO
                List<PcloudRobotWelcome> robotWelcomeListByPcloudClassifyId = pcloudRobotWelcomeDao.getRobotWelcomeListByPcloudClassifyId(Long.valueOf(pcloudRobot.getRobotType()), agreeAddUserDTO.getRobotType());
                pcloudRobotBiz.sendQQWelcomeReply(agreeAddUserDTO.getReceiverId(),agreeAddUserDTO.getUserId(),robotWelcomeListByPcloudClassifyId);
                //TODO 阶段处理
                /*if (personalStageBiz.isPersonalStageUser(agreeAddUserDTO.getRobotWxId())){
                    Long personalStageId = personalStageBiz.createAddUserStageUser(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp());
                    //清空缓存中该阶段的非关键词数量
                    //刪除发送非关键词次数緩存
                    JedisClusterUtils.del(PersonalStageConstant.USER_SEND_KEYWORD_COUNT_LOCK + personalStageId + "_" + agreeAddUserDTO.getUserWxId());
                    //删除进度单点击记录缓存
                    JedisClusterUtils.del("BOOK:LINK_PROGRESS:"+ agreeAddUserDTO.getUserWxId() + "-" +agreeAddUserDTO.getRobotWxId());
                }*/
                return;
            }

        }
    }

    @ParamLog("重置体验同意加好友发送欢迎语")
    @Override
    public void sendGuideNew(AgreeAddUserDTO agreeAddUserDTO) {
        if(null == agreeAddUserDTO || StringUtil.isBlank(agreeAddUserDTO.getRobotWxId()) || StringUtil.isBlank(agreeAddUserDTO.getUserWxId())) {
            log.info("[同意加好友发送欢迎语] 参数为空 agreeAddUserDTO：{}", agreeAddUserDTO);
            return ;
        }
        String cipher = agreeAddUserDTO.getCipher();
        //如果暗号为空，表示直接加好友，需要发送统一欢迎语
        if (cipher == null) {
            //发送配置欢迎语 create by lihao 2020.2.7
            //判断是否是平台端小号
            PcloudRobot pcloudRobot = pcloudRobotDao.getByWxId(agreeAddUserDTO.getRobotWxId());
            if (pcloudRobot!=null){
                //删除需求单记录
                personalStageJumpBiz.deletePaperRecord(agreeAddUserDTO.getRobotWxId(),agreeAddUserDTO.getUserWxId());
                pcloudRobotBiz.sendWelcomeReply(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp());
                //好友引导语
                sendFriendGuide(null, agreeAddUserDTO);
                if (personalStageBiz.isPersonalStageUser(agreeAddUserDTO.getRobotWxId())){
                    Long personalStageId = personalStageBiz.createAddUserStageUser(agreeAddUserDTO.getRobotWxId(), agreeAddUserDTO.getUserWxId(), agreeAddUserDTO.getIp());
                    //清空缓存中该阶段的非关键词数量
                    //刪除发送非关键词次数緩存
                    JedisClusterUtils.del(PersonalStageConstant.USER_SEND_KEYWORD_COUNT_LOCK + personalStageId + "_" + agreeAddUserDTO.getUserWxId());
                    //删除进度单点击记录缓存
                    JedisClusterUtils.del("BOOK:LINK_PROGRESS:"+ agreeAddUserDTO.getUserWxId() + "-" +agreeAddUserDTO.getRobotWxId());
                }
                return;
            }
            SendTextMessageVO vo = new SendTextMessageVO();
            vo.setContent("终于和您见面了!\n请告诉我您在读哪本书？\n如果您在上一步中复制了暗号，\n您可以把暗号粘贴在下方对话框内，以微信聊天的形式发给我。" +
                    "\n如果在上一步中，没有提示您复制暗号，\n您可以在【书中二维码旁】找到本书的简称及年份，\n在下方对话框内输入本书简称及年份，以微信聊天的形式发给我。");
            vo.setCode(SendMessageTypeEnum.SELF.getCode());
            vo.setWxId(agreeAddUserDTO.getRobotWxId());
            vo.setAltId(agreeAddUserDTO.getRobotWxId());
            vo.setWxGroupId(agreeAddUserDTO.getUserWxId());
            vo.setIp(agreeAddUserDTO.getIp());
            vo.setRobotProcessType(RobotProcessTypeEnum.WELCOME);
            vo.setCounts(1);
            vo.setIndex(0);
            vo.setMessageGroupId(UUID.randomUUID().toString());
            wechatGroupConsr.sendMessage(JSON.toJSONString(vo));
            return;
        }
        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);
        //获取群
        GroupQrcodeBaseInfoVO wxGroup = bookGroupClassifyBiz.getWxGroupIdByClassifyIdAndWechatId(dto.getClassifyId(), dto.getWechatUserId());
        //判断是否是品牌方进具体群，如果是，从暗号表获取已经定好的群
        if ((!StringUtil.isEmpty(agreeAddUserDTO.getCipher())) && agreeAddUserDTO.getCipher().contains("RAYS_")) {
            JoinGroupCipher jgc = joinGroupCipherDao.getByCipher(agreeAddUserDTO.getCipher());
            if (CipherTypeEnum.QRCODE_CIPHER.code.equals(jgc.getType())) {
                wxGroup = groupQrcodeDao.getBaseById(jgc.getQrcodeId());
            }
        }
        if (null == wxGroup) {
            log.error("[同意加好友发送欢迎语] : bookGroupClassifyBiz.getWxGroupIdByClassifyIdAndWechatId dto:{}");
            throw new BookBizException(BookBizException.ID_NOT_EXIST, "群不存在");
        }
        String wxGroupId = wxGroup.getWeixinGroupId();
        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());
            vo.setRobotProcessType(RobotProcessTypeEnum.WELCOME);
            vo.setCounts(1);
            vo.setIndex(0);
            vo.setMessageGroupId(UUID.randomUUID().toString());
            log.info("[同意加好友发送欢迎语] : {}", vo);
            wechatGroupConsr.sendMessage(JSON.toJSONString(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 = wxGroup.getUserNumber();
        // 邀请好友进群有次数限制，目前测试为每天只能拉30-40人就操作频繁，所以在此加判断，超过30人或者群人数超过30人就发送邀请链接
        final String num = JedisClusterUtils.get(BookConstant.WXGROUP_ADD_USER_NUM + agreeAddUserDTO.getRobotWxId());
        log.info("[同意加好友发送欢迎语] 拉群 agreeAddUserDTO:{}, wxGroup:{}, num:{}", agreeAddUserDTO, wxGroup, num);
        if (StringUtil.isBlank(wxGroupId)) {
            log.info("[同意加好友发送欢迎语] 拉群 没有找到群 bookGroupClassifyBiz.getGroupQrcode4ClassifyWechat JoinGroupCipherDTO :{}", dto);
            return;
        }
        // 1001666 刘娜需求-1v1客服机器人，不直接拉人，30人以下也发邀请链接
        // 生产环境限制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());
        }
    }
    /**
     * 推好友引导语
     * @param bookGroupId
     * @param agreeAddUserDTO
     */
    private void sendFriendGuide(Long bookGroupId, AgreeAddUserDTO agreeAddUserDTO) {
        String userWxId = agreeAddUserDTO.getUserWxId();
        String ip = agreeAddUserDTO.getIp();
        Integer code = SendMessageTypeEnum.SELF.getCode();
        String robotId = agreeAddUserDTO.getRobotWxId();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("robotWxId", robotId);
        PcloudRobot pcloudRobot = (PcloudRobot)pcloudRobotDao.getBy(paramMap, "getByRobotWxId");
        if (null != pcloudRobot) {
            PcloudGuide  pcloudGuide= pcloudGuideMapper.getFirstByClassifyId(pcloudRobot.getRobotType(),0);
            log.info("[sendFriendGuide] 新增好友，推送引导语: {}", pcloudGuide);
            if (pcloudGuide != null) {
                List<PcloudGuideMessageVO> messageVOList = pcloudGuideMessageMapper.listByGuideId(pcloudGuide.getId());

                PcloudGuideDelayDto guideDelayDto = PcloudGuideDelayDto.builder().sendTime(new Date()).duration(0)
                        .spanTime((pcloudGuide.getTimeSpan() == null ? 0 : pcloudGuide.getTimeSpan())).num(0)
                        .userWxId(agreeAddUserDTO.getUserWxId()).robotWxId(robotId).ip(ip).code(code).msgList(messageVOList).build();
                // 加好友 清除历史
                JedisClusterUtils.hdel(agreeAddUserDTO.getRobotWxId() + PCLOUD_GUIDE_SUFFIX, agreeAddUserDTO.getUserWxId());
                log.info("[sendFriendGuide] 向缓存中写入延迟发送的引导语：{}", JSONObject.toJSONString(guideDelayDto));
                JedisClusterUtils.hset(agreeAddUserDTO.getRobotWxId() + PCLOUD_GUIDE_SUFFIX, agreeAddUserDTO.getUserWxId(), JSONObject.toJSONString(guideDelayDto));
            }
            return;
        }
        List<BookGroupFriendGuide> friendGuideList = bookGroupFriendGuideDao.getListByBookGroupId(bookGroupId);
        if (ListUtils.isEmpty(friendGuideList)){
            return;
        }
        String groupId = UUID.randomUUID().toString();
        int counts = friendGuideList.size();
        for (int i = 0; i < friendGuideList.size(); i++) {
            BookGroupFriendGuide bookGroupFriendGuide = friendGuideList.get(i);
            Integer type = bookGroupFriendGuide.getType();
            if (ReplyTypeEnum.TEXT.value.equals(type)) {
                if (i==friendGuideList.size() - 1){
                    String content=bookGroupFriendGuide.getContent();
                    if (!StringUtil.isEmpty(content)){
                        String endUrl = wechatGroupLinkPrefix+ "/dialog" + "?book_group_id=" + bookGroupId + "&wxId=" + userWxId + "&robotWxId=" + robotId;
                        String resultUrl = UrlUtils.getShortUrl4Own(endUrl);
                        content=content+"\n你可以通过点击"+resultUrl+"，或者输入【】内关键词唤醒我\n" + "小睿会在这里时时陪伴你";
                        bookGroupFriendGuide.setContent(content);
                    }
                }
                SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                sendTextMessageVO.setContent(bookGroupFriendGuide.getContent());
                sendTextMessageVO.setAltId(robotId);
                sendTextMessageVO.setWxGroupId(userWxId);
                sendTextMessageVO.setIp(ip);
                sendTextMessageVO.setCode(code);
                sendTextMessageVO.setMessageGroupId(groupId);
                sendTextMessageVO.setCounts(counts);
                sendTextMessageVO.setIndex(i);
                sendTextMessageVO.setRobotProcessType(RobotProcessTypeEnum.GUIDE);
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
            }
            if (ReplyTypeEnum.IMAGE.value.equals(type)) {
                SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
                sendPicMessageVO.setWxGroupId(userWxId);
                sendPicMessageVO.setAltId(robotId);
                sendPicMessageVO.setPicUrl(bookGroupFriendGuide.getPicUrl());
                sendPicMessageVO.setIp(ip);
                sendPicMessageVO.setCode(code);
                sendPicMessageVO.setMessageGroupId(groupId);
                sendPicMessageVO.setCounts(counts);
                sendPicMessageVO.setIndex(i);
                sendPicMessageVO.setRobotProcessType(RobotProcessTypeEnum.GUIDE);
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendPicMessageVO));
            }
            if (ReplyTypeEnum.LINK.value.equals(type)) {
                SendArticleMessageVO sendArticleMessageVO = new SendArticleMessageVO();
                sendArticleMessageVO.setCode(code);
                sendArticleMessageVO.setAltId(robotId);
                sendArticleMessageVO.setDescription(bookGroupFriendGuide.getDescription());
                sendArticleMessageVO.setWxGroupId(userWxId);
                sendArticleMessageVO.setLinkUrl(bookGroupFriendGuide.getLinkUrl());
                sendArticleMessageVO.setPicUrl(bookGroupFriendGuide.getPicUrl());
                sendArticleMessageVO.setTitle(bookGroupFriendGuide.getContent());
                sendArticleMessageVO.setIp(ip);
                sendArticleMessageVO.setMessageGroupId(groupId);
                sendArticleMessageVO.setCounts(counts);
                sendArticleMessageVO.setIndex(i);
                sendArticleMessageVO.setRobotProcessType(RobotProcessTypeEnum.GUIDE);
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendArticleMessageVO));
            }
            if (ReplyTypeEnum.APP.value.equals(type)) {
                return;
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type)) {
                SendFileVO sendFileVO = new SendFileVO();
                Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(bookGroupFriendGuide.getResourceId()));
                ResourceDTO resourceDTO = map.get(bookGroupFriendGuide.getResourceId());
                if (resourceDTO != null) {
                    sendFileVO.setFileUrl(resourceDTO.getFileUrl());
                    String fileName = resourceDTO.getResourceName();
                    String fileType = resourceDTO.getFileType();
                    log.info("fileName="+fileName+"+fileType+"+fileType);
                    if (fileName.contains(fileType)){//去掉后缀
                        fileName = fileName.substring(0, fileName.indexOf(fileType)-1);
                    }
                    log.info("fileName="+fileName);
                    sendFileVO.setFileName(fileName);
                }
                sendFileVO.setIp(ip);
                sendFileVO.setAltId(robotId);
                sendFileVO.setWxId(userWxId);
                sendFileVO.setMessageGroupId(groupId);
                sendFileVO.setCounts(counts);
                sendFileVO.setIndex(i);
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendFileVO));
            }
        }
        log.info("临时demo发送个人号加好友欢迎语列表信息"+friendGuideList.toString());
    }

    @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);
        bookGroupAppBiz.addBookGuideToBookGroupApp(bookGuide,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);
            BookGuide bookGuideNew = bookGuideDao.getById(bookGuide.getId());
            bookGroupAppBiz.addBookGuideToBookGroupApp(bookGuideNew,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个了，20190911周磊改成不限制了，但是开发要求必须要加限制，所以先限制40个） 刘娜需求 1001282 群不推送关键词
        List<KeywordDTO> keywords = bookKeywordBiz.listFiveKeyword(classifyQrcodeInfo.getClassifyId(), classifyQrcodeInfo.getBookGroupId());
        Boolean isHaveKeywords = !ListUtils.isEmpty(keywords);
        //如果设置了群学习报告，加一个群学习报告的关键词
        KeywordStatusDTO dto = pushLearningReport(classifyQrcodeInfo, robotId, weixinGroupId, pushAddUserMessageDTO.getIp());
        AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(classifyQrcodeInfo.getChannelId());
        if (ListUtils.isEmpty(replyMessages)) {
            //获取群名称
            GroupQrcodeBaseInfoVO groupInfo = groupQrcodeBiz.getBaseById(classifyQrcodeInfo.getGroupQrcodeId());
            BookGroupDTO bookGroupDTO = bookGroupDao.getBookInfo(classifyQrcodeInfo.getBookGroupId());
            //推送消息 刘娜需求 1001282 群不推送关键词
            // 若非之前的机器人则不回复普通关键词
            SendDefaultGuideMessageDTO sendGuideMessageDTO = new SendDefaultGuideMessageDTO();
            sendGuideMessageDTO.setClassifyQrcodeInfo(classifyQrcodeInfo);
            sendGuideMessageDTO.setGroupName(groupInfo == null ? "" : groupInfo.getGroupName());
            sendGuideMessageDTO.setRobotId(robotId);
            sendGuideMessageDTO.setWeixinGroupId(weixinGroupId);
            sendGuideMessageDTO.setIsHaveKeywords(isHaveKeywords);
            sendGuideMessageDTO.setKeywords(keywords);
            sendGuideMessageDTO.setDto(dto);
            sendGuideMessageDTO.setIp(pushAddUserMessageDTO.getIp());
            sendGuideMessageDTO.setAccountSettingDto(accountSettingDto);
            sendGuideMessageDTO.setBookName(bookGroupDTO == null ? "" : bookGroupDTO.getBookName());
            sendWeixinRequestTools.sendDefaultMessage(sendGuideMessageDTO);
        } else {
            //处理链接
            handleUrl(replyMessages, wechatInfo, classifyQrcodeInfo);
            //推送消息
            SendGuideMessageDTO sendGuideMessageDTO = new SendGuideMessageDTO();
            sendGuideMessageDTO.setClassifyQrcodeInfo(classifyQrcodeInfo);
            sendGuideMessageDTO.setReplyMessages(replyMessages);
            sendGuideMessageDTO.setRobotId(robotId);
            sendGuideMessageDTO.setWeixinGroupId(weixinGroupId);
            sendGuideMessageDTO.setKeywords(keywords);
            sendGuideMessageDTO.setDto(dto);
            sendGuideMessageDTO.setIp(pushAddUserMessageDTO.getIp());
            sendGuideMessageDTO.setCode(SendMessageTypeEnum.GROUP.getCode());
            sendGuideMessageDTO.setAccountSettingDto(accountSettingDto);
            sendWeixinRequestTools.sendGuideMessage(sendGuideMessageDTO);
            //新增欢迎语应用触发记录
            addGuideAppTouchRecord(replyMessages,weixinGroupId,classifyQrcodeInfo.getBookGroupId(),classifyQrcodeInfo.getClassifyId());
        }
        if (bookGuide != null && bookGuide.getIsRecommend() != null && bookGuide.getIsRecommend() == 1) {
            //推送公众号消息
            sendWeixinRequestTools.sendAccountMessage(weixinGroupId, bookGuide.getRecommendLanguage(), robotId, wechatInfo, pushAddUserMessageDTO.getIp());
        }
    }

    @ParamLog("推关学习报告/猜谜语关键词消息")
    private KeywordStatusDTO pushLearningReport(GroupClassifyQrcodeDTO classifyQrcodeInfo, String robotId, String weixinGroupId, String ip) {
        boolean reportOpen = false;
        boolean riddleOpen = false;
        boolean clockOpen = false;
        KeywordStatusDTO dto = new KeywordStatusDTO();
        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;
            dto.setClockGuide(weixinClockDto.getClockGuide());
            dto.setClockKeyword(weixinClockDto.getClockKeyword());
        }
        dto.setReportOpen(reportOpen);
        dto.setRiddleOpen(riddleOpen);
        dto.setClockOpen(clockOpen);
        return dto;
//        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);
    }
}
