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

import com.alibaba.fastjson.JSON;
import com.dcg.coolq.sdk.message.MessageBuilder;
import com.dcg.coolq.sdk.message.components.ComponentImage;
import com.dcg.coolq.sdk.message.components.ComponentRecord;
import com.dcg.coolq.sdk.message.components.ComponentText;
import com.dcg.coolq.sdk.message.vos.send.PrivateMsgSendVO;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.user.PartyConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.dao.BookGroupCipherUserDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.WeixinQrcodeGenerationDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.SelfRobotBookGroupDTO;
import com.pcloud.book.group.entity.WeixinQrcodeGeneration;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.enums.LargeTempletEnum;
import com.pcloud.book.group.set.GroupSet;
import com.pcloud.book.group.vo.UserBookInfoVO;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.pcloudKeyword.dto.RobotClassifyDTO;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotBiz;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.pcloudkeyword.set.PcloudRobotSet;
import com.pcloud.book.push.biz.SelfPushBiz;
import com.pcloud.book.push.constant.PushConstant;
import com.pcloud.book.push.dao.PersonalAppletsDao;
import com.pcloud.book.push.dao.SelfPushDao;
import com.pcloud.book.push.dao.SelfPushItemDao;
import com.pcloud.book.push.dao.SelfPushUserDao;
import com.pcloud.book.push.dto.PersonalAppletsRecordDTO;
import com.pcloud.book.push.dto.SelfPushAddParamDTO;
import com.pcloud.book.push.dto.SelfPushRecordDTO;
import com.pcloud.book.push.dto.UserCountAndPushDTO;
import com.pcloud.book.push.entity.PersonalApplets;
import com.pcloud.book.push.entity.SelfPush;
import com.pcloud.book.push.entity.SelfPushItem;
import com.pcloud.book.push.entity.SelfPushUser;
import com.pcloud.book.push.enums.AltTypeEnum;
import com.pcloud.book.push.enums.ItemTypeEnum;
import com.pcloud.book.push.enums.PushStatusEnum;
import com.pcloud.book.skill.dto.AppOrProductReplyDTO;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.facade.quartz.entity.CallBackParam;
import com.pcloud.facade.quartz.entity.ScheduleJob;
import com.pcloud.facade.quartz.service.ScheduleService;
import com.pcloud.usercenter.user.entity.UserLogin;
import com.pcloud.wechatgroup.group.dto.GroupRobotDTO;
import com.pcloud.wechatgroup.group.dto.GroupUserDTO;
import com.pcloud.wechatgroup.selfrobot.dto.RobotBaseInfoDTO;
import com.sdk.wxgroup.*;
import com.sdk.wxgroup.im.mimc.BusinessConstant;
import com.sdk.wxgroup.im.mimc.dto.SendMomentsDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @描述：个人号群发
 * @作者：zhuyajie
 * @创建时间：11:00 2019/11/27
 * @版本：1.0
 */
@Slf4j
@Component("selfPushBiz")
public class SelfPushBizImpl implements SelfPushBiz {
    private static final Logger LOGGER = LoggerFactory.getLogger(SelfPushBizImpl.class);
    @Autowired
    private SelfPushDao selfPushDao;
    @Autowired
    private SelfPushItemDao selfPushItemDao;
    @Autowired
    private SelfPushUserDao selfPushUserDao;
    @Autowired
    private GroupSet groupSet;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private WeixinQrcodeGenerationDao weixinQrcodeGenerationDao;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private BookGroupCipherUserDao bookGroupCipherUserDao;
    @Value("${system.env}")
    private String envStr;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private PartyConsr partyConsr;
    @Autowired
    private PcloudRobotBiz pcloudRobotBiz;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private PcloudRobotSet pcloudRobotSet;
    @Autowired
    private PersonalAppletsDao personalAppletsDao;

    private static final String self_push_SCHEDULE_PRE = "self_push_";


    @Override
    public void createSelfPush(Long partyId, SelfPushAddParamDTO addParamDTO) {
        Boolean sendNow = addParamDTO.getSendNow();
        Integer itemType=0;
        Long personalAppletsId=0L;
        if(addParamDTO.getReplyParamDTOS()!=null&&addParamDTO.getReplyParamDTOS().get(0)!=null) {
             personalAppletsId = addParamDTO.getReplyParamDTOS().get(0).getPersonalAppletsId();
            itemType=addParamDTO.getReplyParamDTOS().get(0).getReplyType();
        }
        //群发
        SelfPush selfPush = new SelfPush();
        selfPush.setCreateUser(partyId);
        selfPush.setUpdateUser(partyId);
        selfPush.setAltType(addParamDTO.getAltType());
        if (SystemCode.adviser.code.equalsIgnoreCase(addParamDTO.getSystemCode())){
            selfPush.setBookGroupId(addParamDTO.getBookGroupId());
            selfPush.setSendAll(false);
        }
        if (SystemCode.pcloud.code.equalsIgnoreCase(addParamDTO.getSystemCode())){
            selfPush.setAltId(addParamDTO.getAltId());
            if (addParamDTO.getSendAll()){//发送全部好友
                List<String> userIdList = wechatGroupConsr.getFriendByRobotId(addParamDTO.getAltId(),addParamDTO.getAltType());
                addParamDTO.setUserIdList(userIdList);
            }
            selfPush.setSendAll(addParamDTO.getSendAll());
        }
        selfPush.setSendNow(sendNow);
        if (sendNow) {
            selfPush.setSendTime(new Date());
            selfPush.setPushStatus(PushStatusEnum.PUSHING.value);
        } else {
            selfPush.setPushSendTime(addParamDTO.getSendTime());
            selfPush.setStartTime(DateUtils.getDateByStr(addParamDTO.getStartTime()));
            selfPush.setEndTime(DateUtils.getDateByStr(addParamDTO.getEndTime()));
            selfPush.setPushType(addParamDTO.getPushType());
            selfPush.setPushStatus(PushStatusEnum.WAIT.value);
            if(addParamDTO.getPushType()==2){
                selfPush.setWeekDays(addParamDTO.getWeekDays());
            }
        }
        selfPushDao.insert(selfPush);
        Long pushId = selfPush.getId();
        //群发项
        List<SelfPushItem> itemList = addParamDTO.getPushItemList();
        setSelfPushItem(pushId, sendNow, partyId, itemList, selfPush.getSendTime(),personalAppletsId,itemType);
        //群发用户
        List<String> userIdList = addParamDTO.getUserIdList();
        setSelfPushUser(userIdList, partyId, pushId);
        if (sendNow) {
            //微信立即发送
            msgPush(userIdList, itemList, pushId);
        } else {
            //定时任务
            createSendQuartz(selfPush);
        }
    }

    @ParamLog("设置定时任务")
    private void createSendQuartz(SelfPush addParamDTO) {
        Integer pushType = addParamDTO.getPushType();
        if (pushType==1) {
            pushDay(addParamDTO);
        } else if (pushType==2) {
            pushWeek(addParamDTO);
        }
    }

    @ParamLog("按周设置定时任务")
    private void pushWeek(SelfPush addParamDTO) {
        String cron;
        String putTime = addParamDTO.getPushSendTime();
        try {
            int hour = Integer.parseInt(putTime.substring(0, 2));
            int minute = Integer.parseInt(putTime.substring(3, 5));
            int second = Integer.parseInt(putTime.substring(6, 8));

            String weekDays = addParamDTO.getWeekDays();
            String weeks="";
            String[] strs=new String[20];
            if(weekDays.length()!=1) {
                strs = weekDays.split(",");
            }else {
                strs[0]=weekDays;
            }
            List<String> strings = Arrays.asList(strs);
            for(int i=0;i<=strings.size()-1;i++){
                if(strings.get(i)==null){
                    break;
                }
                Integer weekDay = Integer.valueOf(strings.get(i));
                if(weekDay==7){
                    weekDay=1;
                }else{
                    weekDay=weekDay+1;
                }
                weeks=weeks+weekDay+",";
            }
            weeks= weeks.substring(0,weeks.length()-1);



            cron = second + " " + minute + " " + hour + " ? * " + weeks;
        } catch (Exception e) {
            throw new BookBizException(BookBizException.ERROR, "时间格式错误");
        }
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setJobGroup("book");
        scheduleJob.setJobName(self_push_SCHEDULE_PRE + addParamDTO.getId());
        scheduleJob.setCronExpression(cron);
        CallBackParam callBackParam = new CallBackParam();
        Map<String, Object> paramMap = new HashMap<>();
        //定时任务调用时用到的参数
        paramMap.put("selfPushId", addParamDTO.getId());
        callBackParam.setParamMap(paramMap);
        callBackParam.setMethodName("sendSelfMsgQuartz");
        callBackParam.setBeanName("selfPushService");
        Map<String, Object> scheduleMap = new HashMap<>();
        scheduleMap.put("scheduleJob", scheduleJob);
        scheduleMap.put("callBackParam", callBackParam);
        try {
            scheduleService.addCronJob(scheduleMap);
        } catch (Exception e) {
            LOGGER.error("设置定时任务失败" + e.getMessage(), e);
            throw new BookBizException(BookBizException.ERROR, "定时任务设置失败");
        }
    }


    @ParamLog("按天设置定时任务")
    private void pushDay(SelfPush addParamDTO) {
        String cron;
        String putTime = addParamDTO.getPushSendTime();
        try {
            int hour = Integer.parseInt(putTime.substring(0, 2));
            int minute = Integer.parseInt(putTime.substring(3, 5));
            int second = Integer.parseInt(putTime.substring(6, 8));
            cron = second + " " + minute + " " + hour + " * * ?";
        } catch (Exception e) {
            throw new BookBizException(BookBizException.ERROR, "时间格式错误");
        }
        ScheduleJob scheduleJob = new ScheduleJob();
        scheduleJob.setJobGroup("book");
        scheduleJob.setJobName(self_push_SCHEDULE_PRE + addParamDTO.getId());
        scheduleJob.setCronExpression(cron);
        CallBackParam callBackParam = new CallBackParam();
        Map<String, Object> paramMap = new HashMap<>();
        //定时任务调用时用到的参数
        paramMap.put("selfPushId", addParamDTO.getId());
        callBackParam.setParamMap(paramMap);
        callBackParam.setMethodName("sendSelfMsgQuartz");
        callBackParam.setBeanName("selfPushService");
        Map<String, Object> scheduleMap = new HashMap<>();
        scheduleMap.put("scheduleJob", scheduleJob);
        scheduleMap.put("callBackParam", callBackParam);
        try {
            scheduleService.addCronJob(scheduleMap);
        } catch (Exception e) {
            LOGGER.error("设置定时任务失败" + e.getMessage(), e);
            throw new BookBizException(BookBizException.ERROR, "定时任务设置失败");
        }
    }

    /**
     * 添加定时任务
     */
    private void addSendQuartzJob(Long pushId, String sendTime) {
        ScheduleJob scheduleJob = new ScheduleJob();
        CallBackParam callBackParam = new CallBackParam();
        Map<String, Object> map = new HashMap<>();
        map.put("pushId", pushId);
        scheduleJob.setJobGroup(PushConstant.JOB_GROUP_SELF_PUSH);
        scheduleJob.setJobName(PushConstant.JOB_NAME_SELF_PUSH + pushId);

        Long second = (DateUtils.StringToDateTime(sendTime).getTime() - System.currentTimeMillis()) / 1000;
        scheduleJob.setStartTime(second.intValue());
        scheduleJob.setStartTimeFormat("ss");
        scheduleJob.setRepeatCount(0);
        scheduleJob.setIntervalTime(0);
        scheduleJob.setIntervalTimeFormat("dd");

        callBackParam.setBeanName("selfPushService");
        callBackParam.setMethodName("sendSelfMsgQuartz");
        callBackParam.setParamMap(map);
        Map<String, Object> scheduleMap = new HashMap<>();
        scheduleMap.put("scheduleJob", scheduleJob);
        scheduleMap.put("callBackParam", callBackParam);
        try {
            scheduleService.addSimpleJob(scheduleMap);
        } catch (Exception e) {
            log.error("【个人号群发】添加定时任务失败" + e.getMessage(), e);
        }
    }

    /**
     * 群发消息推送
     */
    private void msgPush(List<String> userIdList, List<SelfPushItem> itemList, Long pushId) {
        SelfPush selfPush = selfPushDao.getById(pushId);
        if (!StringUtil.isEmpty(selfPush.getAltId())){//平台端群发
            String altId = selfPush.getAltId();
            List<String> sendUserIds = new ArrayList<>();
            sendUserIds.addAll(userIdList);
            ThreadPoolUtils.SEND_MESSAGE_THREAD_POOL.execute(() -> {
                if(itemList.size()==1&&itemList.get(0).getPersonalAppletsId()!=null){
                    for (SelfPushItem pushItem : itemList) {
                        String uuid1= UUID.randomUUID().toString();
                        sendSelfMsgNew(sendUserIds, altId, pushItem, uuid1, itemList.indexOf(pushItem),itemList.size());
                    }
                }
                for (String userId : sendUserIds) {
                    String uuid= UUID.randomUUID().toString();
                    for (SelfPushItem pushItem : itemList) {
                        if (AltTypeEnum.WECHAT.code.equals(selfPush.getAltType())){
                            sendSelfMsg(userId, altId, pushItem, uuid, itemList.indexOf(pushItem),itemList.size());
                        } else if (AltTypeEnum.QQ.code.equals(selfPush.getAltType())){
                            sendSelfMsg4QQ(userId, altId, pushItem);
                        }
                    }
                }
                this.updatePushStatusByPushId(PushStatusEnum.SUCCESS.value, pushId);
            });
        }else if ( null != selfPush.getBookGroupId()){//编辑端群发
            Long bookGroupId = selfPush.getBookGroupId();
            if ("pro".equals(envStr) && ArrayUtils.contains(PushConstant.pro_demo_book_group_id,bookGroupId)) {
                //生产环境特定社群书，发给所有好友
                userIdList = bookGroupCipherUserDao.getFriendIdsByBookGroupId(bookGroupId);
            } else if ("uat".equalsIgnoreCase(envStr) && ArrayUtils.contains(PushConstant.uat_demo_book_group_id, bookGroupId)){
                userIdList = bookGroupCipherUserDao.getFriendIdsByBookGroupId(bookGroupId);
            }
            List<String> sendUserIds = new ArrayList<>();
            sendUserIds.addAll(userIdList);
            ThreadPoolUtils.SEND_MESSAGE_THREAD_POOL.execute(() -> {
                for (String userId : sendUserIds) {
                    //查好友对应的小号
                    SelfRobotBookGroupDTO bookGroupDTO = bookGroupCipherUserDao.getSelfRobotBookGroupInfoByUser(userId, bookGroupId);
                    String altId = bookGroupDTO.getWxId();
                    String uuid= UUID.randomUUID().toString();
                    for (SelfPushItem pushItem : itemList) {
                        if (AltTypeEnum.WECHAT.code.equals(selfPush.getAltType())) {
                            sendSelfMsg(userId, altId, pushItem, uuid, itemList.indexOf(pushItem), itemList.size());
                        }else if (AltTypeEnum.QQ.code.equals(selfPush.getAltType())){
                            sendSelfMsg4QQ(userId, altId, pushItem);
                        }
                    }
                }
                this.updatePushStatusByPushId(PushStatusEnum.SUCCESS.value, pushId);
            });
        }

    }

    private void sendSelfMsg4QQ(String userId, String altId, SelfPushItem selfPushItem) {
        if (StringUtil.isEmpty(userId) || StringUtil.isEmpty(altId)){
            return;
        }
        if(pcloudRobotBiz.getUserTdState(altId, userId) == 1) {
            return;
        }
        Integer itemType = selfPushItem.getItemType();
        PrivateMsgSendVO privateMsgSendVO = new PrivateMsgSendVO();
        privateMsgSendVO.setSenderQQCode(Long.valueOf(altId));
        privateMsgSendVO.setReceiverQQCode(Long.valueOf(userId));
        if (ItemTypeEnum.TEXT.value.equals(itemType)) {
            // 构造一个文本消息
            String message = new MessageBuilder().add(new ComponentText(selfPushItem.getTextContent())).toString();// 文本消息
            privateMsgSendVO.setMessage(message);
            wechatGroupConsr.sendMessage4QQ(privateMsgSendVO);
            return;
        }
        if (ItemTypeEnum.IMAGE.value.equals(itemType)) {
            // 构造一个图片消息
            String message = new MessageBuilder().add(new ComponentImage(selfPushItem.getImageUrl())) .toString(); // 图片消息
            privateMsgSendVO.setMessage(message);
            wechatGroupConsr.sendMessage4QQ(privateMsgSendVO);
            return;
        }
        if (ItemTypeEnum.AUDIO.value.equals(itemType)) {
            Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(selfPushItem.getResourceId()));
            ResourceDTO resourceDTO = map.get(selfPushItem.getResourceId());
            if (resourceDTO != null && !StringUtil.isEmpty(resourceDTO.getFileUrl())) {
                // 构造一个文件消息
                String message = new MessageBuilder().add(new ComponentRecord(resourceDTO.getFileUrl(),false)).toString();
                privateMsgSendVO.setMessage(message);
                wechatGroupConsr.sendMessage4QQ(privateMsgSendVO);
            }
            return;
        }
    }

    /**
     * 群发项设置
     */
    private void setSelfPushItem(Long pushId, Boolean sendNow, Long partyId, List<SelfPushItem> itemList, Date sendTime,Long personalAppletsId,Integer itemType) {
        Integer status;
        if (sendNow) {
            status = PushStatusEnum.PUSHING.value;
        } else {
            status = PushStatusEnum.WAIT.value;
        }
        itemList.forEach(selfPushItem -> {
            selfPushItem.setCreateUser(partyId);
            selfPushItem.setUpdateUser(partyId);
            selfPushItem.setPushId(pushId);
            selfPushItem.setPushStatus(status);
            selfPushItem.setSendTime(sendTime);
            if(personalAppletsId!=null&&personalAppletsId!=0L) {
                selfPushItem.setPersonalAppletsId(personalAppletsId);
            }
        });
        selfPushItemDao.insert(itemList);
    }
    /**
     * 群发用户设置
     */
    private void setSelfPushUser(List<String> userIdList, Long partyId, Long pushId) {
        List<SelfPushUser> userList = new ArrayList<>();
        for (String userId : userIdList) {
            SelfPushUser user = new SelfPushUser();
            user.setWxUserId(userId);
            userList.add(user);
        }
        userList.forEach(selfPushUser -> {
            selfPushUser.setCreateUser(partyId);
            selfPushUser.setPushId(pushId);
        });
        selfPushUserDao.insert(userList);
    }

    /**
     * 消息群发
     * @param userWxId
     * @param altId
     * @param selfPushItem
     */
    public void sendSelfMsg(String userWxId, String altId, SelfPushItem selfPushItem, String uuid, Integer index, Integer counts) {
        if (StringUtil.isEmpty(userWxId) || StringUtil.isEmpty(altId)){
            return;
        }
        if(pcloudRobotBiz.getUserTdState(altId, userWxId) == 1) {
            return;
        }
        RobotProcessTypeEnum robotProcessType = RobotProcessTypeEnum.SELF_PUSH;
        Integer code = SendMessageTypeEnum.SELF.getCode();
        Integer itemType = selfPushItem.getItemType();
        if (ItemTypeEnum.TEXT.value.equals(itemType)) {
            SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
            sendTextMessageVO.setContent(selfPushItem.getTextContent());
            sendTextMessageVO.setCode(code);
            sendTextMessageVO.setWxId(altId);
            sendTextMessageVO.setAltId(altId);
            sendTextMessageVO.setWxGroupId(userWxId);
            sendTextMessageVO.setIp(getIpByRobot(altId));
            sendTextMessageVO.setMessageGroupId(uuid);
            sendTextMessageVO.setRobotProcessType(robotProcessType);
            sendTextMessageVO.setIndex(index);
            sendTextMessageVO.setCounts(counts);
            wechatGroupConsr.sendMessage(JSON.toJSONString(sendTextMessageVO));
            return;
        }
        if (ItemTypeEnum.LINK.value.equals(itemType)) {
            SendArticleMessageVO sendArticleMessageVO = new SendArticleMessageVO();
            sendArticleMessageVO.setCode(code);
            sendArticleMessageVO.setAltId(altId);
            sendArticleMessageVO.setDescription(selfPushItem.getLinkDescription());
            sendArticleMessageVO.setWxGroupId(userWxId);
            String url = selfPushItem.getLinkUrl();
            sendArticleMessageVO.setLinkUrl(url);
            sendArticleMessageVO.setPicUrl(selfPushItem.getLinkImageUrl());
            sendArticleMessageVO.setTitle(selfPushItem.getLinkTitle());
            sendArticleMessageVO.setIp(getIpByRobot(altId));
            sendArticleMessageVO.setMessageGroupId(uuid);
            sendArticleMessageVO.setRobotProcessType(robotProcessType);
            sendArticleMessageVO.setIndex(index);
            sendArticleMessageVO.setCounts(counts);
            wechatGroupConsr.sendMessage(JSON.toJSONString(sendArticleMessageVO));
            return;
        }
        if (ItemTypeEnum.APP.value.equals(itemType)) {
            AppOrProductReplyDTO appOrProductReplyDTO  = new AppOrProductReplyDTO();
            appOrProductReplyDTO.setIp(getIpByRobot(altId));
            appOrProductReplyDTO.setLinkUrl(selfPushItem.getLinkUrl());
            appOrProductReplyDTO.setRobotWxId(altId);
            appOrProductReplyDTO.setUserWxId(userWxId);
            appOrProductReplyDTO.setSendMessageType(code);
            appOrProductReplyDTO.setRobotProcessTypeEnum(robotProcessType);
            appOrProductReplyDTO.setCounts(counts);
            appOrProductReplyDTO.setIndex(index);
            appOrProductReplyDTO.setMessageGroupId(uuid);
            //发送应用
            if(selfPushItem.getAppId() != null) {
                appOrProductReplyDTO.setServeType(AppAndProductTypeEnum.APP.value);
                appOrProductReplyDTO.setServeId(selfPushItem.getAppId());
                pcloudRobotSet.sendAppOrProductReply(appOrProductReplyDTO);
            }
            //发送作品
            if(selfPushItem.getProductId() != null) {
                appOrProductReplyDTO.setServeType(AppAndProductTypeEnum.PRODUCT.value);
                appOrProductReplyDTO.setServeId(selfPushItem.getProductId());
                pcloudRobotSet.sendAppOrProductReply(appOrProductReplyDTO);
            }
            return;//应用类型参与群发C1002391
        }
        if (ItemTypeEnum.IMAGE.value.equals(itemType)) {
            SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
            sendPicMessageVO.setCode(code);
            sendPicMessageVO.setAltId(altId);
            sendPicMessageVO.setWxGroupId(userWxId);
            sendPicMessageVO.setPicUrl(selfPushItem.getImageUrl());
            sendPicMessageVO.setIp(getIpByRobot(altId));
            sendPicMessageVO.setMessageGroupId(uuid);
            sendPicMessageVO.setRobotProcessType(robotProcessType);
            sendPicMessageVO.setIndex(index);
            sendPicMessageVO.setCounts(counts);
            wechatGroupConsr.sendMessage(JSON.toJSONString(sendPicMessageVO));
            return;
        }
        if (ItemTypeEnum.RESOURCE.value.equals(itemType)) {
            SendFileVO sendFileVO = new SendFileVO();
            Map<Long, ResourceDTO> map = resourceConsr.mapByIds(Arrays.asList(selfPushItem.getResourceId()));
            ResourceDTO resourceDTO = map.get(selfPushItem.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(getIpByRobot(altId));
            sendFileVO.setAltId(altId);
            sendFileVO.setWxId(userWxId);
            sendFileVO.setMessageGroupId(uuid);
            sendFileVO.setRobotProcessType(robotProcessType);
            sendFileVO.setIndex(index);
            sendFileVO.setCounts(counts);
            wechatGroupConsr.sendMessage(JSON.toJSONString(sendFileVO));
        }

    }
    /**
     * 小程序群发
     * @param userWxIds
     * @param altId
     * @param selfPushItem
     */
    public void sendSelfMsgNew(List<String> userWxIds, String altId, SelfPushItem selfPushItem, String uuid, Integer index, Integer counts) {
        if (ListUtils.isEmpty(userWxIds) || StringUtil.isEmpty(altId)){
            return;
        }
        RobotProcessTypeEnum robotProcessType = RobotProcessTypeEnum.SELF_PUSH;
        Integer code = SendMessageTypeEnum.SELF.getCode();
        Integer itemType = selfPushItem.getItemType();
        if (ItemTypeEnum.PERSANALAPPLETS.value.equals(itemType)){
            SendMomentsDTO sendMomentsDTO=new SendMomentsDTO();
            //发送的小程序
            PersonalApplets byId = personalAppletsDao.getById(selfPushItem.getPersonalAppletsId());
            if(byId==null){
                return;
            }
            GroupRobotDTO info = wechatGroupConsr.getGroupRobotByRobotId(altId);
            if (info!=null){
                sendMomentsDTO.setIsMasterWx(info.getMasterWx());
                sendMomentsDTO.setReceiveAccount(info.getMac());
            }
            sendMomentsDTO.setMomentType(BusinessConstant.MomentTypeEnum.SEND_WX_MINI);
            sendMomentsDTO.setContent(byId.getAppletsId());//小程序id
            sendMomentsDTO.setLink(byId.getAppletsUrl() + "?wxId=" + userWxIds.get(0));//小程序访问地址增加参数
            sendMomentsDTO.setImages(userWxIds);//发送人
            sendMomentsDTO.setLinkTitle(byId.getSlogan());//小程序宣传语
            sendMomentsDTO.setLinkDesc(byId.getSloganImgUrl());//小程序宣传图
            sendMomentsDTO.setIp(getIpByRobot(altId));
            sendMomentsDTO.setMessageGroupId(uuid);
            sendMomentsDTO.setCounts(counts);
            sendMomentsDTO.setIndex(index);
            sendMomentsDTO.setCode(code);
            sendMomentsDTO.setRobotProcessType(robotProcessType);
            sendMomentsDTO.setAltId(altId);
            sendMomentsDTO.setWxId(userWxIds.get(0));
            wechatGroupConsr.sendMessage(JSON.toJSONString(sendMomentsDTO));
        }
    }


    /**
     * 获取ip
     * @param altId
     * @return
     */
    private String getIpByRobot(String altId) {
        String ip = null;
        GroupRobotDTO groupRobotDTO = wechatGroupConsr.getGroupRobotByWxId(altId);
        if (null != groupRobotDTO) {
            WeixinQrcodeGeneration weixinQrcodeGeneration = weixinQrcodeGenerationDao.getByGeneration(groupRobotDTO.getVersion());
            if (null != weixinQrcodeGeneration) {
                ip = weixinQrcodeGeneration.getWechatGroupIp();
            }
        }
        return ip;
    }

    @Override
    public PageBeanNew<UserBookInfoVO> listSelfPushUser(Long pushId, Integer currentPage, Integer numPerPage) {
        SelfPush selfPush = selfPushDao.getById(pushId);
        if (null == selfPush){
            throw new BookBizException(BookBizException.ERROR,"群发记录不存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pushId", pushId);
        PageBeanNew<UserBookInfoVO> pageBeanNew = selfPushUserDao.listPageNew(new PageParam(currentPage, numPerPage), map, "listByPushId");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        Boolean isXIAORUI = false;//小睿群发
        if (!StringUtil.isEmpty(selfPush.getAltId())){
            PcloudRobot pcloudRobot = pcloudRobotBiz.getPcloudRobotByWxId(selfPush.getAltId());
            if (null != pcloudRobot){
                isXIAORUI = true;
            }
        }
        if (isXIAORUI){//小睿无扫码书刊标签
            List<String> wxUserIds = pageBeanNew.getRecordList().stream().filter(s -> s.getWxUserId() != null).map(UserBookInfoVO::getWxUserId).distinct().collect(Collectors.toList());
            Map<String, GroupUserDTO> userDTOMap = wechatGroupConsr.mapWxUserInfoByWxIdListAndType(wxUserIds,selfPush.getAltType());
            for (UserBookInfoVO userBookInfoVO : pageBeanNew.getRecordList()) {
                if (!MapUtils.isEmpty(userDTOMap) && userDTOMap.containsKey(userBookInfoVO.getWxUserId())) {
                    GroupUserDTO userDTO = userDTOMap.get(userBookInfoVO.getWxUserId());
                    userBookInfoVO.setHeadPic(userDTO.getHeadPic());
                    userBookInfoVO.setNickName(userDTO.getNickName());
                    userBookInfoVO.setSex(userDTO.getSex());
                }
            }
        }else {
            groupSet.setUserBookInfo4SelfPush(pageBeanNew.getRecordList());
        }
        return pageBeanNew;
    }

    @Override
    public PageBeanNew<SelfPushRecordDTO> listSelfPushRecord(Integer currentPage, Integer numPerPage, String startTime, String endTime, Integer status,Long partyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("pushStatus", status);
        map.put("partyId", partyId);
        PageBeanNew<SelfPushRecordDTO> pageBeanNew = selfPushDao.listPageNew(new PageParam(currentPage, numPerPage), map, "listSelfPush");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        //填充群发时间
        setSelfPushTime(pageBeanNew.getRecordList());
        //填充群发人数和关联书刊
        fillPushItemsAndBookName(pageBeanNew.getRecordList());
        //填充个人号信息、群发创建人信息
        List<String> wxIds = pageBeanNew.getRecordList().stream().filter(s -> !StringUtil.isEmpty(s.getAltId())).map(SelfPushRecordDTO::getAltId).distinct().collect(Collectors.toList());
        Map<String, GroupUserDTO> robotMap = new HashMap<>();
        Map<String, RobotClassifyDTO> robotClassifyDTOMap =new HashMap<>();
        if (!ListUtils.isEmpty(wxIds)){
            robotMap = wechatGroupConsr.mapRobotInfoByIdList(wxIds);
            robotClassifyDTOMap=pcloudRobotBiz.mapByIds4Classify(wxIds);
        }
        List<Long> pcloudPartyIds = pageBeanNew.getRecordList().stream().filter(s->!StringUtil.isEmpty(s.getAltId())).map(SelfPushRecordDTO::getCreateUser).distinct().collect(Collectors.toList());
        Map<Long, UserLogin> loginMap = new HashMap<>();
        if (!ListUtils.isEmpty(pcloudPartyIds)){
            for (Long id : pcloudPartyIds){
                if (id != 0L){
                    UserLogin userLogin = partyConsr.getUserLoginInfoByPartyId(id,SystemCode.pcloud.code,"0");
                    loginMap.put(id,userLogin);
                }
            }
        }
        for (SelfPushRecordDTO dto : pageBeanNew.getRecordList()) {
            if (!MapUtils.isEmpty(robotMap) && !StringUtil.isEmpty(dto.getAltId()) && robotMap.containsKey(dto.getAltId())) {
                GroupUserDTO userDTO = robotMap.get(dto.getAltId());
                dto.setRobotName(userDTO.getNickName());
            }
            if (!MapUtils.isEmpty(robotClassifyDTOMap) && !StringUtil.isEmpty(dto.getAltId()) && robotClassifyDTOMap.containsKey(dto.getAltId())) {
                RobotClassifyDTO robotClassifyDTO = robotClassifyDTOMap.get(dto.getAltId());
                dto.setClassifyId(null!=robotClassifyDTO?robotClassifyDTO.getClassifyId():null);
                dto.setClassifyName(null!=robotClassifyDTO?robotClassifyDTO.getClassifyName():null);
                dto.setUniqueNumber(null!=robotClassifyDTO?robotClassifyDTO.getUniqueNumber():null);
            }
            if (!StringUtil.isEmpty(dto.getAltId())){//平台端登录账号
                if (dto.getCreateUser() == 0L){
                    dto.setUserName("pcloud");
                }else if (!MapUtils.isEmpty(loginMap) && loginMap.containsKey(dto.getCreateUser())){
                    UserLogin userLogin = loginMap.get(dto.getCreateUser());
                    dto.setUserName(null == userLogin? "":userLogin.getUserName());
                }
            }
        }
        return pageBeanNew;
    }

    private void setSelfPushTime(List<SelfPushRecordDTO> recordList) {
        if (ListUtils.isEmpty(recordList)){
            return;
        }
        for (SelfPushRecordDTO dto:recordList) {
            String realSendTime="";
            if(dto.getPushType()!=null&&dto.getPushType()==1){
                realSendTime=DateUtils.formatDate(dto.getStartTime(),"yyyy-MM-dd")+"至"+DateUtils.formatDate(dto.getEndTime(),"yyyy-MM-dd")+"；";
                realSendTime=realSendTime+"每天；"+dto.getPushSendTime();
                dto.setRealSendTime(realSendTime);
            }else if(dto.getPushType()!=null&&dto.getPushType()==2){
                String weekDays = dto.getWeekDays();
                realSendTime=DateUtils.formatDate(dto.getStartTime(),"yyyy-MM-dd")+"至"+DateUtils.formatDate(dto.getEndTime(),"yyyy-MM-dd")+"；";
                if(weekDays.contains("1")){
                    weekDays= weekDays.replace("1","周一");
                }
                if(weekDays.contains("2")){
                    weekDays= weekDays.replace("2","周二");
                }
                if(weekDays.contains("3")){
                    weekDays= weekDays.replace("3","周三");
                }
                if(weekDays.contains("4")){
                    weekDays= weekDays.replace("4","周四");
                }
                if(weekDays.contains("5")){
                    weekDays= weekDays.replace("5","周五");
                }
                if(weekDays.contains("6")){
                    weekDays= weekDays.replace("6","周六");
                }
                if(weekDays.contains("7")){
                    weekDays= weekDays.replace("7","周日");
                }

                realSendTime=realSendTime+weekDays+"；"+dto.getPushSendTime();
                dto.setRealSendTime(realSendTime);
            }else{
                if (null!=dto.getSendTime()){
                    dto.setRealSendTime(DateUtils.formatDate(dto.getSendTime(),"yyyy-MM-dd HH:mm:ss"));
                }
            }
        }
    }

    private void fillPushItemsAndBookName(List<SelfPushRecordDTO> recordList) {
        List<Long> pushIds=new ArrayList<>();
        List<Long> bookGroupIds=new ArrayList<>();
        for (SelfPushRecordDTO dto:recordList) {
            if (null != dto.getBookGroupId()&&!bookGroupIds.contains(dto.getBookGroupId())){
                bookGroupIds.add(dto.getBookGroupId());
            }
            if (null != dto.getPushId()&&!pushIds.contains(dto.getPushId())){
                pushIds.add(dto.getPushId());
            }
        }
        Map<Long,List<SelfPushItem>> itemMap=new HashMap<>();
        Map<Long,String> bookNameMap=new HashMap<>();
        Map<Long,Integer> userCountMap=new HashMap<>();
        if (!ListUtils.isEmpty(pushIds)){
            List<SelfPushItem> selfPushItemList = selfPushItemDao.getByPushIds(pushIds);
            this.fillItem(selfPushItemList);
            itemMap=selfPushItemList.stream().collect(Collectors.groupingBy(SelfPushItem::getPushId));
            List<UserCountAndPushDTO> userCountList = selfPushUserDao.getCountByPushIds(pushIds);
            for (UserCountAndPushDTO userCountAndPushDTO:userCountList){
                userCountMap.put(userCountAndPushDTO.getPushId(),userCountAndPushDTO.getUserCount());
            }
        }
        if (!ListUtils.isEmpty(bookGroupIds)){
            List<BookGroupDTO> infos = bookGroupDao.getBookBaseInfoByIds(bookGroupIds);
            for (BookGroupDTO bookGroupDTO:infos){
                bookNameMap.put(bookGroupDTO.getId(),bookGroupDTO.getBookName());
            }
        }
        for (SelfPushRecordDTO dto:recordList) {
            dto.setSelfPushItemList(itemMap.get(dto.getPushId()));
            dto.setBookName(bookNameMap.get(dto.getBookGroupId()));
            dto.setUserCount(userCountMap.get(dto.getPushId()));
        }
    }

    private void fillItem(List<SelfPushItem> list) {
        if (ListUtils.isEmpty(list)){
            return;
        }
        List<Long> resourceIds = list.stream().filter(s->(s.getItemType().equals(ItemTypeEnum.RESOURCE.value) || s.getItemType().equals(ItemTypeEnum.AUDIO.value))).
                map(SelfPushItem::getResourceId).distinct().collect(Collectors.toList());
        Map<Long, ResourceDTO> resourceDTOMap=new HashMap<>();
        if (!ListUtils.isEmpty(resourceIds)){
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (SelfPushItem selfPushItem:list){
            if (ItemTypeEnum.RESOURCE.value.equals(selfPushItem.getItemType())){
                selfPushItem.setReplyType(ReplyTypeEnum.RESOURCE.value);
                ResourceDTO resourceDTO = resourceDTOMap.get(selfPushItem.getResourceId());
                if (resourceDTO!=null){
                    selfPushItem.setResourceName(resourceDTO.getResourceName());
                    selfPushItem.setResourceUrl(resourceDTO.getFileUrl());
                    selfPushItem.setResourceTypeCode(resourceDTO.getTypeCode());
                    selfPushItem.setResourceTypeName(resourceDTO.getTypeName());
                    selfPushItem.setFileType(resourceDTO.getFileType());
                    selfPushItem.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    selfPushItem.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                    selfPushItem.setFileSize(resourceDTO.getFileSize());
                }
            }
            if (ItemTypeEnum.TEXT.value.equals(selfPushItem.getItemType())){
                selfPushItem.setReplyType(ReplyTypeEnum.TEXT.value);
            }
            if (ItemTypeEnum.LINK.value.equals(selfPushItem.getItemType())){
                selfPushItem.setReplyType(ReplyTypeEnum.LINK.value);
            }
            if (ItemTypeEnum.APP.value.equals(selfPushItem.getItemType())){
                selfPushItem.setReplyType(ReplyTypeEnum.APP.value);
            }
            if (ItemTypeEnum.IMAGE.value.equals(selfPushItem.getItemType())){
                selfPushItem.setReplyType(ReplyTypeEnum.IMAGE.value);
            }
            if (ItemTypeEnum.AUDIO.value.equals(selfPushItem.getItemType())){
                selfPushItem.setReplyType(ReplyTypeEnum.AUDIO.value);
                ResourceDTO resourceDTO = resourceDTOMap.get(selfPushItem.getResourceId());
                if (resourceDTO!=null){
                    selfPushItem.setResourceName(resourceDTO.getResourceName());
                    selfPushItem.setResourceUrl(resourceDTO.getFileUrl());
                    selfPushItem.setResourceTypeCode(resourceDTO.getTypeCode());
                    selfPushItem.setResourceTypeName(resourceDTO.getTypeName());
                    selfPushItem.setFileType(resourceDTO.getFileType());
                    selfPushItem.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                    selfPushItem.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                    selfPushItem.setFileSize(resourceDTO.getFileSize());
                }
            }

        }
    }

    @Override
    public void sendSelfMsgQuartz(Long pushId) {
        SelfPush selfPush = selfPushDao.getById(pushId);
        if (null == selfPush) {
            return;
        }
        //判断时间范围
        if (selfPush.getPushType()!=null) {
            Date dateNow = new Date();
            Date startTime = selfPush.getStartTime();
            Date endTime = selfPush.getEndTime();
            if (startTime != null && dateNow.before(startTime)) {
                return;
            }
            if (endTime != null && dateNow.after(endTime)) {
                return;
            }
        }
        List<String> userIdList = selfPushUserDao.getUserIdListByPushId(pushId);
        if (selfPush.getSendAll() && !StringUtil.isEmpty(selfPush.getAltId())){//群发所有好友，更新发送好友列表
            userIdList = wechatGroupConsr.getFriendByRobotId(selfPush.getAltId(), selfPush.getAltType());
            selfPushUserDao.deleteByPushId(pushId);
            setSelfPushUser(userIdList, selfPush.getCreateUser(), pushId);
        }
        List<SelfPushItem> itemList = selfPushItemDao.getByPushId(pushId);
        if (ListUtils.isEmpty(userIdList) || ListUtils.isEmpty(itemList)) {
            return;
        }
        this.updatePushStatusByPushId(PushStatusEnum.PUSHING.value, pushId);
        msgPush(userIdList, itemList, pushId);
    }

    @Override
    public void deleteByPushId(Long pushId) {
        selfPushDao.deleteById(pushId);
        selfPushItemDao.deleteByPushId(pushId);
        selfPushUserDao.deleteByPushId(pushId);
        try {
            scheduleService.deleteJob(self_push_SCHEDULE_PRE + pushId, "book");
        } catch (Exception e) {
            log.error("删除定时任务失败,selfPushId+" + pushId);
        }
    }

    @Override
    @ParamLog("全部好友设置的群发复制")
    public void copyRobotData(String originRobot, String targetRobot) {
        List<SelfPush> selfPushList = selfPushDao.getUnclosedByRobot(originRobot);
        if (ListUtils.isEmpty(selfPushList)){
            return;
        }
        for (SelfPush selfPush :selfPushList){
            List<SelfPushItem> selfPushItemList = selfPushItemDao.getByPushId(selfPush.getId());
            List<String> userList = selfPushUserDao.getUserIdListByPushId(selfPush.getId());
            SelfPushAddParamDTO addParamDTO = new SelfPushAddParamDTO();
            addParamDTO.setAltId(targetRobot);
            addParamDTO.setSystemCode(SystemCode.pcloud.code);
            addParamDTO.setPushItemList(selfPushItemList);
            addParamDTO.setSendAll(true);
            addParamDTO.setSendNow(false);
            addParamDTO.setUserIdList(userList);
            addParamDTO.setPushType(selfPush.getPushType());
            addParamDTO.setWeekDays(selfPush.getWeekDays());
            addParamDTO.setSendTime(selfPush.getPushSendTime());
            if (null != selfPush.getStartTime()){
                addParamDTO.setStartTime(DateUtils.formatDate(selfPush.getStartTime()));
                addParamDTO.setEndTime(DateUtils.formatDate(selfPush.getEndTime()));
            }
            createSelfPush(selfPush.getCreateUser(), addParamDTO);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("修改个人号群发")
    @Override
    public void updateSelfPush(Long partyId, SelfPushAddParamDTO addParamDTO) {
        if (addParamDTO==null||addParamDTO.getPushId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数错误！");
        }
        //先查询群发状态
        Integer status = selfPushItemDao.getStatusByPushId(addParamDTO.getPushId());
        if (!PushStatusEnum.WAIT.value.equals(status)){
            throw new BookBizException(BookBizException.ERROR,"状态不为待发送，不能修改！");
        }
        deleteByPushId(addParamDTO.getPushId());
        createSelfPush(partyId,addParamDTO);
    }

    @ParamLog("获取个人号群发")
    @Override
    public SelfPush getSelfPush(Long pushId) {
        if (pushId==null){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"pushId不能为空！");
        }
        SelfPush selfPush = selfPushDao.getById(pushId);
        if (selfPush==null){
            throw new BookBizException(BookBizException.ERROR,"未找到！");
        }
        List<SelfPushItem> pushItems=selfPushItemDao.getByPushId(pushId);
        fillItem(pushItems);
        selfPush.setPushItems(pushItems);
        String altId=selfPush.getAltId();
        String altName=null;
        String altTypeName=null;
        PcloudRobot pcloudRobot = pcloudRobotBiz.getPcloudRobotByWxId(altId);
        if (pcloudRobot!=null){
            //小睿
            altName=pcloudRobot.getNickName();
            if (AltTypeEnum.WECHAT.code.equals(selfPush.getAltType())){
                altTypeName = LargeTempletEnum.XIAORUI.name;
            }  else if (AltTypeEnum.QQ.code.equals(selfPush.getAltType())){
                altTypeName = LargeTempletEnum.XIAORUI_QQ.name;
            }
        }else {
            //不是小睿
            Map<String, RobotBaseInfoDTO> mapRobotInfo = wechatGroupConsr.mapRobotInfo(Arrays.asList(altId));
            if (mapRobotInfo!=null&&mapRobotInfo.get(altId)!=null){
                RobotBaseInfoDTO robotBaseInfoDTO=mapRobotInfo.get(altId);
                altName=robotBaseInfoDTO.getNickName();
                altTypeName=LargeTempletEnum.getNameByCode(robotBaseInfoDTO.getLargeTemplet());
            }
        }
        selfPush.setAltName(altName);
        selfPush.setAltTypeName(altTypeName);
        return selfPush;
    }

    @Override
    public void createPersonalApplets(PersonalApplets applets) {
        personalAppletsDao.insert(applets);
    }

    @Override
    public void deleteAppletsById(Long id) {
        personalAppletsDao.deleteById(id);
    }

    @Override
    public void updatePersonalApplets(PersonalApplets applets) {
        personalAppletsDao.update(applets);
    }

    @Override
    public PageBeanNew<PersonalApplets> getAllApplets(String appletsId,String content,Integer currentPage,Integer numPerPage) {
        Map<String, Object> map = new HashMap<>();

        map.put("appletsId", appletsId);
        map.put("content", content);
       return personalAppletsDao.listPageNew(new PageParam(currentPage, numPerPage),map,"getAllApplets");
    }

    @Override
    public PageBeanNew<PersonalAppletsRecordDTO> getSendAppletsRecords(Integer currentPage, Integer numPerPage, String startTime, String endTime, Integer status, Long partyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        map.put("pushStatus", status);
        map.put("partyId", partyId);
        PageBeanNew<PersonalAppletsRecordDTO> pageBeanNew = selfPushItemDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getSendAppletsRecords");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        for (PersonalAppletsRecordDTO dto:pageBeanNew.getRecordList()) {
            String realSendTime="";
            if(dto.getPushType()!=null&&dto.getPushType()==1){
                realSendTime=DateUtils.formatDate(dto.getStartTime(),"yyyy-MM-dd")+"至"+DateUtils.formatDate(dto.getEndTime(),"yyyy-MM-dd")+";";
                realSendTime=realSendTime+"每天;"+dto.getPushSendTime();
                dto.setRealSendTime(realSendTime);
            }else if(dto.getPushType()!=null&&dto.getPushType()==2){
                String weekDays = dto.getWeekDays();
                realSendTime=DateUtils.formatDate(dto.getStartTime(),"yyyy-MM-dd")+"至"+DateUtils.formatDate(dto.getEndTime(),"yyyy-MM-dd")+";";
                if(weekDays.contains("1")){
                    weekDays= weekDays.replace("1","周一");
                }
                if(weekDays.contains("2")){
                    weekDays= weekDays.replace("2","周二");
                }
                if(weekDays.contains("3")){
                    weekDays= weekDays.replace("3","周三");
                }
                if(weekDays.contains("4")){
                    weekDays= weekDays.replace("4","周四");
                }
                if(weekDays.contains("5")){
                    weekDays= weekDays.replace("5","周五");
                }
                if(weekDays.contains("6")){
                    weekDays= weekDays.replace("6","周六");
                }
                if(weekDays.contains("7")){
                    weekDays= weekDays.replace("7","周日");
                }

                realSendTime=realSendTime+weekDays+";"+dto.getPushSendTime();
                dto.setRealSendTime(realSendTime);
            }else{
                dto.setRealSendTime(DateUtils.formatDate(dto.getSendTime(),"yyyy-MM-dd HH:mm:ss"));
            }
        }
        List<String> wxIds = pageBeanNew.getRecordList().stream().filter(s -> !StringUtil.isEmpty(s.getAltId())).map(PersonalAppletsRecordDTO::getAltId).distinct().collect(Collectors.toList());
        Map<String, GroupUserDTO> robotMap = new HashMap<>();
        Map<String, RobotClassifyDTO> robotClassifyDTOMap =new HashMap<>();
        if (!ListUtils.isEmpty(wxIds)){
            robotMap = wechatGroupConsr.mapRobotInfoByIdList(wxIds);
            robotClassifyDTOMap=pcloudRobotBiz.mapByIds4Classify(wxIds);
        }

        List<Long> pcloudPartyIds = pageBeanNew.getRecordList().stream().filter(s->!StringUtil.isEmpty(s.getAltId())).map(PersonalAppletsRecordDTO::getCreateUser).distinct().collect(Collectors.toList());
        Map<Long, UserLogin> loginMap = new HashMap<>();
        if (!ListUtils.isEmpty(pcloudPartyIds)){
            for (Long id : pcloudPartyIds){
                if (id == 0L){
                    continue;
                }
                UserLogin userLogin = partyConsr.getUserLoginInfoByPartyId(id,SystemCode.pcloud.code,"0");
                loginMap.put(id,userLogin);
            }
        }
        for (PersonalAppletsRecordDTO dto : pageBeanNew.getRecordList()) {
            if (!MapUtils.isEmpty(robotMap) && !StringUtil.isEmpty(dto.getAltId()) && robotMap.containsKey(dto.getAltId())) {
                GroupUserDTO userDTO = robotMap.get(dto.getAltId());
                dto.setRobotName(userDTO.getNickName());
            }
            if (!MapUtils.isEmpty(robotClassifyDTOMap) && !StringUtil.isEmpty(dto.getAltId()) && robotClassifyDTOMap.containsKey(dto.getAltId())) {
                RobotClassifyDTO robotClassifyDTO = robotClassifyDTOMap.get(dto.getAltId());
                dto.setClassifyId(null!=robotClassifyDTO?robotClassifyDTO.getClassifyId():null);
                dto.setClassifyName(null!=robotClassifyDTO?robotClassifyDTO.getClassifyName():null);
                dto.setUniqueNumber(null!=robotClassifyDTO?robotClassifyDTO.getUniqueNumber():null);
            }
            if (!StringUtil.isEmpty(dto.getAltId())){//平台端登录账号
                if (dto.getCreateUser() == 0L){
                    dto.setUserName("pcloud");
                }else if (!MapUtils.isEmpty(loginMap) && loginMap.containsKey(dto.getCreateUser())){
                    UserLogin userLogin = loginMap.get(dto.getCreateUser());
                    dto.setUserName(null == userLogin? "":userLogin.getUserName());
                }
            }
        }
        return pageBeanNew;
    }

    @Override
    public PersonalApplets getAppletsById(Long id) {
        return personalAppletsDao.getById(id);
    }


    /**
     * 更新发送状态
     * @param pushStatus
     * @param pushId
     */
    public void updatePushStatusByPushId(Integer pushStatus, Long pushId){
        selfPushItemDao.updatePushStatusByPushId(pushStatus, pushId);
        selfPushDao.updatePushStatusById(pushStatus, pushId);
    }
}
