package com.pcloud.book.group.tools;

import com.alibaba.fastjson.JSON;
import com.pcloud.book.clock.dto.BookClockKeywordDTO;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.dto.GroupClassifyQrcodeDTO;
import com.pcloud.book.group.dto.SendDefaultGuideMessageDTO;
import com.pcloud.book.group.dto.SendGuideMessageDTO;
import com.pcloud.book.group.dto.SyncWeixinGroupIdRequestDTO;
import com.pcloud.book.group.dto.UpdateQrDTO;
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.dto.SendMessageDTO;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.keywords.vo.ReplyMessageVO;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.utils.BeanUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ServeLinkUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.httpclient.UrlUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.sdk.wxgroup.ChangeNameVO;
import com.sdk.wxgroup.SendArticleMessageVO;
import com.sdk.wxgroup.SendMessageTypeEnum;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lily
 * @date 2019/4/19 17:03
 */
@Component
public class SendWeixinRequestTools {
    private static final Logger LOGGER = LoggerFactory.getLogger(SendWeixinRequestTools.class);

    @Autowired
    private WechatGroupConsr wechatGroupConsr;

    @ParamLog("修改微信群名称")
    public static void changeGroupName(String robotWxId, String weixinGroupId, String groupName, String ip) {
        ChangeNameVO changeNameVO = new ChangeNameVO();
        changeNameVO.setAltId(robotWxId);
        changeNameVO.setWxGroupId(weixinGroupId);
        changeNameVO.setName(groupName);
        changeNameVO.setIp(ip);
        try {
            WxGroupSDK.changeGroupName(changeNameVO);
        } catch (Exception e) {
            LOGGER.error("修改微信群名称失败", e);
        }
    }

    @ParamLog("更新二维码地址（7天过期更新）")
    public static void updateQrUrl(List<UpdateQrDTO> updateQrs) {
        /*if (ListUtils.isEmpty(updateQrs)) {
            return;
        }
        List<QrcodeVO> qrcodes = new ArrayList<>();
        for (UpdateQrDTO updateQrDTO : updateQrs) {
            QrcodeVO qrcodeVO = new QrcodeVO();
            qrcodeVO.setPriority(1);
            qrcodeVO.setOperation(0);
            qrcodeVO.setId(updateQrDTO.getId());
            qrcodeVO.setAltId(updateQrDTO.getRobotWxId());
            String url = updateQrDTO.getUrl();
            if (url.contains("https://oss")) {
                url = url.replace("//oss", "//file");
            }
            qrcodeVO.setUrl(url);
            qrcodeVO.setRequestUrl("/book/v1.0/weixinQrcodeService/updateQrUrl");
            qrcodes.add(qrcodeVO);
        }
        try {
            // TODO 更新ip
            Kit.post("http:/192.168.82.213:8080/autoGroup",JSON.toJSONString(qrcodeList));
        } catch (Exception e) {
            log.error("更新二维码地址（7天过期更新）失败", e);
        }*/
    }

    /**
     * @Author:lili
     * @Desr:发送同步微信id请求
     * @Date:2019/4/15 15:36
     */
    public static void syncOneWeixinGroupId(Long qrcodeId, String qrcodeUrl, String weixinRobotId) {
        /*List<QrcodeVO> qrcodeVOS = new ArrayList<>();
        QrcodeVO qrcodeVO = new QrcodeVO();
        qrcodeVO.setId(qrcodeId);
        qrcodeVO.setUrl(qrcodeUrl);
        qrcodeVO.setOperation(1);
        qrcodeVO.setAltId(weixinRobotId);
        qrcodeVO.setPriority(5);
        qrcodeVO.setRequestUrl("/book/v1.0/weixinQrcodeService/syncWeixinGroupId");
        qrcodeVOS.add(qrcodeVO);
        try {
            // TODO 更新ip
            WxGroupSDK.syncWeixinGroupId(qrcodeVOS, null);
        } catch (Exception e) {
            log.error("发送同步微信id请求失败", e);
        }*/
    }

    /**
     * @Author:lili
     * @Desr:批量同步微信群标识
     * @Date:2019/4/26 17:50
     */
    public static void syncWeixinGroupIds(List<SyncWeixinGroupIdRequestDTO> weixinGroupIdDTOS) {
        /*if (ListUtils.isEmpty(weixinGroupIdDTOS)) {
            return;
        }
        List<QrcodeVO> qrcodeVOS = new ArrayList<>();
        for (SyncWeixinGroupIdRequestDTO syncWeixinGroupIdRequestDTO : weixinGroupIdDTOS) {
            QrcodeVO qrcodeVO = new QrcodeVO();
            qrcodeVO.setPriority(5);
            qrcodeVO.setOperation(1);
            qrcodeVO.setAltId(syncWeixinGroupIdRequestDTO.getRobotWxId());
            qrcodeVO.setId(syncWeixinGroupIdRequestDTO.getId());
            qrcodeVO.setUrl(syncWeixinGroupIdRequestDTO.getUrl());
            qrcodeVO.setRequestUrl("/book/v1.0/weixinQrcodeService/syncWeixinGroupId");
            qrcodeVOS.add(qrcodeVO);
        }
        try {
            // TODO 更新ip
            WxGroupSDK.syncWeixinGroupId(qrcodeVOS, null);
        } catch (Exception e) {
            log.error("批量同步微信群标识失败", e);
        }*/
    }

    @ParamLog("推送消息")
    private void sendMessage(SendMessageDTO sendMessageDTO, String robotId, String weixinGroupId, String ip, Integer code) {
        if (ReplyTypeEnum.TEXT.value.equals(sendMessageDTO.getReplyType())) {
            SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
            sendTextMessageVO.setContent(sendMessageDTO.getContent());
            sendTextMessageVO.setAltId(robotId);
            sendTextMessageVO.setWxGroupId(weixinGroupId);
            sendTextMessageVO.setIp(ip);
            sendTextMessageVO.setCode(code);
            // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
        } else if (ReplyTypeEnum.IMAGE.value.equals(sendMessageDTO.getReplyType())) {
            SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
            sendPicMessageVO.setWxGroupId(weixinGroupId);
            sendPicMessageVO.setAltId(robotId);
            sendPicMessageVO.setPicUrl(sendMessageDTO.getPicUrl());
            sendPicMessageVO.setIp(ip);
            sendPicMessageVO.setCode(code);
            // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendPicMessageVO));
        } else if (ReplyTypeEnum.APP.value.equals(sendMessageDTO.getReplyType()) || ReplyTypeEnum.LINK.value.equals(sendMessageDTO.getReplyType())) {
            SendArticleMessageVO sendArticleMessageVO = new SendArticleMessageVO();
            sendArticleMessageVO.setAltId(robotId);
            sendArticleMessageVO.setDescription(sendMessageDTO.getDescription());
            sendArticleMessageVO.setLinkUrl(sendMessageDTO.getLinkUrl());
            sendArticleMessageVO.setWxGroupId(weixinGroupId);
            sendArticleMessageVO.setPicUrl(sendMessageDTO.getPicUrl());
            sendArticleMessageVO.setTitle(sendMessageDTO.getContent());
            sendArticleMessageVO.setIp(ip);
            sendArticleMessageVO.setCode(code);
            // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendArticleMessageVO));
        }
    }

//    private static void sendAtMessage(String nickNameStr,String robotId,String weixinGroupId, String ip){
//
//        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
//        sendTextMessageVO.setContent(nickNameStr);
//        sendTextMessageVO.setAltId(robotId);
//        sendTextMessageVO.setWxGroupId(weixinGroupId);
//        sendTextMessageVO.setIp(ip);
//        WxGroupSDK.sendTextMessage(sendTextMessageVO);
//
//    }

    private static String addLinkParam(String url, Long groupQrcodeId, Long classifyId, Long bookGroupId) {
        if (StringUtil.isEmpty(url)) {
            return url;
        }
        final String s = "qrcode_id=" + groupQrcodeId + "&classify_id=" + classifyId + (null == bookGroupId ? "" : "&book_group_id=" + bookGroupId);
        if (url.contains("?")) {
            url = url + "&" + s;
        } else {
            url = url + "?" + s;
        }
        return url;
    }


    @ParamLog("推送公众号消息")
    public void sendAccountMessage(String weixinGroupId, String recommendLanguage, String robotId,
                                          AccountSettingDto accountSettingDto, String ip) {
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        if (StringUtil.isEmpty(recommendLanguage)) {
            recommendLanguage = "关注本书公众号，获取更多资源。";
        }
        sendTextMessageVO.setContent(recommendLanguage);
        sendTextMessageVO.setAltId(robotId);
        sendTextMessageVO.setWxGroupId(weixinGroupId);
        sendTextMessageVO.setIp(ip);
        // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
        SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
        sendPicMessageVO.setWxGroupId(weixinGroupId);
        sendPicMessageVO.setAltId(robotId);
        sendPicMessageVO.setPicUrl(accountSettingDto.getQrcodeUrl());
        sendPicMessageVO.setIp(ip);
        // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendPicMessageVO));
    }

    @ParamLog("推送关键词回复消息")
    public void sendKeywordMessage(ReplyKeywordDTO replyKeywordDTO, String robotId, String weixinGroupId, String ip, Integer code) {
        SendMessageDTO sendMessageDTO = new SendMessageDTO();
        BeanUtils.copyProperties(replyKeywordDTO, sendMessageDTO);
        sendMessage(sendMessageDTO, robotId, weixinGroupId, ip, code);
    }

    @ParamLog("补充域名")
    public static String splitUrlNew(AccountSettingDto accountSettingDto, String url, Long bookGroupId, Long classifyId, Long groupQrcodeId) {
        url = addLinkParam(url, groupQrcodeId, classifyId, bookGroupId);
        return splitUrl(accountSettingDto, url);
    }


    @ParamLog("补充域名")
    public static String splitUrl(AccountSettingDto accountSettingDto, String url) {
        if (null == accountSettingDto){
            LOGGER.error("运营平台未配置公众号，url"+url);
            return url;
        }
        return ServeLinkUtils.splitUrl(url,accountSettingDto.getAccountSettingId(),accountSettingDto.getProtocol(),
                accountSettingDto.getDomain(),accountSettingDto.getFirstDomain(),accountSettingDto.getRandom());
    }

    @ParamLog("群欢迎语中推送关键词信息")
    public void sendKeywordsInfo(List<KeywordDTO> keywords, String robotId, String weixinGroupId, String ip){
        if (ListUtils.isEmpty(keywords)) {
            return;
        }
        final String content = processContent(keywords, robotId, weixinGroupId, ip);
        sendTextMessage(content, robotId, weixinGroupId, ip);
    }

    @ParamLog("个人欢迎语中推送关键词信息")
    public void sendKeywordsInfoToSelf(List<KeywordDTO> keywords, String robotId, String toWxId, String ip){
        if (ListUtils.isEmpty(keywords)) {
            return;
        }
        final String content = processContent(keywords, robotId, toWxId, ip);
        sendTextMessageToSelf(content, robotId, toWxId, ip);
    }

    private String processContent(List<KeywordDTO> keywords, String robotId, String toWxId, String ip) {
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < keywords.size(); i++) {
            KeywordDTO keywordDTO = keywords.get(i);
            String keyword = "关键词【" + keywordDTO.getKeywords() + "】\n" + "    "+keywordDTO.getGuide();
            if (content.length() + keyword.length() > 1000) {
                sendTextMessageToSelf(content.toString(), robotId, toWxId, ip);
                content = new StringBuilder(keyword);
            }else{
                content.append(keyword);
            }
            if (i != keywords.size() - 1) {
                content.append("\n");
            }
        }
        return content.toString();
    }

    private void sendTextMessageToSelf(String content, String robotId, String toWxId, String ip){
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
        sendTextMessageVO.setWxGroupId(toWxId);
        sendTextMessageVO.setContent(content);
        sendTextMessageVO.setAltId(robotId);
        sendTextMessageVO.setIp(ip);
        // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
    }

    public void sendTextMessage(String content, String robotId, String weixinGroupId, String ip){
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        sendTextMessageVO.setContent(content);
        sendTextMessageVO.setAltId(robotId);
        sendTextMessageVO.setWxGroupId(weixinGroupId);
        sendTextMessageVO.setIp(ip);
        // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));;
    }

    /**
     * 发送默认欢迎语
     */
    public void sendDefaultMessage(SendDefaultGuideMessageDTO dto) {
        String groupName = dto.getGroupName();
        String robotId = dto.getRobotId();
        String weixinGroupId = dto.getWeixinGroupId();
        Boolean isHaveKeywords = dto.getIsHaveKeywords();
        List<KeywordDTO> keywords = dto.getKeywords();
        KeywordStatusDTO keywordStatusDTO = dto.getDto();
        GroupClassifyQrcodeDTO classifyQrcodeInfo = dto.getClassifyQrcodeInfo();
        String ip = dto.getIp();
        StringBuilder content = new StringBuilder(getNickNameStr(weixinGroupId));
        String bookName = dto.getBookName();
        //欢迎语
        content.append("欢迎加入");
        if (!StringUtil.isEmpty(bookName)) {
            content.append("【").append(bookName).append("】");
        }
        if (!StringUtil.isEmpty(groupName)) {
            content.append(groupName).append("！");
        } else {
            content.append("交流群！");
        }
        if(isHaveKeywords){
//            content = content + "本群目的为学习交流和学习辅导，线上资源和工具为图书的增值服务，可根据实际情况配合图书一起使用。在群内回复以下关键词领取任务或资源：";
            content.append("本群目的为学习交流和学习辅导，线上资源和工具为图书的增值服务，可根据实际情况配合图书一起使用。");
        }
        StringBuilder sb = new StringBuilder();
        boolean isOld = createGuideMessageBase(keywords, classifyQrcodeInfo, sb, dto.getAccountSettingDto(), content.length());
        StringBuilder groupKeyword = createGroupKeyword(keywordStatusDTO, classifyQrcodeInfo, sb, isOld, dto.getAccountSettingDto());
        // 1001692 自定义欢迎语+关键词文案，如果超过300字，关键词拆分出来发
        if ((content.length() + sb.length()) >= 1000) {
            sendTextMessage(content.toString(), robotId, weixinGroupId, ip);
            sendTextMessage(groupKeyword.toString().replaceFirst("\n\n", ""), robotId, weixinGroupId, ip);
        } else {
            sendTextMessage(content.append(groupKeyword).toString(), robotId, weixinGroupId, ip);
        }
    }

    @ParamLog("发送欢迎语消息")
    public void sendGuideMessage(SendGuideMessageDTO dto) {
        if (Objects.isNull(dto) || CollectionUtils.isEmpty(dto.getReplyMessages())) {
            return;
        }
        List<ReplyMessageVO> replyMessages = dto.getReplyMessages();
        String robotId = dto.getRobotId();
        String weixinGroupId = dto.getWeixinGroupId();
        List<KeywordDTO> keywords = dto.getKeywords();
        KeywordStatusDTO keywordStatusDTO = dto.getDto();
        GroupClassifyQrcodeDTO classifyQrcodeInfo = dto.getClassifyQrcodeInfo();
        String ip = dto.getIp();
        Integer code = dto.getCode();
        int i = 0;
        for (ReplyMessageVO replyMessageVO : replyMessages) {
            SendMessageDTO sendMessageDTO = new SendMessageDTO();
            BeanUtils.copyProperties(replyMessageVO, sendMessageDTO);
            String nickNameStr = getNickNameStr(weixinGroupId);
            if(i == 0) {
                LOGGER.info("发送欢迎语" + nickNameStr);
//                if (StringUtils.isNotEmpty(nickNameStr)) {
                if (ReplyTypeEnum.TEXT.value.equals(sendMessageDTO.getReplyType())) {
                    String s = nickNameStr + " " + sendMessageDTO.getContent();
                    StringBuilder sb = new StringBuilder();
                    boolean isOld = createGuideMessageBase(keywords, classifyQrcodeInfo, sb, dto.getAccountSettingDto(), s.length());
                    StringBuilder groupKeyword = createGroupKeyword(keywordStatusDTO, classifyQrcodeInfo, sb, isOld, dto.getAccountSettingDto());
                    // 1001692 自定义欢迎语+关键词文案，如果超过300字，关键词拆分出来发
                    if (s.length() + groupKeyword.length() >= 1000) {
                        sendMessageDTO.setContent(s);
                        sendMessage(sendMessageDTO, robotId, weixinGroupId, ip, code);
                        sendMessageDTO.setContent(groupKeyword.toString().replaceFirst("\n\n", ""));
                        sendMessage(sendMessageDTO, robotId, weixinGroupId, ip, code);
                        i++;
                        continue;
                    } else {
                        sendMessageDTO.setContent(s + groupKeyword.toString());
                    }
                } else {
                    SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                    sendTextMessageVO.setContent(nickNameStr);
                    sendTextMessageVO.setAltId(robotId);
                    sendTextMessageVO.setWxGroupId(weixinGroupId);
                    sendTextMessageVO.setIp(ip);
                    // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
                }
//                }
            }
            sendMessage(sendMessageDTO, robotId, weixinGroupId, ip, code);
            i++;
        }
    }


    private static boolean createGuideMessageBase(List<KeywordDTO> keywords, GroupClassifyQrcodeDTO classifyQrcodeInfo, StringBuilder sb, AccountSettingDto accountSettingDto, int length) {
        boolean isOld = true;
        boolean haveKeyword = !CollectionUtils.isEmpty(keywords);
        if (haveKeyword) {
            List<KeywordDTO> collect = keywords.stream()
                    .filter(p -> (ReplyTypeEnum.IMAGE.value.equals(p.getReplyType()) || ReplyTypeEnum.TEXT.value.equals(p.getReplyType())))
                    .collect(Collectors.toList());
            // 1001745 包含图片和文字则不合并关键词详情，其他情况走之前的模式
            if (CollectionUtils.isEmpty(collect)) {
                isOld = false;
                sb.append("\n\n本群配有以下资源服务，点击链接或回复相应关键词立即获取：\n");
                for (KeywordDTO keyword : keywords) {
                    if (sb.length() + (keyword.getKeywords() + "\n").length() >= 730) {
                        break;
                    }
                    sb.append("关键词：").append(keyword.getKeywords()).append("\n");
                    if (ReplyTypeEnum.LINK.value.equals(keyword.getReplyType()) || ReplyTypeEnum.APP.value.equals(keyword.getReplyType())) {
                        String linkUrl = SendWeixinRequestTools.splitUrlNew(accountSettingDto, keyword.getLinkUrl(), classifyQrcodeInfo.getBookGroupId(), classifyQrcodeInfo.getClassifyId(), classifyQrcodeInfo.getGroupQrcodeId());
                        sb.append(" ").append(keyword.getContent()).append("\n->").append(UrlUtils.getShortUrl4Own(linkUrl)).append("\n\n");
                    }
                }
            } else {
                sb.append("\n\n在群内回复以下关键词，领取任务或资源：\n");
                for (KeywordDTO keyword : keywords) {
                    if ((length + sb.length()) >= 1000 && (sb.length() + (keyword.getKeywords() + "\n").length()) >= 892) {
                        break;
                    }
                    sb.append("【").append(keyword.getKeywords()).append("】");
                }
            }
        }
        return isOld;
    }

    private static StringBuilder createGroupKeyword(KeywordStatusDTO keywordStatusDTO, GroupClassifyQrcodeDTO classifyQrcodeInfo, StringBuilder sb, boolean isOld, AccountSettingDto accountSettingDto) {
        // 运营关键词
        StringBuilder groupKeyword = getGroupKeyword(keywordStatusDTO, sb, isOld);
        //根据编辑id判断是否是heals的群
        Boolean isHeals = false;
        if (null != classifyQrcodeInfo && Objects.equals(BookProps.getHealsAdviserId(),classifyQrcodeInfo.getAdviserId())) {
            isHeals = true ;
            LOGGER.info("系统的heals的编辑账号是：{}，群的编辑账号是：{}",BookProps.getHealsAdviserId(), classifyQrcodeInfo.getAdviserId() );
        }
        // 拼接反馈链接
        String feedbackUrl = "*common/C" + classifyQrcodeInfo.getChannelId() + "/A0/feedback/suggest?groupQrcodeId=" + classifyQrcodeInfo.getGroupQrcodeId();
        if (isHeals) {
            feedbackUrl = feedbackUrl + "&isHeals=1";
        }String url = splitUrl(accountSettingDto, feedbackUrl);
        LOGGER.info("发送欢迎语反馈链接feedbackUrl:{}, url:{}", feedbackUrl, url);
        groupKeyword.append("如果您在使用本群过程中有任何意见或建议，请点击这里反馈吧\n->").append(UrlUtils.getShortUrl4Own(url));
        return groupKeyword;
    }

    /**
     * 组装群运营关键词
     * @param dto 运营关键词相关参数
     * @param sb 推送内容
     * @param isOld 包含图片或者文字走旧流程就不包含描述，否则加描述
     * @return 最终发送内容
     */
    private static StringBuilder getGroupKeyword(KeywordStatusDTO dto, StringBuilder sb, Boolean isOld) {
        String currentContent = sb.toString();
        if (!currentContent.contains("关键词") && (dto.getClockOpen() || dto.getRiddleOpen() || dto.getReportOpen())) {
            // 检查是否包含关键词
            sb.append("\n\n在群内回复以下关键词:\n");
        }

        if(isOld) {
            if(dto.getReportOpen()) {
                sb.append("【学习报告】");
            }
            if(dto.getRiddleOpen()) {
                sb.append("【猜谜语】");
            }
            if(dto.getClockOpen()) {
                sb.append("【").append(dto.getClockKeyword()).append("】");
            }

            // 最后加入空白行
            sb.append("\n\n");
        }
        else {
            if(dto.getReportOpen()) {
                sb.append("关键词：学习报告\n 回复学习报告，获取个人学习报告，与群成员PK元气值\n\n");
            }
            if(dto.getRiddleOpen()) {
                sb.append("关键词：猜谜语\n 回复猜谜语，开启群游戏，连续答对5题，所有群成员可获得精美礼券\n\n");
            }
            if(dto.getClockOpen()) {
                sb.append("关键词：").append(dto.getClockKeyword()).append("\n ").append(dto.getClockGuide()).append("\n\n");
            }
            sb.append("请点击蓝色链接，获取对应资源服务。\n");
        }
        return sb;
    }

    private static String getNickNameStr(String weixinGroupId) {
        StringBuilder nameStr = new StringBuilder();
        Map<String, Integer> nickNames = JedisClusterUtils.getJson("BOOK:WEIXINGROUP:GUIDEUSER" + weixinGroupId, Map.class);
        int i = 0;
        List<String> names = new ArrayList<>();
        Set<Map.Entry<String, Integer>> entries = nickNames.entrySet();
        for (Map.Entry<String, Integer> stringIntegerEntry : entries) {
            if (i == 5) {
                break;
            }
            String key = stringIntegerEntry.getKey();
            names.add(key);
            i++;
        }
        for (String nickName : names) {
            nickNames.remove(nickName);
            if (StringUtils.isNotEmpty(nickName)) {
                nameStr.append("@").append(nickName).append("  ");
            }
        }
        JedisClusterUtils.setJson("BOOK:WEIXINGROUP:GUIDEUSER" + weixinGroupId, nickNames, 600);
        return nameStr.toString();
    }

    @ParamLog("欢迎语中推送关键词信息")
    public void sendClockKeywordsInfo(List<BookClockKeywordDTO> keywords, String robotId, String weixinGroupId, String ip) {
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        sendTextMessageVO.setAltId(robotId);
        sendTextMessageVO.setWxGroupId(weixinGroupId);
        sendTextMessageVO.setIp(ip);
        if (ListUtils.isEmpty(keywords)) {
            return;
        }
        String content = "";
        for (int i = 0; i < keywords.size(); i++) {
            BookClockKeywordDTO bookClockKeywordDTO = keywords.get(i);
            String keyword = "关键词【" + bookClockKeywordDTO.getKeyword() +  "】\n" + "    " + bookClockKeywordDTO.getGuide();
            if (content.length() + keyword.length() > 1000) {
                sendTextMessageVO.setContent(content);
                // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
                content = keyword;
            }else{
                content = content + keyword;
            }
            if (i != keywords.size() - 1) {
                content = content + "\n";
            }
        }
        sendTextMessageVO.setContent(content);
        // TODO sdk.message
                wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
    }
}
