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

import com.pcloud.appcenter.app.dto.AppDto;
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.set.GroupSet;
import com.pcloud.book.group.vo.UserBookInfoVO;
import com.pcloud.book.guide.dto.PcloudGuideMessageDTO;
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.set.PcloudRobotSet;
import com.pcloud.book.push.biz.SelfPushBiz;
import com.pcloud.book.push.constant.PushConstant;
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.SelfPushAddParamDTO;
import com.pcloud.book.push.dto.SelfPushRecordDTO;
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.ItemTypeEnum;
import com.pcloud.book.push.enums.PushStatusEnum;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
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.resourcecenter.product.dto.ProductDto;
import com.pcloud.usercenter.user.entity.UserLogin;
import com.pcloud.wechatgroup.group.dto.GroupRobotDTO;
import com.pcloud.wechatgroup.group.dto.GroupUserDTO;
import com.sdk.wxgroup.*;
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 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;

    private static final String self_push_SCHEDULE_PRE = "self_push_";


    @Override
    public void createSelfPush(Long partyId, SelfPushAddParamDTO addParamDTO) {
        Boolean sendNow = addParamDTO.getSendNow();
        //群发
        SelfPush selfPush = new SelfPush();
        selfPush.setCreateUser(partyId);
        selfPush.setUpdateUser(partyId);
        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.setUserIdList(userIdList);
            }
            selfPush.setSendAll(addParamDTO.getSendAll());
        }
        selfPush.setSendNow(sendNow);
        if (sendNow) {
            selfPush.setSendTime(new Date());
        } else {
            selfPush.setPushSendTime(addParamDTO.getSendTime());
            selfPush.setStartTime(DateUtils.getDateByStr(addParamDTO.getStartTime()));
            selfPush.setEndTime(DateUtils.getDateByStr(addParamDTO.getEndTime()));
            selfPush.setPushType(addParamDTO.getPushType());
            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());
        //群发用户
        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(() -> {
                for (String userId : sendUserIds) {
                    for (SelfPushItem pushItem : itemList) {
                        sendSelfMsg(userId, altId, pushItem);
                    }
                }
                selfPushItemDao.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();
                    for (SelfPushItem pushItem : itemList) {
                        sendSelfMsg(userId, altId, pushItem);
                    }
                }
                selfPushItemDao.updatePushStatusByPushId(PushStatusEnum.SUCCESS.value, pushId);
            });
        }

    }

    /**
     * 群发项设置
     */
    private void setSelfPushItem(Long pushId, Boolean sendNow, Long partyId, List<SelfPushItem> itemList, Date sendTime) {
        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);
        });
        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) {
        if (StringUtil.isEmpty(userWxId) || StringUtil.isEmpty(altId)){
            return;
        }
        if(pcloudRobotBiz.getUserTdState(altId, userWxId) == 1) {
            return;
        }
        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));
            WxGroupSDK.sendTextMessage(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));
            WxGroupSDK.sendArticleMessage(sendArticleMessageVO);
            return;
        }
        if (ItemTypeEnum.APP.value.equals(itemType)) {
            //发送应用
            if(selfPushItem.getAppId() != null) {
                pcloudRobotSet.sendAppOrProductReply(AppAndProductTypeEnum.APP.value, selfPushItem.getAppId(),
                        selfPushItem.getLinkUrl(), altId,userWxId, getIpByRobot(altId), code);
            }
            //发送作品
            if(selfPushItem.getProductId() != null) {
                pcloudRobotSet.sendAppOrProductReply(AppAndProductTypeEnum.PRODUCT.value, selfPushItem.getProductId(),
                        selfPushItem.getLinkUrl(), altId, userWxId, getIpByRobot(altId), code);
            }
            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));
            WxGroupSDK.sendPicMessage(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);
            WxGroupSDK.sendFile(sendFileVO);
        }
    }

    /**
     * 获取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) {
        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<>());
        }
        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 = selfPushItemDao.listPageNew(new PageParam(currentPage, numPerPage), map, "listSelfPushRecord");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        for (SelfPushRecordDTO 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<SelfPushItem> selfPushItemList = selfPushItemDao.getByPushId(dto.getPushId());
            this.fillItem(selfPushItemList);
            dto.setSelfPushItemList(selfPushItemList);

        }
        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){
                    continue;
                }
                UserLogin userLogin = partyConsr.getUserLoginInfoByPartyId(id,SystemCode.pcloud.code,"0");
                loginMap.put(id,userLogin);
            }
        }
        for (SelfPushRecordDTO dto : pageBeanNew.getRecordList()) {
            Integer userCount = selfPushUserDao.getCountByPushId(dto.getPushId());
            dto.setUserCount(userCount);
            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 (null != dto.getBookGroupId()){
                BookGroupDTO bookGroupDTO = bookGroupDao.getBookBaseInfoById(dto.getBookGroupId());
                dto.setBookName(bookGroupDTO.getBookName());
            }
            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 fillItem(List<SelfPushItem> list) {
        if (ListUtils.isEmpty(list)){
            return;
        }
        List<Long> resourceIds = list.stream().filter(s->s.getItemType().equals(ItemTypeEnum.RESOURCE.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);
            }
        }
    }

    @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());
            selfPushUserDao.deleteByPushId(pushId);
            setSelfPushUser(userIdList, selfPush.getCreateUser(), pushId);
        }
        List<SelfPushItem> itemList = selfPushItemDao.getByPushId(pushId);
        if (ListUtils.isEmpty(userIdList) || ListUtils.isEmpty(itemList)) {
            return;
        }
        selfPushItemDao.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);
        }
    }
}
