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

import com.google.common.collect.Lists;

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.guide.biz.PcloudRobotWakeUpBiz;
import com.pcloud.book.guide.dto.WakeUpInfoDto;
import com.pcloud.book.guide.entity.PcloudRobotWakeup;
import com.pcloud.book.guide.entity.PcloudRobotWakeupClassify;
import com.pcloud.book.guide.entity.PcloudWakeupMessage;
import com.pcloud.book.guide.mapper.PcloudRobotWakeupClassifyMapper;
import com.pcloud.book.guide.mapper.PcloudRobotWakeupMapper;
import com.pcloud.book.guide.mapper.PcloudWakeupMessageMapper;
import com.pcloud.book.guide.vo.RobotWakeUpConfigVO;
import com.pcloud.book.guide.vo.RobotWakeUpMsgVO;
import com.pcloud.book.guide.vo.RobotWakeUpShowVO;
import com.pcloud.book.pcloudKeyword.dto.RobotClassifyDTO;
import com.pcloud.book.pcloudkeyword.biz.PcloudRobotBiz;
import com.pcloud.book.pcloudkeyword.dao.PcloudRobotDao;
import com.pcloud.book.pcloudkeyword.entity.PcloudRobot;
import com.pcloud.book.pcloudkeyword.facade.response.PcloudRobotClassifyResponseVO;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.exceptions.ParamCheck;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.facade.quartz.entity.CallBackParam;
import com.pcloud.facade.quartz.entity.ScheduleJob;
import com.pcloud.facade.quartz.service.ScheduleService;
import com.sdk.wxgroup.SendFileVO;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;
import lombok.extern.slf4j.Slf4j;

import org.codehaus.jackson.JsonParseException;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

import static com.pcloud.book.guide.constant.PcloudGuideRedisConstant.*;

@Component("pcloudRobotWakeUpBiz")
@Slf4j
public class PcloudRobotWakeUpBizImpl implements PcloudRobotWakeUpBiz {

    @Autowired
    private PcloudRobotWakeupMapper pcloudRobotWakeupMapper;

    @Autowired
    private PcloudRobotDao pcloudRobotDao;

    @Autowired
    private PcloudWakeupMessageMapper pcloudWakeupMessageMapper;

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private PcloudRobotBiz pcloudRobotBiz;
    @Autowired
    private PcloudRobotWakeupClassifyMapper pcloudRobotWakeupClassifyMapper;

    @Override
    public void robotWakeUpConfig(RobotWakeUpConfigVO robotWakeUpConfigVO) {
        Integer cycle = robotWakeUpConfigVO.getCycle();
        if (cycle == null || cycle < 1) {
            cycle = 1;
        }
        if (cycle > 23) {
            cycle = 23;
        }

        Integer lastDay = robotWakeUpConfigVO.getLastDay();
        if (lastDay == 1) {
            lastDay = 3;
        } else if (lastDay == 2) {
            lastDay = 7;
        } else if (lastDay == 3) {
            lastDay = DateUtils.getDayOfMonth(new Date());
        }
        PcloudRobotWakeup pcloudRobotWakeup = new PcloudRobotWakeup();
        pcloudRobotWakeup.setCreateTime(new Date());
        pcloudRobotWakeup.setCycle(cycle);
        pcloudRobotWakeup.setLast(lastDay);
        pcloudRobotWakeup.setStartTime(new Date());
        pcloudRobotWakeupMapper.insertSelective(pcloudRobotWakeup);

        List<Integer> classifyList = robotWakeUpConfigVO.getClassifyList();
        pcloudRobotDao.updateWakeUpByClassifyIds(classifyList);

        // 删除旧有消息配置
        pcloudWakeupMessageMapper.deleteAll();
        List<RobotWakeUpMsgVO> list = robotWakeUpConfigVO.getMsgVOList();
        if (list.size() > 3) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "最多配置三条消息");
        }

        for (RobotWakeUpMsgVO robotWakeUpMsgVO : list) {
            PcloudWakeupMessage pcloudWakeupMessage = new PcloudWakeupMessage();
            pcloudWakeupMessage.setCreateTime(new Date());
            if (robotWakeUpMsgVO.getReplyType() == 1) {
                pcloudWakeupMessage.setType("text");
                pcloudWakeupMessage.setTextContent(robotWakeUpMsgVO.getContent());
            } else if (robotWakeUpMsgVO.getReplyType() == 2) {
                pcloudWakeupMessage.setType("image");
                pcloudWakeupMessage.setImgUrl(robotWakeUpMsgVO.getPicUrl());
            } else if (robotWakeUpMsgVO.getReplyType() == 5) {
                String code = StringUtil.isEmpty(robotWakeUpMsgVO.getResourceTypeCode()) ? " " : robotWakeUpMsgVO.getResourceTypeCode();
                String size = StringUtil.isEmpty(robotWakeUpMsgVO.getSize()) ? " " : robotWakeUpMsgVO.getSize();
                List<String> infos = new ArrayList<>();
                infos.add(code);
                infos.add(size);
                pcloudWakeupMessage.setType("file");
                pcloudWakeupMessage.setTextContent(JSONObject.toJSONString(infos));
                pcloudWakeupMessage.setFileUrl(robotWakeUpMsgVO.getFileUrl());
                pcloudWakeupMessage.setFileName(robotWakeUpMsgVO.getContent());
            }
            pcloudWakeupMessage.setSeqNum(robotWakeUpMsgVO.getSeqNum());
            pcloudWakeupMessage.setId(null);
            pcloudWakeupMessageMapper.insertSelective(pcloudWakeupMessage);
        }

        String cron = "0 0 0/$ * * ? ";
        cron = cron.replace("$", String.valueOf(cycle));
        createCronJob(cron, null);

    }

    private void createCronJob(String cronStr, Integer wakeUpId) {
        try {
            String jobName = PCLOUD_WAKE_UP_CRON_JOB +":"+ wakeUpId;
            ScheduleJob job = new ScheduleJob();
            //定时器任务
            job.setJobName(jobName);
            //cron表达式
            job.setCronExpression(cronStr);
            //定时器分组
            job.setJobGroup("book");
            CallBackParam param = new CallBackParam();
            //service名称
            param.setBeanName("pcloudRobotWakeUpService");
            //回调内部接口方法名称
            param.setMethodName("doJob");

            //设置回调参数
            Map<String, Object> map = new HashMap<>();
            map.put("jobName", jobName);
            map.put("wakeUpId",wakeUpId);
            param.setParamMap(map);
            Map<String, Object> scheduleMap = new HashMap<>();
            scheduleMap.put("scheduleJob", job);
            scheduleMap.put("callBackParam", param);
            scheduleService.addCronJob(scheduleMap);
        } catch (SchedulerException | JsonParseException e) {
            log.info("【PcloudRobotWakeUpBizImpl.createCronJob】创建定时任务失败", e);
        }
    }

    @Override
    public void robotWakeUpRemove() {
        pcloudRobotWakeupMapper.deleteAll();
        pcloudWakeupMessageMapper.deleteAll();
        pcloudRobotDao.clearWakeUp();
        try {
            scheduleService.deleteJob(PCLOUD_WAKE_UP_CRON_JOB, "book");
        } catch (SchedulerException | JsonParseException e) {
            log.info("【PcloudRobotWakeUpBizImpl.robotWakeUpRemove】删除定时任务失败", e);
        }
    }

    @Override
    public RobotWakeUpShowVO getRobotWakeUpConfig(Integer wakeUpId) {
        RobotWakeUpShowVO robotWakeUpShowVO = pcloudRobotWakeupMapper.getRobotWakeUpConfigById(wakeUpId);
        setDays(Lists.newArrayList(robotWakeUpShowVO));
        setMessage(Lists.newArrayList(robotWakeUpShowVO));
        return robotWakeUpShowVO;
    }

    @Override
    public void doJob(Integer wakeUpId) {
        // 1. 查询所有开启自动提醒的小号
        PcloudRobotWakeup pcloudRobotWakeup = pcloudRobotWakeupMapper.selectByPrimaryKey(wakeUpId);
        if (null == pcloudRobotWakeup){
            log.info("唤醒wakeUpId为：{}的任务查询不到");
            return;
        }
        List<RobotClassifyDTO>  allRobotClassify = pcloudRobotWakeupClassifyMapper.getRobotClassifyByWakeUpId(wakeUpId);
        // 2. 查询提醒时间
        if (ListUtils.isEmpty(allRobotClassify)){
            log.info("唤醒wakeUpId为：{}的任务查询不到个人号",wakeUpId);
            return;
        }
        List<Integer> classifyIds = allRobotClassify.stream().map(e ->e.getClassifyId()).collect(Collectors.toList());
        List<String> allRobot = pcloudRobotDao.getPcloudRobotByTypes(classifyIds);
        if (ListUtils.isEmpty(allRobot)){
            log.info("任务：{}，没有可用的机器人",wakeUpId);
            return;
        }
        if (pcloudRobotWakeup == null || pcloudRobotWakeup.getLast() == null) {
            return;
        }
        List<RobotWakeUpMsgVO> list = pcloudWakeupMessageMapper.selectByWakeUpId(wakeUpId);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        log.info("[开始自动唤醒 推送消息] msg: {}", JSONObject.toJSONString(list));

        for (String robot : allRobot) {
            Map<String, String> userInfo = JedisClusterUtils.hgetAll(robot + PCLOUD_ROBOT_WAKE_UP_SUFFIX);
            if (userInfo.isEmpty()) {
                return;
            }
            Set<String> wxids = userInfo.keySet();
            if (wxids.isEmpty()) {
                return;
            }
            for (String wxid : wxids) {
                WakeUpInfoDto dto = JSONObject.parseObject(userInfo.get(wxid), WakeUpInfoDto.class);
                Date date = dto.getTime();
                String ip = dto.getIp();
                if (DateUtils.getDateDiff(date, pcloudRobotWakeup.getStartTime()) > pcloudRobotWakeup.getLast()) {
                    //修改全局订阅状态
                    pcloudRobotBiz.updateUserTdState(robot, wxid, 0);

                    int a= (int) Math.floor(Math.random()*list.size());
                    list = Arrays.asList(list.get(a));
                    for (RobotWakeUpMsgVO msg : list) {
                        if ("text".equals(msg.getType())) {
                            SendTextMessageVO txt = new SendTextMessageVO();
                            txt.setAltId(robot);
                            txt.setContent(msg.getContent());
                            txt.setWxGroupId(wxid);
                            txt.setIp(ip);
                            WxGroupSDK.sendTextMessage(txt);
                        }
                        if ("image".equals(msg.getType())) {
                            SendPicMessageVO pic = new SendPicMessageVO();
                            pic.setAltId(robot);
                            pic.setPicUrl(msg.getPicUrl());
                            pic.setWxId(wxid);
                            pic.setWxGroupId(wxid);
                            pic.setIp(ip);
                            WxGroupSDK.sendPicMessage(pic);
                        }
                        if ("file".equals(msg.getType())) {
                            SendFileVO file = new SendFileVO();
                            file.setAltId(robot);
                            file.setFileUrl(msg.getFileUrl());
                            file.setFileName(msg.getFileName());
                            file.setWxId(wxid);
                            file.setWxGroupId(wxid);
                            file.setIp(ip);
                            WxGroupSDK.sendFile(file);
                        }
                    }
                }
            }
        }
    }

    @Override
    public List<PcloudRobotClassifyResponseVO> listAllClassify() {
        return pcloudRobotWakeupMapper.listAllClassify();
    }

    @Override
    public void copyRobotWakeUp(String sourceWxId, String targetWxId) {
        PcloudRobot sourceRobot = pcloudRobotDao.getByWxId(sourceWxId);

        if (sourceRobot == null) {
            throw new BookBizException(BookBizException.ERROR, "源个人号未录入！");
        }

        if (sourceRobot.getRobotType() != null && sourceRobot.getWakeUp() == 1) {
            pcloudRobotDao.updateWakeUpByClassifyIds(Collections.singletonList(sourceRobot.getRobotType()));
        }
    }

    @Override
    @ParamLog("新增小号唤醒配置")
    @Transactional(rollbackFor = Exception.class)
    public void addrobotWakeUpConfig(RobotWakeUpConfigVO robotWakeUpConfigVO) {
        Integer lastDay = robotWakeUpConfigVO.getLastDay();
        if (lastDay == 1) {
            lastDay = 3;
        } else if (lastDay == 2) {
            lastDay = 7;
        } else if (lastDay == 3) {
            lastDay = DateUtils.getDayOfMonth(new Date());
        }
        checkStartTime(robotWakeUpConfigVO.getStartTime());
        PcloudRobotWakeup pcloudRobotWakeup = new PcloudRobotWakeup();
        pcloudRobotWakeup.setCreateTime(new Date());
        pcloudRobotWakeup.setLast(lastDay);
        pcloudRobotWakeup.setStartTime(robotWakeUpConfigVO.getStartTime());
        pcloudRobotWakeupMapper.insertSelective(pcloudRobotWakeup);

        List<Integer> classifyList = robotWakeUpConfigVO.getClassifyList();
        if (ListUtils.isEmpty(classifyList)){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(),"个人号不能为空");
        }
        List<PcloudRobotWakeupClassify> pcloudRobotWakeupClassifies = new ArrayList<>();
        classifyList.stream().forEach(e ->{
            PcloudRobotWakeupClassify pcloudRobotWakeupClassify = new PcloudRobotWakeupClassify();
            pcloudRobotWakeupClassify.setWakeUpId(pcloudRobotWakeup.getId());
            pcloudRobotWakeupClassify.setRobotClassifyId(e);
            pcloudRobotWakeupClassify.setCreateTime(new Date());
            pcloudRobotWakeupClassifies.add(pcloudRobotWakeupClassify);
        });
        pcloudRobotWakeupClassifyMapper.batchInsert(pcloudRobotWakeupClassifies);
        List<RobotWakeUpMsgVO> list = robotWakeUpConfigVO.getMsgVOList();
        if (ListUtils.isEmpty(list)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "消息不能为空");
        }
        if (list.size() > 10) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "最多配置十条消息");
        }
        List<PcloudWakeupMessage> pcloudWakeupMessages = new ArrayList<>();
        for (RobotWakeUpMsgVO robotWakeUpMsgVO : list) {
            PcloudWakeupMessage pcloudWakeupMessage = new PcloudWakeupMessage();
            pcloudWakeupMessage.setCreateTime(new Date());
            if (robotWakeUpMsgVO.getReplyType() == 1) {
                pcloudWakeupMessage.setType("text");
                pcloudWakeupMessage.setTextContent(robotWakeUpMsgVO.getContent());
            } else if (robotWakeUpMsgVO.getReplyType() == 2) {
                pcloudWakeupMessage.setType("image");
                pcloudWakeupMessage.setImgUrl(robotWakeUpMsgVO.getPicUrl());
            } else if (robotWakeUpMsgVO.getReplyType() == 5) {
                String code = StringUtil.isEmpty(robotWakeUpMsgVO.getResourceTypeCode()) ? " " : robotWakeUpMsgVO.getResourceTypeCode();
                String size = StringUtil.isEmpty(robotWakeUpMsgVO.getSize()) ? " " : robotWakeUpMsgVO.getSize();
                List<String> infos = new ArrayList<>();
                infos.add(code);
                infos.add(size);
                pcloudWakeupMessage.setType("file");
                pcloudWakeupMessage.setTextContent(JSONObject.toJSONString(infos));
                pcloudWakeupMessage.setFileUrl(robotWakeUpMsgVO.getFileUrl());
                pcloudWakeupMessage.setFileName(robotWakeUpMsgVO.getContent());
            }
            pcloudWakeupMessage.setSeqNum(robotWakeUpMsgVO.getSeqNum());
            pcloudWakeupMessage.setId(null);
            pcloudWakeupMessage.setWakeUpId(pcloudRobotWakeup.getId());
            pcloudWakeupMessages.add(pcloudWakeupMessage);
        }
        pcloudWakeupMessageMapper.batchInsert(pcloudWakeupMessages);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(robotWakeUpConfigVO.getStartTime());//放入Date类型数据
        Integer year = calendar.get(Calendar.YEAR);	//获取年份
        Integer month = calendar.get(Calendar.MONTH) + 1;//获取月份
        Integer date = calendar.get(Calendar.DATE);		//获取日
        Integer hour = calendar.get(Calendar.HOUR_OF_DAY);	//时（24小时制）
        Integer minute = calendar.get(Calendar.MINUTE);		//分
        Integer second = calendar.get(Calendar.SECOND);
        String cron = second + " " + minute + " " + hour + " " +
                date + " " + month + " " + "? " + year;
        createCronJob(cron, pcloudRobotWakeup.getId());

    }

    private void checkStartTime(Date startTime) {
        Date newDate = new Date();
        if (startTime.before(newDate)){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"唤醒发送时间不得早于当前时间");
        }
    }

    @Override
    @ParamLog("获取机器人小号配置列表分页")
    public PageBeanNew<RobotWakeUpShowVO> getRobotWakeUpConfigList(Integer currentPage, Integer numPerPage) {
        ParamCheck.pageParam(currentPage,numPerPage);
        Integer totalCount  = pcloudRobotWakeupMapper.getRobotWakeUpConfigListCount();
        List<RobotWakeUpShowVO> robotWakeUpShowVOS = new ArrayList<>();
        if (totalCount > 0){
          robotWakeUpShowVOS = pcloudRobotWakeupMapper.getRobotWakeUpConfigList(currentPage * numPerPage,numPerPage);
          }
        PageBeanNew<RobotWakeUpShowVO> robotWakeUpShowVOPageBeanNew = new PageBeanNew<>(currentPage,numPerPage,totalCount,robotWakeUpShowVOS);
        if (!ListUtils.isEmpty(robotWakeUpShowVOS)){
            setDays(robotWakeUpShowVOS);
            setMessage(robotWakeUpShowVOS);
        }
        return robotWakeUpShowVOPageBeanNew;

    }

    private void setMessage(List<RobotWakeUpShowVO> robotWakeUpShowVOS) {
        robotWakeUpShowVOS.stream().forEach(robotWakeUpShowVO ->{
            List<RobotWakeUpMsgVO> robotWakeUpMsgVOS = robotWakeUpShowVO.getMsgList();
            if (!ListUtils.isEmpty(robotWakeUpMsgVOS)){
                robotWakeUpMsgVOS.stream().forEach(pcloudWakeupMessage ->{

                    if ("text".equals(pcloudWakeupMessage.getType())) {
                        pcloudWakeupMessage.setReplyType(1);
                    } else if ("image".equals(pcloudWakeupMessage.getType())) {
                        pcloudWakeupMessage.setReplyType(2);
                    } else if ("file".equals(pcloudWakeupMessage.getType())) {
                        List<String> array = JSONObject.parseArray(pcloudWakeupMessage.getContent(), String.class);
                        if (array.size() > 1) {
                            pcloudWakeupMessage.setResourceTypeCode(array.get(0));
                            pcloudWakeupMessage.setSize(array.get(1));
                        }
                        pcloudWakeupMessage.setReplyType(5);
                        pcloudWakeupMessage.setContent(pcloudWakeupMessage.getFileName());
                    }
                });
            }
        } );
    }

    private void setDays(List<RobotWakeUpShowVO> robotWakeUpShowVOS) {
        robotWakeUpShowVOS.stream().forEach(robotWakeUpShowVO ->{
            Integer last = robotWakeUpShowVO.getLastDay();
            if (last == 3) {
                last = 1;
            } else if (last == 7) {
                last = 2;
            } else {
                last = 3;
            }
            robotWakeUpShowVO.setLastDay(last);
        } );

    }

    @Override
    @ParamLog("删除机器人小号唤醒配置")
    public void deleterobotWakeUp(Integer wakeUpid) {
        //1. 唤醒删除
        pcloudRobotWakeupMapper.deleteByPrimaryKey(wakeUpid);
        pcloudRobotWakeupClassifyMapper.deleteByWakeUpId(wakeUpid);
        pcloudWakeupMessageMapper.delectByWakeUpId(wakeUpid);
    }

    @Override
    @ParamLog("更新机器人小号唤醒配置")
    @Transactional(rollbackFor = Exception.class)
    public void updaterobotWakeUp(RobotWakeUpConfigVO robotWakeUpConfigVO) {
        Integer wakeUpId = robotWakeUpConfigVO.getWakeUpId();
        Integer lastDay = robotWakeUpConfigVO.getLastDay();
        if (lastDay == 1) {
            lastDay = 3;
        } else if (lastDay == 2) {
            lastDay = 7;
        } else if (lastDay == 3) {
            lastDay = DateUtils.getDayOfMonth(new Date());
        }
        checkStartTime(robotWakeUpConfigVO.getStartTime());
        PcloudRobotWakeup pcloudRobotWakeup = new PcloudRobotWakeup();
        pcloudRobotWakeup.setId(robotWakeUpConfigVO.getWakeUpId());
        pcloudRobotWakeup.setLast(lastDay);
        pcloudRobotWakeup.setStartTime(robotWakeUpConfigVO.getStartTime());
        pcloudRobotWakeup.setUpdateTime(new Date());
        pcloudRobotWakeupMapper.updateByPrimaryKeySelective(pcloudRobotWakeup);


        List<Integer> classifyList = robotWakeUpConfigVO.getClassifyList();
        if (ListUtils.isEmpty(classifyList)){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(),"个人号不能为空");
        }
        List<PcloudRobotWakeupClassify> pcloudRobotWakeupClassifies = new ArrayList<>();
        classifyList.stream().forEach(e ->{
            PcloudRobotWakeupClassify pcloudRobotWakeupClassify = new PcloudRobotWakeupClassify();
            pcloudRobotWakeupClassify.setWakeUpId(pcloudRobotWakeup.getId());
            pcloudRobotWakeupClassify.setRobotClassifyId(e);
            pcloudRobotWakeupClassify.setCreateTime(new Date());
            pcloudRobotWakeupClassifies.add(pcloudRobotWakeupClassify);
        });
        pcloudRobotWakeupClassifyMapper.deleteByWakeUpId(wakeUpId);
        pcloudRobotWakeupClassifyMapper.batchInsert(pcloudRobotWakeupClassifies);
        //更新资源
        List<RobotWakeUpMsgVO> list = robotWakeUpConfigVO.getMsgVOList();
        if (ListUtils.isEmpty(list)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "消息不能为空");
        }
        if (list.size() > 10) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "最多配置十条消息");
        }
        List<PcloudWakeupMessage> pcloudWakeupMessages = new ArrayList<>();
        for (RobotWakeUpMsgVO robotWakeUpMsgVO : list) {
            PcloudWakeupMessage pcloudWakeupMessage = new PcloudWakeupMessage();
            pcloudWakeupMessage.setCreateTime(new Date());
            if (robotWakeUpMsgVO.getReplyType() == 1) {
                pcloudWakeupMessage.setType("text");
                pcloudWakeupMessage.setTextContent(robotWakeUpMsgVO.getContent());
            } else if (robotWakeUpMsgVO.getReplyType() == 2) {
                pcloudWakeupMessage.setType("image");
                pcloudWakeupMessage.setImgUrl(robotWakeUpMsgVO.getPicUrl());
            } else if (robotWakeUpMsgVO.getReplyType() == 5) {
                String code = StringUtil.isEmpty(robotWakeUpMsgVO.getResourceTypeCode()) ? " " : robotWakeUpMsgVO.getResourceTypeCode();
                String size = StringUtil.isEmpty(robotWakeUpMsgVO.getSize()) ? " " : robotWakeUpMsgVO.getSize();
                List<String> infos = new ArrayList<>();
                infos.add(code);
                infos.add(size);
                pcloudWakeupMessage.setType("file");
                pcloudWakeupMessage.setTextContent(JSONObject.toJSONString(infos));
                pcloudWakeupMessage.setFileUrl(robotWakeUpMsgVO.getFileUrl());
                pcloudWakeupMessage.setFileName(robotWakeUpMsgVO.getContent());
            }
            pcloudWakeupMessage.setSeqNum(robotWakeUpMsgVO.getSeqNum());
            pcloudWakeupMessage.setId(null);
            pcloudWakeupMessage.setWakeUpId(pcloudRobotWakeup.getId());
            pcloudWakeupMessages.add(pcloudWakeupMessage);
        }
        pcloudWakeupMessageMapper.delectByWakeUpId(wakeUpId);
        pcloudWakeupMessageMapper.batchInsert(pcloudWakeupMessages);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(robotWakeUpConfigVO.getStartTime());//放入Date类型数据
        Integer year = calendar.get(Calendar.YEAR);	//获取年份
        Integer month = calendar.get(Calendar.MONTH) + 1;//获取月份
        Integer date = calendar.get(Calendar.DATE);		//获取日
        Integer hour = calendar.get(Calendar.HOUR_OF_DAY);	//时（24小时制）
        Integer minute = calendar.get(Calendar.MINUTE);		//分
        Integer second = calendar.get(Calendar.SECOND);
        String cron = second + " " + minute + " " + hour + " " +
                date + " " + month + " " + "? " + year;
        UpdateCronJob(cron,wakeUpId);

    }

    private void UpdateCronJob(String cronStr, Integer wakeUpId) {
        try {
            String jobName = PCLOUD_WAKE_UP_CRON_JOB +":"+ wakeUpId;
            ScheduleJob job = new ScheduleJob();
            //先删，再添加
            scheduleService.deleteJob(jobName, "book");
            //定时器任务
            job.setJobName(jobName);
            //cron表达式
            job.setCronExpression(cronStr);
            //定时器分组
            job.setJobGroup("book");
            CallBackParam param = new CallBackParam();
            //service名称
            param.setBeanName("pcloudRobotWakeUpService");
            //回调内部接口方法名称
            param.setMethodName("doJob");

            //设置回调参数
            Map<String, Object> map = new HashMap<>();
            map.put("jobName", jobName);
            map.put("wakeUpId",wakeUpId);
            param.setParamMap(map);
            Map<String, Object> scheduleMap = new HashMap<>();
            scheduleMap.put("scheduleJob", job);
            scheduleMap.put("callBackParam", param);
            log.info("[*********************]{}",JSONObject.toJSONString(scheduleMap));
            scheduleService.addCronJob(scheduleMap);
        } catch (SchedulerException | JsonParseException e) {
            log.info("【PcloudRobotWakeUpBizImpl.createCronJob】创建定时任务失败", e);
        }
    }

}
