package com.pcloud.book.group.tools;

import com.pcloud.book.clock.dto.BookClockKeywordDTO;
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.channelcenter.base.constants.ChannelConstants;
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.cache.redis.JedisClusterUtils;
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.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

    @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("发送欢迎语消息")
    public static void sendGuideMessage(List<ReplyMessageVO> replyMessages, String robotId, String weixinGroupId, Boolean isGroupRobot, List<KeywordDTO> keywords, KeywordStatusDTO dto, String ip, Integer code) {
        //JedisClusterUtils.del("BOOK:WEIXINGROUP:GUIDEUSER" + weixinGroupId);
        if (ListUtils.isEmpty(replyMessages)) {
            return;
        }
        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();
                        if (!CollectionUtils.isEmpty(keywords) && isGroupRobot) {
                            sb.append("\n\n在群内回复以下关键词，领取任务或资源:\n");
                            for (KeywordDTO keyword : keywords) {
                                // 关键词长度和欢迎语长度之和超过300会拆分成两条，若拆分之后关键词长度还是大于300则只发300以内的部分
                                if ((s.length() + sb.length()) >= 300 && (sb.length() + (keyword.getKeywords() + "\n").length()) >= 277) {
                                    break;
                                }
                                sb.append("【").append(keyword.getKeywords()).append("】");
                            }
                        }
                        StringBuilder groupKeyword = getGroupKeyword(dto, sb);
                        // 1001692 自定义欢迎语+关键词文案，如果超过300字，关键词拆分出来发
                        if (s.length() + groupKeyword.length() >= 300) {
                            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);
                        WxGroupSDK.sendTextMessage(sendTextMessageVO);
                    }
//                }
            }
            sendMessage(sendMessageDTO, robotId, weixinGroupId, ip, code);
            i++;
        }
    }


    @ParamLog("推送消息")
    private static 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);
            WxGroupSDK.sendTextMessage(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);
            WxGroupSDK.sendPicMessage(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);
            WxGroupSDK.sendArticleMessage(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 static 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);
        WxGroupSDK.sendTextMessage(sendTextMessageVO);
        SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
        sendPicMessageVO.setWxGroupId(weixinGroupId);
        sendPicMessageVO.setAltId(robotId);
        sendPicMessageVO.setPicUrl(accountSettingDto.getQrcodeUrl());
        sendPicMessageVO.setIp(ip);
        WxGroupSDK.sendPicMessage(sendPicMessageVO);
    }

    @ParamLog("推送关键词回复消息")
    public static 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) {
        String protocol = accountSettingDto.getProtocol();
        if (StringUtils.isEmpty(protocol)) {
            protocol = ChannelConstants.HTTP;
        }
        String resultUrl = "";
        if (!StringUtils.isEmpty(url)) {
            if (url.startsWith("http")) {
                return url;
            }
            if (url.startsWith("*")) {
                String endUrl = url.substring(url.indexOf("/"), url.length());
                if (accountSettingDto.getRandom() == null) {
                    resultUrl = protocol + "app." + accountSettingDto.getFirstDomain() + "/" + url.substring(1, url.indexOf("/")) + "/W"
                            + accountSettingDto.getAccountSettingId() + endUrl;
                } else {
                    resultUrl = protocol + "app" + accountSettingDto.getRandom() + "." + accountSettingDto.getFirstDomain() + "/" + url.substring(1, url.indexOf("/")) + "/W"
                            + accountSettingDto.getAccountSettingId() + endUrl;
                }
            } else {
                resultUrl = protocol + accountSettingDto.getDomain() + "/W" + accountSettingDto.getAccountSettingId() + url;
            }
        }
        return resultUrl;
    }

    @ParamLog("群欢迎语中推送关键词信息")
    public static 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 static 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 static 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() > 300) {
                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 static 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);
        WxGroupSDK.sendTextMessage(sendTextMessageVO);
    }

    public static 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);
        WxGroupSDK.sendTextMessage(sendTextMessageVO);
    }

    public static void main(String[] args) {
//        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
//        sendTextMessageVO.setContent("关键词1：a" + "\n" + "换行换行换行" + "\n");
//        sendTextMessageVO.setAltId("wxid_qj200bf0key022");
//        sendTextMessageVO.setWxGroupId("14108963419@chatroom");
//        WxGroupSDK.sendTextMessage(sendTextMessageVO);
    }

    public static void sendDefaultMessage(String groupName, String robotId, String weixinGroupId, Boolean isHaveKeywords, Boolean isGroupRobot, List<KeywordDTO> keywords, KeywordStatusDTO dto, String ip) {
        StringBuilder content = new StringBuilder(getNickNameStr(weixinGroupId));
        if (StringUtil.isEmpty(groupName)) {
            content.append(" 欢迎加入本群!");
        } else {
            content.append(" 欢迎加入").append(groupName).append("！");
        }
        if(isHaveKeywords){
//            content = content + "本群目的为学习交流和学习辅导，线上资源和工具为图书的增值服务，可根据实际情况配合图书一起使用。在群内回复以下关键词领取任务或资源：";
            content.append("本群目的为学习交流和学习辅导，线上资源和工具为图书的增值服务，可根据实际情况配合图书一起使用。");
        }
        StringBuilder sb = new StringBuilder();
        if (!CollectionUtils.isEmpty(keywords) && isGroupRobot) {
            sb.append("\n\n在群内回复以下关键词，领取任务或资源:\n");
            for (KeywordDTO keyword : keywords) {
                if ((content.length() + sb.length()) >= 300 && (sb.length() + (keyword.getKeywords() + "\n").length()) >= 277) {
                    break;
                }
                sb.append("【").append(keyword.getKeywords()).append("】");
            }
        }
        StringBuilder groupKeyword = getGroupKeyword(dto, sb);
        // 1001692 自定义欢迎语+关键词文案，如果超过300字，关键词拆分出来发
        if ((content.length() + sb.length()) >= 300) {
            sendTextMessage(content.toString(), robotId, weixinGroupId, ip);
            sendTextMessage(groupKeyword.toString().replaceFirst("\n\n", ""), robotId, weixinGroupId, ip);
        } else {
            sendTextMessage(content.append(groupKeyword).toString(), robotId, weixinGroupId, ip);
        }
    }

    private static StringBuilder getGroupKeyword(KeywordStatusDTO dto, StringBuilder sb) {
        if (!sb.toString().contains("【") && (dto.getClockOpen() || dto.getRiddleOpen() || dto.getReportOpen())) {
            sb.append("\n\n在群内回复以下关键词:\n");
        }
        if (dto.getReportOpen()) {
            sb.append("【学习报告】");
        }
        if (dto.getRiddleOpen()) {
            sb.append("【猜谜语】");
        }
        if (dto.getClockOpen()) {
            sb.append("【").append(dto.getClockKeyword()).append("】");
        }
        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 (Iterator<Map.Entry<String, Integer>> iterator = entries.iterator(); iterator.hasNext(); ) {
            if (i == 5) {
                break;
            }
            Map.Entry<String, Integer> entry = iterator.next();
            String key = entry.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 static 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() > 300) {
                sendTextMessageVO.setContent(content);
                WxGroupSDK.sendTextMessage(sendTextMessageVO);
                content = keyword;
            }else{
                content = content + keyword;
            }
            if (i != keywords.size() - 1) {
                content = content + "\n";
            }
        }
        sendTextMessageVO.setContent(content);
        WxGroupSDK.sendTextMessage(sendTextMessageVO);
    }
}
