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.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.QrcodeVO;
import com.sdk.wxgroup.SendArticleMessageVO;
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 java.util.*;

/**
 * @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) {
        ChangeNameVO changeNameVO = new ChangeNameVO();
        changeNameVO.setAltId(robotWxId);
        changeNameVO.setWxGroupId(weixinGroupId);
        changeNameVO.setName(groupName);
        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, String ip) {
        //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())) {
                        sendMessageDTO.setContent(nickNameStr + " " + sendMessageDTO.getContent());
                    } else {
                        sendAtMessage(nickNameStr, robotId, weixinGroupId, ip);
                    }
                }
            }
            sendMessage(sendMessageDTO, robotId, weixinGroupId, ip);
            i++;
        }
    }


    @ParamLog("推送消息")
    private static void sendMessage(SendMessageDTO sendMessageDTO, String robotId, String weixinGroupId, String ip) {
        if (ReplyTypeEnum.TEXT.value.equals(sendMessageDTO.getReplyType())) {
            SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
            sendTextMessageVO.setContent(sendMessageDTO.getContent());
            sendTextMessageVO.setAltId(robotId);
            sendTextMessageVO.setGroupId(weixinGroupId);
            sendTextMessageVO.setIp(ip);
            WxGroupSDK.sendTextMessage(sendTextMessageVO);
        } else if (ReplyTypeEnum.IMAGE.value.equals(sendMessageDTO.getReplyType())) {
            SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
            sendPicMessageVO.setGroupId(weixinGroupId);
            sendPicMessageVO.setAltId(robotId);
            sendPicMessageVO.setPicUrl(sendMessageDTO.getPicUrl());
            sendPicMessageVO.setIp(ip);
            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.setGroupId(weixinGroupId);
            sendArticleMessageVO.setPicUrl(sendMessageDTO.getPicUrl());
            sendArticleMessageVO.setTitle(sendMessageDTO.getContent());
            sendArticleMessageVO.setIp(ip);
            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.setGroupId(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;
        }
        if (url.contains("?")) {
            url = url + "&qrcode_id=" + groupQrcodeId + "&classify_id=" + classifyId + "&book_group_id=" + bookGroupId;
        } else {
            url = url + "?qrcode_id=" + groupQrcodeId + "&classify_id=" + classifyId + "&book_group_id=" + bookGroupId;
        }
        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.setGroupId(weixinGroupId);
        sendTextMessageVO.setIp(ip);
        WxGroupSDK.sendTextMessage(sendTextMessageVO);
        SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
        sendPicMessageVO.setGroupId(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) {
        SendMessageDTO sendMessageDTO = new SendMessageDTO();
        BeanUtils.copyProperties(replyKeywordDTO, sendMessageDTO);
        sendMessage(sendMessageDTO, robotId, weixinGroupId, ip);
    }

    @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;
        }
        String content = "";
        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) {
                sendTextMessage(content, robotId, weixinGroupId, ip);
                content = keyword;
            }else{
                content = content + keyword;
            }
            if (i != keywords.size() - 1) {
                content = content + "\n";
            }
        }
        sendTextMessage(content, robotId, weixinGroupId, ip);
    }

    public static void sendTextMessage(String content, String robotId, String weixinGroupId, String ip){
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        sendTextMessageVO.setContent(content);
        sendTextMessageVO.setAltId(robotId);
        sendTextMessageVO.setGroupId(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.setGroupId("14108963419@chatroom");
//        WxGroupSDK.sendTextMessage(sendTextMessageVO);
    }

    public static void sendDefaultMessage(String groupName, String robotId, String weixinGroupId, Boolean isHaveKeywords, String ip) {
        String content = getNickNameStr(weixinGroupId);
        if (StringUtil.isEmpty(groupName)) {
            content += " 欢迎加入本群!";
        } else {
            content += " 欢迎加入" + groupName + "！";
        }
        if(isHaveKeywords){
            content = content + "本群目的为学习交流和学习辅导，线上资源和工具为图书的增值服务，可根据实际情况配合图书一起使用。凭以下关键词领取任务或资源：";
        }
        sendTextMessage(content, robotId, weixinGroupId, ip);
    }

    private static String getNickNameStr(String weixinGroupId) {
        String nameStr = "";
        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 = nameStr + "@" + nickName + "  ";
            }
        }
        JedisClusterUtils.setJson("BOOK:WEIXINGROUP:GUIDEUSER" + weixinGroupId, nickNames, 600);
        return nameStr;
    }

    @ParamLog("欢迎语中推送关键词信息")
    public static void sendClockKeywordsInfo(List<BookClockKeywordDTO> keywords, String robotId, String weixinGroupId, String ip) {
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        sendTextMessageVO.setAltId(robotId);
        sendTextMessageVO.setGroupId(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);
    }
}
