package com.yizhi.application.calendarTask;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.album.application.feign.AlbumClient;
import com.yizhi.album.application.vo.AlbumCalendarVo;
import com.yizhi.application.live.enums.LiveStatus;
import com.yizhi.application.vo.CalendarTask;
import com.yizhi.application.vo.CalendarTaskSortEnums;
import com.yizhi.assignment.application.feign.AssignmentStudentClient;
import com.yizhi.assignment.application.vo.AssignmentCalendarVO;
import com.yizhi.core.application.cache.RedisCache;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.course.application.feign.CourseClient;
import com.yizhi.course.application.vo.domain.CourseEntityVo;
import com.yizhi.exam.application.feign.ExamApiClient;
import com.yizhi.exam.application.vo.ExamCalendarVO;
import com.yizhi.live.application.feign.LiveActivityClient;
import com.yizhi.live.application.vo.LiveOnlineCountVo;
import com.yizhi.live.application.vo.PageLiveVo;
import com.yizhi.research.application.feign.ResearchClient;
import com.yizhi.research.application.vo.domain.ResearchVo;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.training.application.vo.api.CalendarTaskParamVo;
import com.yizhi.training.application.vo.domain.TrainingProjectVo;
import com.yizhi.util.application.domain.Response;
import com.yizhi.util.application.enums.i18n.ButtonStatus;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/calendar/api")
@Api(tags = "日历任务")
public class CalendarTaskController {


    @Autowired
    private CourseClient courseClient;
    @Autowired
    private TrainingProjectClient trainingProjectClient;
    @Autowired
    private ExamApiClient examApiClient;
    @Autowired
    private AssignmentStudentClient assignmentStudentClient;
    @Autowired
    private ResearchClient researchClient;
    @Autowired
    private LiveActivityClient liveActivityClient;
    @Autowired
    private AlbumClient albumClient;
    @Autowired
    private RedisCache redisCache;

    private static Logger logger = LoggerFactory.getLogger(CalendarTaskController.class);
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    //日历任务红点数据的key
    private static final String calendar_task_pre = "calendar_task_month_accountId:";
    //日历任务列表数据的key
    private static final String calendar_task_data = "calendar_task_data_accountId:";
    private static final Integer TRAINING = 1;
    private static final Integer COURSE = 2;
    private static final Integer ASSIGNMENT = 3;
    private static final Integer EXAM = 4;
    private static final Integer RESEARCH = 5;
    private static final Integer LIVE = 6;
    private static final Integer ALBUM = 7;

    @PostMapping("/pc/getPage")
    @ApiOperation(value = "按时间分页查询业务数据", response = CalendarTask.class)
    public Response getTaskByDate(@ApiParam("paramVo") @RequestBody CalendarTaskParamVo paramVo) {
        //1.培训;2.课程;3.作业; 4.考试;5.调研 6、直播 7、专辑

        if (paramVo.getDate() == null) {
            return Response.fail("缺失当前时间参数！");
        }

        Integer pageNo = paramVo.getPageNo() == null ? 1 : paramVo.getPageNo();
        Integer pageSize = paramVo.getPageSize() == null ? 6 : paramVo.getPageSize();
        paramVo.setPageNo(pageNo);
        paramVo.setPageSize(pageSize);
        Page<CalendarTask> calendarTaskPage = new Page<>(pageNo, pageSize);
        switch (paramVo.getTaskType()) {

            case 1:
                //培训
                calendarTaskPage = getProject(calendarTaskPage, paramVo, TRAINING);
                break;
            case 2:
                //课程
                com.yizhi.course.application.vo.CalendarTaskParamVo courseVo = new com.yizhi.course.application.vo.CalendarTaskParamVo();
                BeanUtils.copyProperties(paramVo, courseVo);
                calendarTaskPage = getCourse(calendarTaskPage, courseVo, COURSE);

                break;
            case 3:
                //作业
                com.yizhi.assignment.application.vo.CalendarTaskParamVo assignVo = new com.yizhi.assignment.application.vo.CalendarTaskParamVo();
                BeanUtils.copyProperties(paramVo, assignVo);
                calendarTaskPage = getAssignment(calendarTaskPage, assignVo, ASSIGNMENT);
                break;
            case 4:
                //  考试
                com.yizhi.exam.application.vo.CalendarTaskParamVo examVo = new com.yizhi.exam.application.vo.CalendarTaskParamVo();
                BeanUtils.copyProperties(paramVo, examVo);
                calendarTaskPage = getExam(calendarTaskPage, examVo, EXAM);
                break;
            case 5:
                //调研
                com.yizhi.research.application.vo.CalendarTaskParamVo researchVo = new com.yizhi.research.application.vo.CalendarTaskParamVo();
                BeanUtils.copyProperties(paramVo, researchVo);
                calendarTaskPage = getResearch(calendarTaskPage, researchVo, RESEARCH);
                break;
            case 6:
                //直播
                com.yizhi.live.application.vo.CalendarTaskParamVo liveVo = new com.yizhi.live.application.vo.CalendarTaskParamVo();
                BeanUtils.copyProperties(paramVo, liveVo);
                calendarTaskPage = getLive(calendarTaskPage, liveVo, LIVE);
                break;
            case 7:
                //专辑
                com.yizhi.album.application.vo.CalendarTaskParamVo albumVo = new com.yizhi.album.application.vo.CalendarTaskParamVo();
                BeanUtils.copyProperties(paramVo, albumVo);
                calendarTaskPage = getAlbum(calendarTaskPage, albumVo, ALBUM);
                break;
            default:
                return Response.fail("taskType传参超出1-7合理范围");

        }

        return Response.ok(calendarTaskPage);
    }

    @PostMapping("/pc/getPageNum")
    @ApiOperation(value = "按时间分页查询业务数据", response = CalendarTask.class)
    public Response<Map<String, Integer>> getTaskByDateNum(@ApiParam("paramVo") @RequestBody CalendarTaskParamVo paramVo) {

        if (paramVo.getDate() == null) {
            return Response.fail("缺失当前时间参数！");
        }

        Integer total = 0;
        paramVo.setPageNo(1);
        paramVo.setPageSize(Integer.MAX_VALUE);
        Map<String, Integer> recordsNumMap = new LinkedHashMap<>();

        //课程
        total = getNum(COURSE, paramVo);
        recordsNumMap.put("Course", total);

        //培训
        total = getNum(TRAINING, paramVo);
        recordsNumMap.put("TrainingProgram2", total);

        //专辑
        total = getNum(ALBUM, paramVo);
        recordsNumMap.put("Album", total);

        // 考试
        total = getNum(EXAM, paramVo);
        recordsNumMap.put("Exam", total);

        //作业
        total = getNum(ASSIGNMENT, paramVo);
        recordsNumMap.put("Assignment", total);

        //调研
        total = getNum(RESEARCH, paramVo);
        recordsNumMap.put("Research", total);

        //直播
        total = getNum(LIVE, paramVo);
        recordsNumMap.put("livestream", total);

        return Response.ok(recordsNumMap);
    }

    @PostMapping("/api/getPage")
    @ApiOperation(value = "按时间分页查询业务数据", response = CalendarTask.class)
    public Response<CalendarTask> getTaskByDateApi(@ApiParam("paramVo") @RequestBody CalendarTaskParamVo paramVo) {

        if (paramVo.getDate() == null) {
            return Response.fail("缺失当前时间参数！");
        }
        Integer pageNo = paramVo.getPageNo() == null ? 1 : paramVo.getPageNo();
        Integer pageSize = paramVo.getPageSize() == null ? 20 : paramVo.getPageSize();
        Page<CalendarTask> calendarTaskPage = new Page<>(pageNo, pageSize);
        paramVo.setPageNo(1);
        paramVo.setPageSize(Integer.MAX_VALUE);

        //首頁走这里 从缓存中加载数据
        if (pageNo == 1 && pageSize == 3) {
           return  Response.ok(getDataFromCache(pageNo,pageSize,paramVo));
        }
        //获取分页数据
        getPage(calendarTaskPage, paramVo);
        List<CalendarTask> calendarTasks = calendarTaskPage.getRecords();
        List<CalendarTask> calendarTaskList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(calendarTasks)) {
            sortData(calendarTasks, pageNo, pageSize, calendarTaskList);
            calendarTaskPage.setRecords(calendarTaskList);
        }
        return Response.ok(calendarTaskPage);
    }

    /**
     * 首頁走这里 从缓存中加载数据
     *
     * @param pageNo
     * @param pageSize
     * @param paramVo
     * @return
     */
    private Page<CalendarTask> getDataFromCache(Integer pageNo, Integer pageSize, CalendarTaskParamVo paramVo) {
        Page<CalendarTask> calendarTaskPage = new Page<>(pageNo, pageSize);
        if (pageNo == 1 && pageSize == 3) {
            Long accountId = ContextHolder.get().getAccountId();
            String key = calendar_task_data + format.format(paramVo.getDate()) + ":" + accountId.toString();
            Object hGet = null;
            //考虑需要非第一页时，不能读缓存,加缓存主要为了提高首页加载速度，防止明显卡顿现象
            hGet = redisCache.get(key);
            if (hGet != null) {
                logger.info("===========从缓存中读取信息=========");
                List<CalendarTask> calendarTasks = JSON.parseArray(hGet.toString(), CalendarTask.class);
                calendarTaskPage.setRecords(calendarTasks);
                calendarTaskPage.setTotal(calendarTasks.size());
            } else {
                //获取分页数据
                getPage(calendarTaskPage, paramVo);
                List<CalendarTask> calendarTasks = calendarTaskPage.getRecords();
                List<CalendarTask> calendarTaskList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(calendarTasks)) {
                    sortData(calendarTasks, pageNo, pageSize, calendarTaskList);
                    calendarTaskPage.setRecords(calendarTaskList);
                }
                if (CollectionUtils.isNotEmpty(calendarTaskList)) {
                    redisCache.set(key, JSON.toJSONString(calendarTaskList), 5 * 60L);
                }
            }
            //按照指定顺序排序
            List<CalendarTask> records = calendarTaskPage.getRecords();
            records = records.stream().sorted(Comparator.comparing(CalendarTask::getSort)).collect(Collectors.toList());
            calendarTaskPage.setRecords(records);
        }
        return calendarTaskPage;
    }

    /**
     * 处理数据
     *
     * @param calendarTasks
     * @param pageNo
     * @param pageSize
     * @param calendarTaskList
     */
    private void sortData(List<CalendarTask> calendarTasks, Integer pageNo, Integer pageSize, List<CalendarTask> calendarTaskList) {
        if (CollectionUtils.isNotEmpty(calendarTasks)) {
            Collections.sort(calendarTasks, new Comparator<CalendarTask>() {
                @Override
                public int compare(CalendarTask o1, CalendarTask o2) {
                    if (o1.getTaskStartDate().getTime() - o2.getTaskStartDate().getTime() > 0) {
                        return -1;
                    } else if (o1.getTaskStartDate().getTime() - o2.getTaskStartDate().getTime() < 0) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });
//            Integer pageStart = (pageNo - 1) * pageSize;
//            Integer pageEnd = pageNo * pageSize;
//            Integer recordsSize = calendarTasks.size();
//            if (recordsSize < pageEnd) {
//                pageEnd = recordsSize;
//            }
//            for (int i = pageStart; i < pageEnd; i++) {
//                if (i < recordsSize) {
//                    calendarTaskList.add(calendarTasks.get(i));
//                }
//            }
            //首页样式改造，去除了假分页
            calendarTaskList.addAll(calendarTasks);
        }
    }


    /**
     * 获取每天对应的日历任务数量
     *
     * @param
     * @return
     */
    @PostMapping("/calendarTaskNum")
    @ApiOperation(value = "按时间分页查询业务数据", response = CalendarTask.class)
    public Response<CalendarTask> getTaskNumByDate(@ApiParam("paramVo") @RequestBody CalendarTaskParamVo paramVo) {
        if (paramVo.getDate() == null) {
            return Response.fail("缺失当前时间参数！");
        }
        paramVo.setPageNo(1);
        paramVo.setPageSize(Integer.MAX_VALUE);
        Long accountId = ContextHolder.get().getAccountId();
        String key = calendar_task_pre + ":" + accountId.toString() + ":";
        String item = accountId.toString();
        int month = DateUtil.month(paramVo.getDate());
        //month是从0,开始的需要加一
        month++;
        key = key + month;

        Object o = redisCache.get(key);
        if (o != null) {
            Map<String, Integer> map = JSON.parseObject(o.toString(), Map.class);
            return Response.ok(map);
        } else {
            Map<String, Integer> dateMap = new LinkedHashMap<>(31);
            Date now = paramVo.getDate();
            DateTime endOfMonth = DateUtil.endOfMonth(now);
            Integer days = DateUtil.dayOfMonth(endOfMonth) - DateUtil.dayOfMonth(now);
            for (int i = 0; i <= days; i++) {
                paramVo.setDate(DateUtil.offsetDay(now, i));
                getNumByType(paramVo, dateMap);
            }
            if (!dateMap.isEmpty()) {
                redisCache.set(key, JSON.toJSONString(dateMap), 60 * 20);
            }
            return Response.ok(dateMap);
        }
    }

    /**
     * 根据类型   //1.培训;2.课程;3.作业; 4.考试;5.调研 6、直播  7、专辑 查询业务个数
     *
     * @param paramVo
     * @param map
     */
    public void getNumByType(CalendarTaskParamVo paramVo, Map<String, Integer> map) {
        for (int i = 1; i <= 7; i++) {
            Integer num = null;
            try {
                num = getNum(i, paramVo);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            if (num > 0) {
                map.put(format.format(paramVo.getDate()), 1);
                break;
            }
        }
    }

    /**
     * 获取各业务的数量
     *
     * @param type
     * @param paramVo
     * @return
     */
    public Integer getNum(Integer type, CalendarTaskParamVo paramVo) {
        Page page = null;
        switch (type) {

            case 1:
                //培训
                try {
                    page = trainingProjectClient.getPageToCalendar(paramVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务培训查询数据异常");
                }
                break;
            case 2:
                //课程
                try {
                    com.yizhi.course.application.vo.CalendarTaskParamVo courseVo = new com.yizhi.course.application.vo.CalendarTaskParamVo();
                    BeanUtils.copyProperties(paramVo, courseVo);
                    page = courseClient.getPageToCalendar(courseVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务课程查询数据异常");
                }
                break;
            case 3:
                //作业
                try {
                    com.yizhi.assignment.application.vo.CalendarTaskParamVo assignVo = new com.yizhi.assignment.application.vo.CalendarTaskParamVo();
                    BeanUtils.copyProperties(paramVo, assignVo);
                    page = assignmentStudentClient.getPageToCalendar(assignVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务作业查询数据异常");
                }
                break;
            case 4:
                //  考试
                try {
                    com.yizhi.exam.application.vo.CalendarTaskParamVo examVo = new com.yizhi.exam.application.vo.CalendarTaskParamVo();
                    BeanUtils.copyProperties(paramVo, examVo);
                    page = examApiClient.getPageToCalendar(examVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务考试查询数据异常");
                }
                break;
            case 5:
                //调研
                try {
                    com.yizhi.research.application.vo.CalendarTaskParamVo researchVo = new com.yizhi.research.application.vo.CalendarTaskParamVo();
                    BeanUtils.copyProperties(paramVo, researchVo);
                    page = researchClient.getPageToCalendar(researchVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务调研查询数据异常");
                }
                break;
            case 6:
                //直播
                try {
                    com.yizhi.live.application.vo.CalendarTaskParamVo liveVo = new com.yizhi.live.application.vo.CalendarTaskParamVo();
                    BeanUtils.copyProperties(paramVo, liveVo);
                    page = liveActivityClient.getPageToCalendar(liveVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务直播查询数据异常");
                }
                break;
            case 7:
                //专辑
                try {
                    com.yizhi.album.application.vo.CalendarTaskParamVo albumVo = new com.yizhi.album.application.vo.CalendarTaskParamVo();
                    BeanUtils.copyProperties(paramVo, albumVo);
                    page = albumClient.getPageToCalendar(albumVo);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.info("日历任务专辑查询数据异常");
                }
                break;
        }
        if (page == null) {
            return 0;
        }
        return page.getTotal();
    }

    /**
     * 获取分页数据
     *
     * @param calendarTaskPage
     * @param paramVo
     */
    public void getPage(Page<CalendarTask> calendarTaskPage, CalendarTaskParamVo paramVo) {
        Integer total = 0;
        //培训
        try {
            calendarTaskPage = getProject(calendarTaskPage, paramVo, TRAINING);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务培训查询数据异常");
        }
        //课程
        try {
            com.yizhi.course.application.vo.CalendarTaskParamVo courseVo = new com.yizhi.course.application.vo.CalendarTaskParamVo();
            BeanUtils.copyProperties(paramVo, courseVo);
            calendarTaskPage = getCourse(calendarTaskPage, courseVo, COURSE);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务课程查询数据异常");
        }
        //作业
        try {
            com.yizhi.assignment.application.vo.CalendarTaskParamVo assignmentVo = new com.yizhi.assignment.application.vo.CalendarTaskParamVo();
            BeanUtils.copyProperties(paramVo, assignmentVo);
            calendarTaskPage = getAssignment(calendarTaskPage, assignmentVo, ASSIGNMENT);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务作业查询数据异常");
        }
        //  考试
        try {
            com.yizhi.exam.application.vo.CalendarTaskParamVo examVo = new com.yizhi.exam.application.vo.CalendarTaskParamVo();
            BeanUtils.copyProperties(paramVo, examVo);
            calendarTaskPage = getExam(calendarTaskPage, examVo, EXAM);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务考试查询数据异常");
        }
        //调研
        try {
            com.yizhi.research.application.vo.CalendarTaskParamVo researchVo = new com.yizhi.research.application.vo.CalendarTaskParamVo();
            BeanUtils.copyProperties(paramVo, researchVo);
            calendarTaskPage = getResearch(calendarTaskPage, researchVo, RESEARCH);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务调研查询数据异常");
        }
        //直播
        try {
            com.yizhi.live.application.vo.CalendarTaskParamVo liveVo = new com.yizhi.live.application.vo.CalendarTaskParamVo();
            BeanUtils.copyProperties(paramVo, liveVo);
            calendarTaskPage = getLive(calendarTaskPage, liveVo, LIVE);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务直播查询数据异常");
        }
        //专辑
        try {
            com.yizhi.album.application.vo.CalendarTaskParamVo albumVo = new com.yizhi.album.application.vo.CalendarTaskParamVo();
            BeanUtils.copyProperties(paramVo, albumVo);
            calendarTaskPage = getAlbum(calendarTaskPage, albumVo, ALBUM);
            total += calendarTaskPage.getTotal();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("日历任务专辑查询数据异常");
        }
        calendarTaskPage.setTotal(total);
    }

    public Integer getNotNull(Integer a) {
        a = (a == null ? 0 : a);
        return a;
    }


    /**
     * 获取课程列表
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getCourse(Page<CalendarTask> calendarTaskPage, com.yizhi.course.application.vo.CalendarTaskParamVo paramVo, Integer type) {
        Page<CourseEntityVo> page = courseClient.getPageToCalendar(paramVo);
        if (page != null) {
            List<CourseEntityVo> courses = page.getRecords();
            if (CollectionUtils.isNotEmpty(courses)) {
                List calendarTasks = new ArrayList(courses.size());
                courses.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskLogo(a.getImage());
                    calendarTask.setTaskName(a.getName());
                    calendarTask.setTaskType(type);
                    calendarTask.setTaskTypeString("课程");
                    calendarTask.setTaskButtonStatus(Arrays.asList(ButtonStatus.GO_STUDY.getCode()));
                    calendarTask.setTaskStartDate(a.getTaskStartDate());
                    calendarTask.setTaskEndDate(a.getTaskEndDate());
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.COURSE.getSort());
                    calendarTasks.add(calendarTask);
                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;

    }

    /**
     * 获取项目列表
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getProject(Page<CalendarTask> calendarTaskPage, CalendarTaskParamVo paramVo, Integer type) {
        Page<TrainingProjectVo> page = trainingProjectClient.getPageToCalendar(paramVo);
        Date now = new Date();

        if (page != null) {
            List<TrainingProjectVo> trainingProjects = page.getRecords();
            if (CollectionUtils.isNotEmpty(trainingProjects)) {
                List calendarTasks = new ArrayList(trainingProjects.size());
                trainingProjects.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskTypeString("项目");
                    calendarTask.setTaskLogo(a.getLogoImg());
                    calendarTask.setTaskName(a.getName());
                    calendarTask.setTaskType(type);
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.TRAINING.getSort());
                    if (a.getStartTime() != null && now.getTime() < a.getStartTime().getTime()) {
                        calendarTask.setTaskButtonStatus(Arrays.asList(ButtonStatus.VIEW_PROJECT.getCode()));
                    } else {
                        calendarTask.setTaskButtonStatus(Arrays.asList(ButtonStatus.LEARN_NOW.getCode()));
                    }
                    calendarTask.setTaskStartDate(a.getStartTime());
                    calendarTask.setTaskEndDate(a.getEndTime());
                    calendarTasks.add(calendarTask);
                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;

    }

    /**
     * 获取考试数据
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getExam(Page<CalendarTask> calendarTaskPage, com.yizhi.exam.application.vo.CalendarTaskParamVo paramVo, Integer type) {

        Page<ExamCalendarVO> page = examApiClient.getPageToCalendar(paramVo);
        Date now = new Date();

        if (page != null) {
            List<ExamCalendarVO> examCalendarVOS = page.getRecords();

            if (CollectionUtils.isNotEmpty(examCalendarVOS)) {
                List calendarTasks = new ArrayList(examCalendarVOS.size());
                examCalendarVOS.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskTypeString("考试");
                    calendarTask.setTaskName(a.getName());
                    calendarTask.setTaskCanNum(a.getExamNum());
                    calendarTask.setTaskUseNum(a.getAnswerNum());
                    calendarTask.setTaskType(type);
                    calendarTask.setTaskStartDate(a.getStartTime());
                    calendarTask.setTaskEndDate(a.getEndTime());
                    calendarTask.setTaskTag(a.getTaskTag());
                    calendarTask.setTaskButtonStatus(a.getTaskButtonStatus());
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.EXAM.getSort());
                    if (a.getStartTime() != null && now.getTime() < a.getStartTime().getTime()) {
                        calendarTask.setTaskButtonStatus(null);
                    }
                    calendarTasks.add(calendarTask);
                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;
    }

    /**
     * 获取作业列表
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getAssignment(Page<CalendarTask> calendarTaskPage, com.yizhi.assignment.application.vo.CalendarTaskParamVo paramVo, Integer type) {
        Page<AssignmentCalendarVO> page = assignmentStudentClient.getPageToCalendar(paramVo);

        if (page != null) {
            List<AssignmentCalendarVO> assignments = page.getRecords();

            if (CollectionUtils.isNotEmpty(assignments)) {
                List calendarTasks = new ArrayList(assignments.size());
                assignments.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskTypeString("作业");
                    calendarTask.setTaskName(a.getName());
                    calendarTask.setTaskCanNum(a.getCount());
                    calendarTask.setTaskType(type);
                    calendarTask.setTaskStartDate(a.getTaskStartDate());
                    calendarTask.setTaskEndDate(a.getTaskEndDate());
                    calendarTask.setFinishDate(a.getFinishTime());
                    calendarTask.setTaskTag(a.getTaskTag());
                    calendarTask.setTaskButtonStatus(a.getTaskButtonStatus());
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.ASSIGNMENT.getSort());
                    calendarTasks.add(calendarTask);

                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;
    }


    /**
     * 获取调研数据
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getResearch(Page<CalendarTask> calendarTaskPage, com.yizhi.research.application.vo.CalendarTaskParamVo paramVo, Integer type) {
        Page<ResearchVo> page = researchClient.getPageToCalendar(paramVo);
        Date now = new Date();

        if (page != null) {
            List<ResearchVo> researchs = page.getRecords();

            if (CollectionUtils.isNotEmpty(researchs)) {
                List calendarTasks = new ArrayList(researchs.size());
                researchs.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskTypeString("调研");
                    calendarTask.setTaskName(a.getName());
                    calendarTask.setTaskType(type);
                    calendarTask.setTaskStartDate(a.getStartTime());
                    calendarTask.setTaskEndDate(a.getEndTime());
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.RESEARCH.getSort());
                    calendarTask.setTaskButtonStatus(Arrays.asList(ButtonStatus.START_RESEARCH.getCode()));
                    if (a.getStartTime() != null && now.getTime() < a.getStartTime().getTime()) {
                        calendarTask.setTaskButtonStatus(null);
                    }
                    calendarTasks.add(calendarTask);
                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;
    }

    /**
     * 获取直播数据
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getLive(Page<CalendarTask> calendarTaskPage, com.yizhi.live.application.vo.CalendarTaskParamVo paramVo, Integer type) {
        Page<PageLiveVo> page = liveActivityClient.getPageToCalendar(paramVo);

        if (page != null) {
            List<PageLiveVo> liveVos = page.getRecords();

            if (CollectionUtils.isNotEmpty(liveVos)) {
                List calendarTasks = new ArrayList(liveVos.size());
                liveVos.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskTypeString("直播");
                    calendarTask.setTaskName(a.getTitle());
                    calendarTask.setChannel(a.getChannel());
                    calendarTask.setTaskLogo(a.getLogoImage());
                    calendarTask.setTaskType(type);
                    calendarTask.setTaskStartDate(a.getStartTime());
                    calendarTask.setTaskEndDate(a.getEndTime());
                    calendarTask.setTaskTag(a.getStatus());
                    calendarTask.setRelationUserName(a.getAnchor());
                    calendarTask.setTaskUseNum(0);
                    String liveStatus = a.getStatus();
                    if (StringUtils.isEmpty(liveStatus) && liveStatus.equals(String.valueOf(LiveStatus.RUNNING.getCode()))){
                        //在学人数
                        List<LiveOnlineCountVo> liveOnlineCountVos = liveActivityClient.liveCountOnlineRealTime(a.getChannel());
                        if (!org.springframework.util.CollectionUtils.isEmpty(liveOnlineCountVos)){
                            liveOnlineCountVos.parallelStream().forEach(liveOnlineCountVo -> {
                                String channelId = liveOnlineCountVo.getChannelId();
                                if (!StringUtils.isEmpty(channelId) && channelId.equals(a.getChannel())){
                                    calendarTask.setTaskUseNum(liveOnlineCountVo.getCount());
                                }
                            });
                        }
                    }
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.LIVE.getSort());
                    calendarTask.setTaskButtonStatus(Arrays.asList(ButtonStatus.WATCH_NOW.getCode()));
//                    if (a.getStartTime() != null && now.getTime() < a.getStartTime().getTime()) {
//                        calendarTask.setTaskButtonStatus(null);
//                    }
                    calendarTask.setViewType(a.getViewType());
                    calendarTasks.add(calendarTask);
                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;
    }

    /**
     * 获取专辑数据
     *
     * @param calendarTaskPage
     * @param type
     * @return
     */
    public Page<CalendarTask> getAlbum(Page<CalendarTask> calendarTaskPage, com.yizhi.album.application.vo.CalendarTaskParamVo paramVo, Integer type) {
        Page<AlbumCalendarVo> page = albumClient.getPageToCalendar(paramVo);

        if (page != null) {
            List<AlbumCalendarVo> albumCalendarVos = page.getRecords();

            if (CollectionUtils.isNotEmpty(albumCalendarVos)) {
                List calendarTasks = new ArrayList(albumCalendarVos.size());
                albumCalendarVos.forEach(a -> {
                    CalendarTask calendarTask = new CalendarTask();
                    calendarTask.setTaskId(a.getId());
                    calendarTask.setTaskTypeString("专辑");
                    calendarTask.setTaskName(a.getName());
                    calendarTask.setTaskLogo(a.getImage());
                    calendarTask.setTaskType(type);
                    calendarTask.setFinishDate(a.getTaskEndDate());
                    calendarTask.setTaskStartDate(a.getTaskStartDate());
                    //排序字段
                    calendarTask.setSort(CalendarTaskSortEnums.ALBUM.getSort());
                    calendarTask.setTaskEndDate(a.getTaskEndDate());
                    if (DateUtil.isSameDay(paramVo.getDate(), new Date())) {
                        calendarTask.setTaskButtonStatus(Arrays.asList(ButtonStatus.GO_STUDY.getCode()));
                    }
                    calendarTasks.add(calendarTask);
                });
                calendarTasks.addAll(calendarTaskPage.getRecords());
                calendarTaskPage.setRecords(calendarTasks);
            }
            calendarTaskPage.setTotal(page.getTotal());
        }
        return calendarTaskPage;
    }
}
