package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yonge.cooleshow.biz.dal.dao.CourseScheduleDao;
import com.yonge.cooleshow.biz.dal.dao.HomeDao;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetDao;
import com.yonge.cooleshow.biz.dal.dao.UserAccountRecordDao;
import com.yonge.cooleshow.biz.dal.dto.SubjectHomeSearch;
import com.yonge.cooleshow.biz.dal.dto.req.TotalReq;
import com.yonge.cooleshow.biz.dal.enums.CourseScheduleEnum;
import com.yonge.cooleshow.biz.dal.enums.GoodTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.TeacherTagEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.support.WrapperUtil;
import com.yonge.cooleshow.biz.dal.vo.CourseHomeVo;
import com.yonge.cooleshow.biz.dal.vo.SubjectHomeVo;
import com.yonge.cooleshow.biz.dal.vo.TagTotalTeacher;
import com.yonge.cooleshow.biz.dal.vo.res.HomeTotalStudent;
import com.yonge.cooleshow.biz.dal.vo.res.HomeTotalTeacher;
import com.yonge.cooleshow.biz.dal.vo.res.HomeUserToDoNum;
import com.yonge.cooleshow.biz.dal.wrapper.TeacherIndexWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.teacher.TeacherHomeWrapper;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.toolset.base.page.PageInfo;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.utils.date.DateUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author: liweifan
 * @Data: 2022/3/30 18:08
 */
@Service
public class HomeServiceImpl implements HomeService {
    @Resource
    private HomeDao baserMapper;
    @Resource
    private CourseScheduleService courseScheduleService;
    @Resource
    private MusicSheetDao musicSheetDao;
    @Resource
    private UserAccountRecordDao userAccountRecordDao;
    @Resource
    private ExposureRecordService exposureRecordService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private SysMusicCompareRecordService sysMusicCompareRecordService;
    @Resource
    private UserOrderDetailService userOrderDetailService;

    @Override
    public HomeUserToDoNum getUserToDoNum() {
        HomeUserToDoNum userToDoNum = baserMapper.getUserToDoNum();
        userToDoNum.setEntryNum(null == userToDoNum.getEntryNum() ? 0 : userToDoNum.getEntryNum());
        userToDoNum.setMusicianNum(null == userToDoNum.getMusicianNum() ? 0 : userToDoNum.getMusicianNum());
        userToDoNum.setMusicNum(null == userToDoNum.getMusicNum() ? 0 : userToDoNum.getMusicNum());
        userToDoNum.setVideoCourseNum(null == userToDoNum.getVideoCourseNum() ? 0 : userToDoNum.getVideoCourseNum());
        userToDoNum.setStyleNum(null == userToDoNum.getStyleNum()? 0 : userToDoNum.getStyleNum());
        return userToDoNum;
    }

    @Override
    public HttpResponseResult<HomeTotalTeacher> totalTeacher(TotalReq query) {
        //统计查询
        List<HomeTotalTeacher> totalList = baserMapper.totalTeacher(query.getTimeType().getCode(), query);

        // 点亮图标
        List<TagTotalTeacher> tagList = baserMapper.tagTeacher(query.getTimeType().getCode(), query);

        Map<String, Map<String, List<TagTotalTeacher>>> tagTimeTypeGroup = tagList.stream()
                                                                         .collect(Collectors.groupingBy(
                                                                                 TagTotalTeacher::getTimeStr,
                                                                                 Collectors.groupingBy(
                                                                                         TagTotalTeacher::getTagType)));
        Map<String, Map<Long, List<TagTotalTeacher>>> tagTimeUserGroup = tagList.stream()
                                                                       .collect(Collectors.groupingBy(
                                                                               TagTotalTeacher::getTimeStr,
                                                                               Collectors.groupingBy(
                                                                                       TagTotalTeacher::getUserId)));

        Integer registerNum = 0;
        Integer entryNum = 0;
        Integer liveNum = 0;
        Integer musicianNum = 0;
        Integer tagNum  = tagList.stream().collect(Collectors.groupingBy(TagTotalTeacher::getUserId)).size();
        Integer styleTagNum = 0;
        Integer videoTagNum = 0;
        Integer liveTagNum = 0;
        Integer musicTagNum = 0;
        for (HomeTotalTeacher totalTeacher : totalList) {
            totalTeacher.setRegisterNum(null == totalTeacher.getRegisterNum() ? 0 : totalTeacher.getRegisterNum());
            totalTeacher.setEntryNum(null == totalTeacher.getEntryNum() ? 0 : totalTeacher.getEntryNum());
            totalTeacher.setLiveNum(null == totalTeacher.getLiveNum() ? 0 : totalTeacher.getLiveNum());
            totalTeacher.setMusicianNum(null == totalTeacher.getMusicianNum() ? 0 : totalTeacher.getMusicianNum());

            Map<String, List<TagTotalTeacher>> typeGroup = tagTimeTypeGroup.get(totalTeacher.getTimeStr());
            if (typeGroup != null) {
                List<TagTotalTeacher> liveTagList = typeGroup.get(TeacherTagEnum.LIVE.getCode());
                List<TagTotalTeacher> musicTagList = typeGroup.get(TeacherTagEnum.MUSIC.getCode());
                List<TagTotalTeacher> styleTagList = typeGroup.get(TeacherTagEnum.STYLE.getCode());
                List<TagTotalTeacher> videoTagList = typeGroup.get(TeacherTagEnum.VIDEO.getCode());
                totalTeacher.setLiveTagNum(CollectionUtils.isEmpty(liveTagList) ? 0:liveTagList.size());
                totalTeacher.setMusicTagNum(CollectionUtils.isEmpty(musicTagList) ? 0:musicTagList.size());
                totalTeacher.setStyleTagNum(CollectionUtils.isEmpty(styleTagList) ? 0:styleTagList.size());
                totalTeacher.setVideoTagNum(CollectionUtils.isEmpty(videoTagList) ? 0:videoTagList.size());
            } else {
                totalTeacher.setLiveTagNum(0);
                totalTeacher.setMusicTagNum(0);
                totalTeacher.setStyleTagNum(0);
                totalTeacher.setVideoTagNum(0);
            }


            Map<Long, List<TagTotalTeacher>> userGroup = tagTimeUserGroup.get(totalTeacher.getTimeStr());

            if (userGroup != null) {

                totalTeacher.setTagNum(userGroup.size());
            } else {
                totalTeacher.setTagNum(0);
            }


            registerNum += totalTeacher.getRegisterNum();
            entryNum += totalTeacher.getEntryNum();
            liveNum += totalTeacher.getLiveNum();
            musicianNum += totalTeacher.getMusicianNum();
            styleTagNum += totalTeacher.getStyleTagNum();
            videoTagNum += totalTeacher.getVideoTagNum();
            liveTagNum += totalTeacher.getLiveTagNum();
            musicTagNum += totalTeacher.getMusicTagNum();
        }
        HomeTotalTeacher total = new HomeTotalTeacher();
        total.setRegisterNum(registerNum);
        total.setEntryNum(entryNum);
        total.setLiveNum(liveNum);
        total.setMusicianNum(musicianNum);
        total.setTagNum(tagNum);
        total.setStyleTagNum(styleTagNum);
        total.setVideoTagNum(videoTagNum);
        total.setLiveTagNum(liveTagNum);
        total.setMusicTagNum(musicTagNum);
        total.setInfoList(totalList);
        return HttpResponseResult.succeed(total);
    }

    @Override
    public HttpResponseResult<HomeTotalStudent> totalStudent(TotalReq query) {
        List<HomeTotalStudent> totalList = baserMapper.totalStudent(query.getTimeType().getCode(), query);
        Integer registerNum = 0;
        Integer vipNum = 0;
        Integer svipNum = 0;
        Integer practiceNum = 0;
        Integer videoNum = 0;
        Integer liveNum = 0;
        Integer musicNum = 0;
        Integer shoppingNum = 0;
        Integer payStudentNum = 0;
        Integer discountNum = 0;
        Integer vipCourseNum = 0;

        for (HomeTotalStudent totalStudent : totalList) {
            totalStudent.setRegisterNum(null == totalStudent.getRegisterNum() ? 0 : totalStudent.getRegisterNum());
            totalStudent.setVipNum(null == totalStudent.getVipNum() ? 0 : totalStudent.getVipNum());
            totalStudent.setSvipNum(null == totalStudent.getSvipNum() ? 0 : totalStudent.getSvipNum());
            totalStudent.setPracticeNum(null == totalStudent.getPracticeNum() ? 0 : totalStudent.getPracticeNum());
            totalStudent.setVideoNum(null == totalStudent.getVideoNum() ? 0 : totalStudent.getVideoNum());
            totalStudent.setLiveNum(null == totalStudent.getLiveNum() ? 0 : totalStudent.getLiveNum());
            totalStudent.setMusicNum(null == totalStudent.getMusicNum() ? 0 : totalStudent.getMusicNum());
            totalStudent.setShoppingNum(null == totalStudent.getShoppingNum() ? 0 : totalStudent.getShoppingNum());
            totalStudent.setPayStudentNum(null == totalStudent.getPayStudentNum() ? 0 : totalStudent.getPayStudentNum());
            totalStudent.setDiscountNum(null == totalStudent.getDiscountNum() ? 0 : totalStudent.getDiscountNum());
            totalStudent.setVipCourseNum(null == totalStudent.getVipCourseNum() ? 0 : totalStudent.getVipCourseNum());

            registerNum += totalStudent.getRegisterNum();
            vipNum += totalStudent.getVipNum();
            svipNum += totalStudent.getSvipNum();
            practiceNum += totalStudent.getPracticeNum();
            videoNum += totalStudent.getVideoNum();
            liveNum += totalStudent.getLiveNum();
            musicNum += totalStudent.getMusicNum();
            shoppingNum += totalStudent.getShoppingNum();
            payStudentNum += totalStudent.getPayStudentNum();
            discountNum += totalStudent.getDiscountNum();
            vipCourseNum += totalStudent.getVipCourseNum();
        }
        HomeTotalStudent total = new HomeTotalStudent();
        total.setRegisterNum(registerNum);
        total.setVipNum(vipNum);
        total.setSvipNum(svipNum);
        total.setPracticeNum(practiceNum);
        total.setVideoNum(videoNum);
        total.setLiveNum(liveNum);
        total.setMusicNum(musicNum);
        total.setShoppingNum(shoppingNum);
        total.setPayStudentNum(payStudentNum);
        total.setDiscountNum(discountNum);
        total.setVipCourseNum(vipCourseNum);

        total.setInfoList(totalList);
        return HttpResponseResult.succeed(total);
    }

    /**
     * 获取首页课程数据
     * <p>未完成  未开始&进行中
     * <p>已完成  已完成课程
     *
     * @param param 传入参数
     *              <p> - dateTime  如果查询年数据 yyyy   如果查询月数据 yyyy-mm
     *              <p> - type 类型  PRACTICE趣纠课  LIVE直播课
     *              <p> - timeType 时间类型 MONTH、月度 YEAR
     */
    public CourseHomeVo queryCourseHomeData(Map<String, Object> param) {
        CourseScheduleEnum.existCourseType(WrapperUtil.toStr(param, "type"), "课程类型参数错误");
        String dateTimeStr = WrapperUtil.toStr(param, "dateTime", "查询时间不能为空!");
        String timeType = WrapperUtil.toStr(param, "timeType", "查询时间不类型不能为空!");
        //按年查询true  按月查询false
        boolean isYear = timeType.equals("YEAR");
        //获取年
        String[] split = dateTimeStr.split("-");
        int year = Integer.parseInt(split[0]);
        //获取月
        int month = isYear ? 1 : Integer.parseInt(split[1]);
        LocalDate firstDate;
        LocalDate endDate;
        CourseHomeVo result = new CourseHomeVo();
        CourseScheduleDao courseScheduleServiceDao = courseScheduleService.getDao();
        firstDate = LocalDate.of(year, month, 1);
        //获取开始时间
        if (isYear) {
            //查询当年最后一天
            endDate = firstDate.with(TemporalAdjusters.lastDayOfYear());
        } else {
            //查询当月最后一天
            endDate = firstDate.with(TemporalAdjusters.lastDayOfMonth());
        }
        param.put("startDate", firstDate);
        param.put("endDate", endDate);

        //查询数据
        List<CourseHomeVo.CourseHomeInfoVo> courseYearInfoList;
        if (isYear) {
            courseYearInfoList = courseScheduleServiceDao.queryCourseHomeOfYear(param);
        } else {
            courseYearInfoList = courseScheduleServiceDao.queryCourseHomeOfMonth(param);
        }
        if (CollectionUtils.isEmpty(courseYearInfoList)) {
            courseYearInfoList = new ArrayList<>();
        }
        Map<String, CourseHomeVo.CourseHomeInfoVo> collect = courseYearInfoList.stream()
                .collect(Collectors.toMap(CourseHomeVo.CourseHomeInfoVo::getDate, Function.identity(), (key1, key2) -> key2));
        //补全数据
        while (firstDate.isBefore(endDate)) {
            CourseHomeVo.CourseHomeInfoVo infoVo = collect.get(firstDate.toString());
            if (Objects.isNull(infoVo)) {
                infoVo = new CourseHomeVo.CourseHomeInfoVo();
                if (isYear) {
                    infoVo.setDate(firstDate.toString().substring(0, 7));
                } else {
                    infoVo.setDate(firstDate.toString());
                }
                infoVo.setDoneCount(0);
                infoVo.setUndoneCount(0);
                courseYearInfoList.add(infoVo);
            } else {
                if (isYear) {
                    infoVo.setDate(firstDate.toString().substring(0, 7));
                }
            }
            if (isYear) {
                firstDate = firstDate.plusMonths(1L);
            } else {
                firstDate = firstDate.plusDays(1L);
            }
        }
        result.setCourseHomeInfoList(courseYearInfoList);
        //计算总数方法
        Function<Function<CourseHomeVo.CourseHomeInfoVo, Integer>, Integer> reduceFunc = (c) -> result.getCourseHomeInfoList().stream()
                .map(c)
                .reduce(0, Integer::sum);
        result.setTotalDoneCount(reduceFunc.apply(CourseHomeVo.CourseHomeInfoVo::getDoneCount));
        result.setTotalUndoneCount(reduceFunc.apply(CourseHomeVo.CourseHomeInfoVo::getUndoneCount));
        result.setTotalCount(result.getTotalDoneCount() + result.getTotalUndoneCount());
        result.getCourseHomeInfoList().sort(Comparator.comparing(CourseHomeVo.CourseHomeInfoVo::getDate));
        return result;
    }

    @Override
    public PageInfo<SubjectHomeVo> subjectHome(IPage<SubjectHomeVo> page, SubjectHomeSearch query) {
        PageInfo<SubjectHomeVo> subjectHomeVoPageInfo = PageUtil.pageInfo(baserMapper.selectSubjectHome(page, query));
        List<SubjectHomeVo> rows = subjectHomeVoPageInfo.getRows();
        for (int i = 0; i < rows.size(); i++) {
            rows.get(i).setIndex((subjectHomeVoPageInfo.getPageNo() -1) * subjectHomeVoPageInfo.getLimit() + i + 1);
        }
        return subjectHomeVoPageInfo;
    }


    /**
     * 老师端首页统计课程
     *
     * @param query 参数
     * @return TeacherHomeWrapper.TeacherTotalCourse
     */
    @Override
    public List<TeacherHomeWrapper.TeacherTotalCourse> teacherTotalCourse(TeacherHomeWrapper.TeacherTotalCourseQuery query) {

        // VIP定制课 趣纠课 直播课 视频课

        List<TeacherHomeWrapper.TeacherTotalCourse> result = new ArrayList<>();
        result.add(TeacherHomeWrapper.TeacherTotalCourse.builder().goodType(GoodTypeEnum.LIVE).build());
        result.add(TeacherHomeWrapper.TeacherTotalCourse.builder().goodType(GoodTypeEnum.VIDEO).build());
        result.add(TeacherHomeWrapper.TeacherTotalCourse.builder().goodType(GoodTypeEnum.VIP_COURSE).build());
        result.add(TeacherHomeWrapper.TeacherTotalCourse.builder().goodType(GoodTypeEnum.PRACTICE).build());



        List<TeacherHomeWrapper.TeacherTotalCourse> teacherTotalCourses = baserMapper.teacherTotalCourse(query);
        Map<GoodTypeEnum, TeacherHomeWrapper.TeacherTotalCourse> collect = teacherTotalCourses.stream()
                .collect(Collectors.toMap(TeacherHomeWrapper.TeacherTotalCourse::getGoodType, Function.identity(), (key1, key2) -> key2));
        for (TeacherHomeWrapper.TeacherTotalCourse teacherTotalCourse : result) {
            TeacherHomeWrapper.TeacherTotalCourse totalCourse = collect.get(teacherTotalCourse.getGoodType());
            if (totalCourse != null) {
                teacherTotalCourse.setBuyNum(totalCourse.getBuyNum());
                teacherTotalCourse.setClassHourNum(totalCourse.getClassHourNum());
            }
        }
        return result;
    }


    /**
     * 老师端首页统计乐谱
     *
     * @param teacherId 老师ID
     * @return TeacherHomeWrapper.MusicSheetTotal 乐谱统计
     */
    @Override
    public TeacherHomeWrapper.MusicSheetTotal musicSheetTotal(Long teacherId) {

        /*
        曲目数量：审核通过、未下架的曲目数量

        审核中：已提交审核还未通过审核的曲目

        曝光：用户查看到曲目即曝光+1，同一个页面反复滑动查看曝光数不变；刷新页面或跳转到新页面则曝光+1

        例：用户进入到首页，查看到当前曲目，曝光+1；用户在当前页面反复滑动，无刷新时，则曝光还是为1，用户刷新或跳转到新页面查看到该曲目时，曝光累计增加

        付费人数：该老师所有的曲目付费人数，去重统计

        收益：售卖曲目累计收益金额
         */
        TeacherHomeWrapper.MusicSheetTotal musicSheetTotal = musicSheetDao.musicSheetTotal(teacherId);
        if (musicSheetTotal == null) {
            musicSheetTotal = new TeacherHomeWrapper.MusicSheetTotal();
        }
        // 收益
        TeacherHomeWrapper.MusicSheetTotal musicSheetTotal1 = userAccountRecordDao.musicSheetTotal(teacherId);
        if (musicSheetTotal1 != null) {
            musicSheetTotal.setMusicSheetIncome(musicSheetTotal1.getMusicSheetIncome());
            musicSheetTotal.setMusicSheetPayNum(musicSheetTotal1.getMusicSheetPayNum());
        }


        return musicSheetTotal;

    }

    @Override
    public List<TeacherHomeWrapper.MusicSheetTotal> musicSheetPage(TeacherHomeWrapper.MusicSheetQuery query) {
        return musicSheetDao.musicSheetPage(query);
    }

    @Override
    public TeacherIndexWrapper.TeacherPracticeHome getTeacherPracticeHome(TeacherIndexWrapper.SummarySearch summarySearch) {
        TeacherIndexWrapper.TeacherPracticeHome teacherPracticeHome = new TeacherIndexWrapper.TeacherPracticeHome();
        //获取老师关联的学员
        List<Long> studentIds = teacherService.getDao().getStudentIds(summarySearch.getTeacherId(),summarySearch.getSubjectId());
        if(CollectionUtils.isEmpty(studentIds)){
            return teacherPracticeHome;
        }
        //获取学员练习汇总
        TeacherIndexWrapper.PracticeSummaryDto practiceSummary = sysMusicCompareRecordService.getDao().getStudentTrainOverView(studentIds,summarySearch);
        //计算平均练习时长
        if(Objects.nonNull(practiceSummary)
                && practiceSummary.getPracticeCount().compareTo(BigDecimal.ZERO) > 0
                && practiceSummary.getTotalPracticeTime().compareTo(BigDecimal.ZERO) > 0){
            practiceSummary.setAveragePracticeTime(practiceSummary.getTotalPracticeTime().divide(practiceSummary.getPracticeCount(), 0, BigDecimal.ROUND_HALF_UP));
        }
        teacherPracticeHome.setPracticeSummary(practiceSummary);

        //获取学员练习时长
        //获取分组条件，如果所选时间段只有一天，则按小时分组，超过一个月按天分组，超过一年按月分组
        String groupBy;
        List<String> dateList;
        Date startDate = DateUtil.strToDate(summarySearch.getStartTime(), DateUtil.DEFAULT_PATTERN);
        if(StringUtils.equals(summarySearch.getStartTime(),summarySearch.getEndTime())){
            groupBy = "%Y-%m-%d %H";
            //获取当天的小时段
            dateList = DateUtil.getHourList(startDate);
        }else {
            Date endDate = DateUtil.strToDate(summarySearch.getEndTime(), DateUtil.DEFAULT_PATTERN);
            if(DateUtil.daysBetween(startDate,endDate) <= 31){
                groupBy = "%Y-%m-%d";
                dateList = DateUtil.getDayList(startDate,endDate);
            }else if(DateUtil.monthsBetween(startDate,endDate) <= 12){
                groupBy = "%Y-%m";
                dateList = DateUtil.getMonthList(startDate,endDate);
            }else {
                groupBy = "%Y";
                dateList = DateUtil.getYearList(startDate,endDate);
            }
        }
        List<TeacherIndexWrapper.PracticeTimeDto> studentTrainTime = sysMusicCompareRecordService.getDao().getStudentTrainTime(studentIds, summarySearch, groupBy);
        //补全时间段
        teacherPracticeHome.setPracticeTimes(fillData(studentTrainTime,dateList));
        //练习人数
        List<TeacherIndexWrapper.PracticeTimeDto> studentTrainCount = sysMusicCompareRecordService.getDao().getStudentTrainCount(studentIds, summarySearch, groupBy);
        //补全时间段
        teacherPracticeHome.setPracticeCounts(fillData(studentTrainCount,dateList));

        return teacherPracticeHome;
    }

    //数据补全，按时间顺序
    private List<TeacherIndexWrapper.PracticeTimeDto> fillData(List<TeacherIndexWrapper.PracticeTimeDto> studentTrainTime, List<String> dateList) {
        Map<String,TeacherIndexWrapper.PracticeTimeDto> timeMap = studentTrainTime.stream()
                .collect(Collectors.toMap(TeacherIndexWrapper.PracticeTimeDto::getDate, o -> o));
        List<TeacherIndexWrapper.PracticeTimeDto> result = new ArrayList<>();
        for (String s : dateList) {
            TeacherIndexWrapper.PracticeTimeDto practiceTimeDto = timeMap.get(s);
            if(Objects.nonNull(practiceTimeDto)){
                result.add(practiceTimeDto);
            }else {
                result.add(new TeacherIndexWrapper.PracticeTimeDto(s,0L));
            }
        }
        return result;
    }

    //数据补全，按时间顺序
    private List<TeacherIndexWrapper.CourseExposureTotal> exposureFillData(List<TeacherIndexWrapper.CourseExposureTotal> exposureTotals,
                                                                           List<String> dateList,
                                                                           String[] typeArr) {
        if(exposureTotals == null){
            exposureTotals = new ArrayList<>();
        }
        //按类型分组
        Map<String, List<TeacherIndexWrapper.CourseExposureTotal>> typeMap = exposureTotals.stream()
                .collect(Collectors.groupingBy(TeacherIndexWrapper.CourseExposureTotal::getType));
        List<TeacherIndexWrapper.CourseExposureTotal> result = new ArrayList<>();
        //按时间段补全数据
        for (String s : dateList) {
            for (String type : typeArr) {
                List<TeacherIndexWrapper.CourseExposureTotal> dateMap = typeMap.get(type);
                if(CollectionUtils.isEmpty(dateMap)){
                    result.add(new TeacherIndexWrapper.CourseExposureTotal(s,type,0));
                }else {
                    Map<String, TeacherIndexWrapper.CourseExposureTotal> dateMapGroup = dateMap.stream()
                            .collect(Collectors.toMap(TeacherIndexWrapper.CourseExposureTotal::getDate, o -> o));
                    TeacherIndexWrapper.CourseExposureTotal courseExposureTotal = dateMapGroup.get(s);
                    if(Objects.nonNull(courseExposureTotal)){
                        result.add(courseExposureTotal);
                    }else {
                        result.add(new TeacherIndexWrapper.CourseExposureTotal(s,type,0));
                    }
                }
            }
        }
        return result;
    }

    @Override
    public List<TeacherIndexWrapper.StudentPracticeSummaryDto> getTeacherHomeStudent(TeacherIndexWrapper.StudentSearch studentSearch) {
        //获取老师关联的学员
        List<Long> studentIds = teacherService.getDao().getStudentIds(studentSearch.getTeacherId(),studentSearch.getSubjectId());
        if(CollectionUtils.isEmpty(studentIds)){
            return Collections.emptyList();
        }
        //获取学员练习汇总
        return sysMusicCompareRecordService.getDao().getStudentTrainOverViewList(studentIds,studentSearch);
    }


    @Override
    public Map<String,List<TeacherIndexWrapper.CourseExposureTotal>> courseExposureTotal(TeacherIndexWrapper.CourseExposureSearch search) {
        String groupBy;
        List<String> dateList;
        Date startDate = DateUtil.strToDate(search.getStartTime(), DateUtil.DEFAULT_PATTERN);
        Date endDate = DateUtil.strToDate(search.getEndTime(), DateUtil.DEFAULT_PATTERN);
        if(DateUtil.daysBetween(startDate,endDate) <= 31){
            groupBy = "%Y-%m-%d";
            dateList = DateUtil.getDayList(startDate,endDate);
        }else if(DateUtil.monthsBetween(startDate,endDate) <= 12){
            groupBy = "%Y-%m";
            dateList = DateUtil.getMonthList(startDate,endDate);
        }else {
            groupBy = "%Y";
            dateList = DateUtil.getYearList(startDate,endDate);
        }
        List<TeacherIndexWrapper.CourseExposureTotal> courseExposureTotals = exposureRecordService.getDao().courseExposureTotal(search, groupBy);
        //按分类分组
        Map<String,List<TeacherIndexWrapper.CourseExposureTotal>> typeMap = courseExposureTotals.stream()
                .collect(Collectors.groupingBy(TeacherIndexWrapper.CourseExposureTotal::getType));
        Map<String,List<TeacherIndexWrapper.CourseExposureTotal>> result = new HashMap<>();
        result.put("EXPOSURE_LIVE",exposureFillData(typeMap.get(GoodTypeEnum.LIVE.getCode()),dateList,new String[]{GoodTypeEnum.LIVE.getCode()}));
        result.put("EXPOSURE_VIDEO",exposureFillData(typeMap.get(GoodTypeEnum.VIDEO.getCode()),dateList,new String[]{GoodTypeEnum.VIDEO.getCode()}));
        result.put("EXPOSURE_MUSIC",exposureFillData(typeMap.get(GoodTypeEnum.MUSIC.getCode()),dateList,new String[]{GoodTypeEnum.MUSIC.getCode()}));
        return result;
    }

    @Override
    public Map<String,List<TeacherIndexWrapper.CourseExposureTotal>> courseBuyTotal(TeacherIndexWrapper.CourseExposureSearch search) {
        //获取学员练习时长
        //获取分组条件，如果所选时间段只有一天，则按小时分组，超过一个月按天分组，超过一年按月分组
        String groupBy;
        List<String> dateList;
        Date startDate = DateUtil.strToDate(search.getStartTime(), DateUtil.DEFAULT_PATTERN);
        Date endDate = DateUtil.strToDate(search.getEndTime(), DateUtil.DEFAULT_PATTERN);
        if(DateUtil.daysBetween(startDate,endDate) <= 31){
            groupBy = "%Y-%m-%d";
            dateList = DateUtil.getDayList(startDate,endDate);
        }else if(DateUtil.monthsBetween(startDate,endDate) <= 12){
            groupBy = "%Y-%m";
            dateList = DateUtil.getMonthList(startDate,endDate);
        }else {
            groupBy = "%Y";
            dateList = DateUtil.getYearList(startDate,endDate);
        }
        Map<String,List<TeacherIndexWrapper.CourseExposureTotal>> result = new HashMap<>();
        //直播课
        List<TeacherIndexWrapper.CourseExposureTotal> liveSummer = userOrderDetailService.getDao().liveBuyTotal(search,groupBy);
        result.put(GoodTypeEnum.LIVE.getCode(),exposureFillData(liveSummer,dateList,new String[]{GoodTypeEnum.LIVE.getCode()}));
        //视频课
        List<TeacherIndexWrapper.CourseExposureTotal> videoSummer = userOrderDetailService.getDao().videoBuyTotal(search,groupBy);
        result.put(GoodTypeEnum.VIDEO.getCode(),exposureFillData(videoSummer,dateList,new String[]{GoodTypeEnum.VIDEO.getCode()}));
        //获取老师关联的学员
        List<Long> studentIds = teacherService.getDao().getStudentIds(search.getTeacherId(),null);
        if(CollectionUtils.isNotEmpty(studentIds)){
            //曲谱
            search.setStudentIds(studentIds);
            List<TeacherIndexWrapper.CourseExposureTotal> musicSheetSummer = userOrderDetailService.getDao().musicSheetBuyTotal(search,groupBy);
            result.put(GoodTypeEnum.MUSIC.getCode(),exposureFillData(musicSheetSummer,dateList,new String[]{GoodTypeEnum.MUSIC.getCode()}));
        }
        return result;
    }

}
