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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonAuthRecordDao;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonGroupDao;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonGroupDetailDao;
import com.yonge.cooleshow.biz.dal.dto.CourseMusicAlbumRelationDto;
import com.yonge.cooleshow.biz.dal.dto.Mapper;
import com.yonge.cooleshow.biz.dal.dto.VideoLessonGroupDetailDto;
import com.yonge.cooleshow.biz.dal.dto.search.VideoGroupSearch;
import com.yonge.cooleshow.biz.dal.dto.search.VideoLessonGroupSearch;
import com.yonge.cooleshow.biz.dal.dto.search.VideoLessonSearch;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.TeacherTagEnum;
import com.yonge.cooleshow.biz.dal.enums.course.CourseRelationTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.course.CourseTypeEnum;
import com.yonge.cooleshow.biz.dal.queryInfo.CourseRelationQueryInfo;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.cooleshow.biz.dal.wrapper.course.CourseRelationWrapper;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.string.MessageFormatter;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import com.yonge.toolset.utils.json.JsonUtil;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * VideoLessonGroupService服务实现类
 *
 * @author yzp
 * @version v1.0
 * @date 2022-03-26 00:01:38
 **/
@Service
public class VideoLessonGroupServiceImpl extends ServiceImpl<VideoLessonGroupDao, VideoLessonGroup> implements VideoLessonGroupService {

    private final static Logger log = LoggerFactory.getLogger(VideoLessonGroupServiceImpl.class);

    @Autowired
    private MusicTagService musicTagService;

    @Autowired
    private VideoLessonGroupDao videoLessonGroupDao;
    @Autowired
    private VideoLessonGroupDetailDao videoLessonGroupDetailDao;
    @Autowired
    private VideoLessonAuthRecordDao recordDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private SysConfigService sysConfigService;
    
    @Autowired
    private VideoLessonGroupLogService videoLessonGroupLogService;
    @Autowired
    private VideoLessonGroupDetailService videoLessonGroupDetailService;
    @Autowired
    private CourseRelationMusicAlbumService courseRelationMusicAlbumService;

    public VideoLessonGroupDao getDao() {
        return videoLessonGroupDao;
    }

    /**
     * @Description: 查询视频课组
     * @Author: cy
     * @Date: 2022/3/31
     */
    @Override
    public IPage<VideoLessonGroupVo> selectPage(IPage<VideoLessonGroupVo> page, VideoLessonGroupSearch query) {
		if (org.apache.commons.lang3.StringUtils.isNotBlank(query.getAuditStatus())) {

			if (query.getAuditStatus().equals(AuthStatusEnum.DOING.getCode())) {
				query.setShelvesFlag(null);
			} else if (query.getAuditStatus().equals(AuthStatusEnum.UNPASS.getCode())) {
				query.setShelvesFlag(null);
			} else {
				if (query.getAuditStatus().equals(AuthStatusEnum.OUT_SALE.getCode())) {
					query.setAuditStatus(AuthStatusEnum.PASS.getCode());
					query.setShelvesFlag(0);
				} else if (query.getAuditStatus().equals(AuthStatusEnum.PASS.getCode())) {
					query.setShelvesFlag(1);
				}
			}
		}
        List<VideoLessonGroupVo> videoLessonGroupVos = baseMapper.selectPage(page, query);
        if(CollectionUtils.isNotEmpty(videoLessonGroupVos)){
            //获取直播课关联的曲目数量
            List<Long> videoLessonGroupIds = videoLessonGroupVos.stream().map(VideoLessonGroupVo::getId).collect(Collectors.toList());
            List<Mapper> musicNum = this.baseMapper.countMusicAlbum(videoLessonGroupIds);
            Map<Long,Long> map = musicNum.stream().collect(Collectors.toMap(e->Long.parseLong(e.getKey().toString()), e->Long.parseLong(e.getValue().toString())));
            for (VideoLessonGroupVo videoLessonGroupVo : videoLessonGroupVos) {
                if (videoLessonGroupVo.getLessonPrice().compareTo(BigDecimal.ZERO) == 0) {
                    videoLessonGroupVo.setCountStudent(videoLessonGroupVo.getCountStudent() + videoLessonGroupVo.getVirtualNumber());
                }
                videoLessonGroupVo.setMusicNum(map.get(videoLessonGroupVo.getId()));
            }
        }
        return page.setRecords(videoLessonGroupVos);
    }

    public List<VideoLessonGroupVo> selectPage(VideoLessonGroupSearch query) {
        List<VideoLessonGroupVo> list = baseMapper.selectPage(null, query);
        List<VideoLessonGroupVo> collect = list.stream().filter(videoLessonGroupVo -> !videoLessonGroupVo.getId().equals(query.getVideoLessonGroupId()))
                                               .sorted(Comparator.comparing(VideoLessonGroupVo::getCountStudent, Comparator.reverseOrder())).limit(2).collect(Collectors.toList());
        for (VideoLessonGroupVo videoLessonGroupVo : collect) {
            if (videoLessonGroupVo.getLessonPrice().compareTo(BigDecimal.ZERO) == 0) {
                videoLessonGroupVo.setCountStudent(videoLessonGroupVo.getCountStudent() + videoLessonGroupVo.getVirtualNumber());
            }
        }
        return collect;
    }

    /**
     * @Description: 根据组id查详情
     * @Author: cy
     * @Date: 2022/4/11
     */
    public VideoLessonGroup selectGroup(Long groupId) {
        return videoLessonGroupDao.selectGroupById(groupId);
    }

    /**
     * @Description: 修改视频课组
     * @Author: cy
     * @Date: 2022/3/31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroup(VideoLessonGroupUpVo lessonGroupUpVo) {
        videoLessonGroupDao.updateGroup(lessonGroupUpVo);
    }

    /**
     * @Description: 审核-修改视频课组审核状态
     * @Author: cy
     * @Date: 2022/4/24
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGroup(VideoLessonExamineVo examineVo) {
    	
    	if (examineVo.getAuditStatus().equals("PASS")) {
    		examineVo.setShelvesFlag(1);
            examineVo.setShelvesTime(new Date());
    	}
        //改主表
        videoLessonGroupDao.updateExamine(examineVo);
        
        VideoLessonGroup lessonGroup = baseMapper.selectById(examineVo.getId());
        //插从表
        VideoLessonAuthRecord record = new VideoLessonAuthRecord();
        record.setAuditStatus(examineVo.getAuditStatus());
        record.setVideoGroupId(examineVo.getId());
        record.setAuditId(examineVo.getAuditId());
        record.setAuditName(examineVo.getAuditName());
        record.setRemarks(examineVo.getRemarks());
        record.setVersion(videoLessonGroupLogService.queryMaxVersion(examineVo.getId()));
        recordDao.insert(record);

        //清状态
        recordDao.delete(Wrappers.<VideoLessonAuthRecord>lambdaQuery()
                .eq(VideoLessonAuthRecord::getVideoGroupId, examineVo.getId())
                .eq(VideoLessonAuthRecord::getAuditStatus, AuthStatusEnum.DOING));

        // 设置标签
        if (AuthStatusEnum.PASS.getCode().equals(examineVo.getAuditStatus())) {
            teacherService.setTeacherTag(lessonGroup.getTeacherId(), TeacherTagEnum.VIDEO);

            // 设置关联的曲目
            courseRelationMusicAlbumService.asyncUpdateCourseRelationMusicAlbumInfo(examineVo.getId(),CourseTypeEnum.VIDEO);

        }

        //推送
        String status = examineVo.getAuditStatus();
        Map<Long, String> receivers = new HashMap<>();
        SysUser teacher = sysUserFeignService.queryUserById(lessonGroup.getTeacherId());
        receivers.put(lessonGroup.getTeacherId(), teacher.getPhone());
        if (status.equals("PASS")) {
            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIDEO_SHEET_AUTH_PASS,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), lessonGroup.getLessonName());
            } catch (Exception e) {
                log.warn("视频课审核失败，{}", e.getMessage());
            }
        } else {
            try {
                String remark = "无";
                if (!StringUtils.isEmpty(examineVo.getRemarks())) {
                    remark = examineVo.getRemarks();
                }
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIDEO_SHEET_AUTH_UNPASS,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), lessonGroup.getLessonName(), remark);
            } catch (Exception e) {
                log.warn("视频课审核失败，{}", e.getMessage());
            }
        }
    }

    /**
     * 处理课程曲目关联关系
     */
    private void courseMusicAlbumRelation(List<VideoLessonGroupDetailDto> lessonList, Long lessonGroupId, Long userBy) {
        // 设置关联曲目

        // 需要更新的关联数据
        List<CourseRelationMusicAlbum> updateCourseRelationMusicAlbums = new ArrayList<>();
        // 需要添加的关联数据
        List<CourseRelationMusicAlbum> addCourseRelationMusicAlbums = new ArrayList<>();

        // 查询课程组所有的关联曲目
        List<CourseRelationMusicAlbum> relationMusicAlbumList = courseRelationMusicAlbumService.lambdaQuery()
                        .eq(CourseRelationMusicAlbum::getCourseGroupId,  lessonGroupId)
                        .ne(CourseRelationMusicAlbum::getDelFlog, 0)
                        .list();

        if (CollectionUtils.isEmpty(relationMusicAlbumList)) {
            relationMusicAlbumList = new ArrayList<>();
        }

        // 需要更新的id
        List<Long> updateCourseRelationIdList = new ArrayList<>();
        for (VideoLessonGroupDetailDto videoLessonGroupDetailDto : lessonList) {
            // 需要修改的关联数据
            List<CourseMusicAlbumRelationDto> relationList = Optional.ofNullable(videoLessonGroupDetailDto.getRelationList())
                    .orElse(Lists.newArrayList());

            videoLessonGroupDetailDto.setCourseRelationMusicAlbumList(new ArrayList<>());

            for (CourseMusicAlbumRelationDto courseMusicAlbumRelationDto : relationList) {
                CourseRelationMusicAlbum courseRelationMusicAlbum = new CourseRelationMusicAlbum();
                // 修改的数据
                if (courseMusicAlbumRelationDto.getRelationId() != null && courseMusicAlbumRelationDto.getRelationId() != 0) {
                    for (CourseRelationMusicAlbum relationMusicAlbum : relationMusicAlbumList) {
                        if (relationMusicAlbum.getId().equals(courseMusicAlbumRelationDto.getRelationId())) {
                            updateCourseRelationIdList.add(courseMusicAlbumRelationDto.getRelationId());
                            courseRelationMusicAlbum = relationMusicAlbum;
                            break;
                        }
                    }
                }
                courseRelationMusicAlbum.setCourseGroupId(videoLessonGroupDetailDto.getVideoLessonGroupId());
                courseRelationMusicAlbum.setCourseId(videoLessonGroupDetailDto.getId());
                courseRelationMusicAlbum.setCourseType(CourseTypeEnum.VIDEO);
                courseRelationMusicAlbum.setMusicAlbumId(courseMusicAlbumRelationDto.getMusicAlbumId());
                // 推荐该赠送
                if (courseRelationMusicAlbum.getUseRelationType() != null
                        && courseRelationMusicAlbum.getUseRelationType().equals(CourseRelationTypeEnum.RECOMMEND)
                        && courseMusicAlbumRelationDto.getUseRelationType().equals(CourseRelationTypeEnum.GIFT)) {
                    courseRelationMusicAlbum.setDelFlog(2);
                } else if (courseRelationMusicAlbum.getDelFlog() == null) {
                    courseRelationMusicAlbum.setDelFlog(1);
                }
                courseRelationMusicAlbum.setRelationType(courseMusicAlbumRelationDto.getRelationMusicAlbum());
                courseRelationMusicAlbum.setUseRelationType(courseMusicAlbumRelationDto.getUseRelationType());
                courseRelationMusicAlbum.setUpdateBy(userBy);
                courseRelationMusicAlbum.setUpdateTime(new Date());
                if (courseRelationMusicAlbum.getId() == null) {
                    courseRelationMusicAlbum.setCreateBy(userBy);
                    courseRelationMusicAlbum.setCreateTime(new Date());
                    courseRelationMusicAlbum.setDelFlog(2);
                    addCourseRelationMusicAlbums.add(courseRelationMusicAlbum);
                } else {
                    updateCourseRelationMusicAlbums.add(courseRelationMusicAlbum);
                }
                videoLessonGroupDetailDto.getCourseRelationMusicAlbumList().add(courseRelationMusicAlbum);
            }
        }
        // 删除关联数据
        courseRelationMusicAlbumService.lambdaUpdate()
                 .eq(CourseRelationMusicAlbum::getCourseGroupId, lessonGroupId)
                 .eq(CourseRelationMusicAlbum::getCourseType,CourseTypeEnum.VIDEO)
                 .notIn(CourseRelationMusicAlbum::getId,updateCourseRelationIdList)
                 .set(CourseRelationMusicAlbum::getDelFlog,0)
                 .set(CourseRelationMusicAlbum::getUpdateTime,new Date())
                 .update();

        // 保存更新的关联数据
        if (CollectionUtils.isNotEmpty(updateCourseRelationMusicAlbums)) {
            courseRelationMusicAlbumService.updateBatchById(updateCourseRelationMusicAlbums);
        }
        if (CollectionUtils.isNotEmpty(addCourseRelationMusicAlbums)) {
            courseRelationMusicAlbumService.saveOrUpdateBatch(addCourseRelationMusicAlbums);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateShelves(VideoLessonShelvesVo shelvesVo) {
        VideoLessonGroup videoLessonGroup = getById(shelvesVo.getId());
        if (videoLessonGroup.getDraftFlag() != null && videoLessonGroup.getDraftFlag().equals(YesOrNoEnum.YES)) {
            throw new BizException("草稿状态不能上架");
        }
        //改主表
        videoLessonGroupDao.updateShelves(shelvesVo);
        if(shelvesVo.getShelvesFlag() == 0 && ClientEnum.SYSTEM.equals(shelvesVo.getClientType())){
            //发推送
            sendOutSaleMessage(shelvesVo);
        }
    }

    private void sendOutSaleMessage(VideoLessonShelvesVo shelvesVo) {
        VideoLessonGroupVo detail = detail(shelvesVo.getId());
        // 发送课程下架通知
        try {
            SysUser user = sysUserFeignService.queryUserById(detail.getTeacherId());
            Map<Long, String> receivers = new HashMap<>();
            receivers.put(user.getId(), user.getPhone());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIDEO_COURSE_OUT_SALE_REASON,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode(),
                    detail.getLessonName(), shelvesVo.getShelvesReason());
        } catch (Exception e) {
            log.warn("视频课下架推送发送失败，{}", e.getMessage());
        }
    }

    /**
     * @Description: 删除视频课
     * @Author: cy
     * @Date: 2022/3/31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGroup(Long id) {
        videoLessonGroupDao.deleteById(id);
        videoLessonGroupDetailDao.deleteByGroupId(id);
    }

    /**
     * @Description: 新增视频课组&视频课
     * @Author: cy
     * @Date: 2022/4/1
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long add(VideoLessonVo lessonVo, SysUser sysUser) {
        VideoLessonGroup lessonGroup = lessonVo.getLessonGroup();
        List<VideoLessonGroupDetailDto> lessonList = lessonVo.getLessonList();
        if (CollectionUtils.isEmpty(lessonList)) {
            lessonList = new ArrayList<>();
        }
        lessonGroup.setLessonCount(lessonList.size());

        //校验声部
        Long subjectId = Long.valueOf(lessonGroup.getLessonSubject());
        List<Subject> subjectList = teacherDao.querySubject(sysUser.getId());
        List<Long> longList = subjectList.stream().map(Subject::getId).collect(Collectors.toList());
        if (!longList.contains(subjectId)) {
            throw new BizException("该声部无法选择");
        }
        
        Date date = new Date();

        // 设置默认置顶和排序
        if (lessonGroup.getTopFlag() == null) {
            lessonGroup.setTopFlag(0);
        }
        if (lessonGroup.getSortNumber() == null) {
            lessonGroup.setSortNumber(0);
        }
        lessonGroup.setAuditStatus(AuthStatusEnum.DOING);

        // 草稿状态不审核
        if (lessonGroup.getDraftFlag() == null) {
            lessonGroup.setDraftFlag(YesOrNoEnum.NO);
        }
        if (lessonGroup.getDraftFlag().equals(YesOrNoEnum.YES)) {
            lessonGroup.setAuditStatus(null);
            lessonGroup.setShelvesFlag(0);
        }

        //添加组
        lessonGroup.setTeacherId(sysUser.getId());
        lessonGroup.setAuditVersion(YesOrNoEnum.NO);
        if ("VIP".equals(lessonGroup.getPayType())) {
            lessonGroup.setLessonPrice(BigDecimal.ZERO);
        }
        videoLessonGroupDao.insert(lessonGroup);

        for (VideoLessonGroupDetail detail : lessonList) {
            detail.setVideoLessonGroupId(lessonGroup.getId());
            detail.setTeacherId(sysUser.getId());
        }

        //添加课程
        if (CollectionUtils.isNotEmpty(lessonList)) {
            videoLessonGroupDetailDao.insertVideoLesson(lessonList);
        }

        //刷新统计
        VideoLessonGroupUpVo groupUpVo = new VideoLessonGroupUpVo();
        groupUpVo.setId(lessonGroup.getId());
        videoLessonGroupDao.updateGroup(groupUpVo);

        //记录video_lesson_auth_record
        /*VideoLessonAuthRecord record = new VideoLessonAuthRecord();
        record.setVideoGroupId(lessonGroup.getId());
        record.setGroupId(lessonGroup.getId());
        record.setAuditStatus(AuthStatusEnum.DOING.getCode());
        record.setAuthType(AuthTypeEnum.ADD);
        recordDao.insert(record);*/


        // 设置关联曲目
        courseMusicAlbumRelation(lessonList, lessonGroup.getId(), lessonVo.getUserBy());

        if (YesOrNoEnum.NO.equals(lessonGroup.getDraftFlag())) {
            VideoLessonGroupLog videoLessonGroupLog = new VideoLessonGroupLog();

            try {
                org.springframework.beans.BeanUtils.copyProperties(lessonGroup, videoLessonGroupLog);
            } catch (Exception e) {
                throw new BizException("属性复制失败");
            }
            videoLessonGroupLog.setId(null);
            videoLessonGroupLog.setVideoLessonGroupId(lessonGroup.getId());
            videoLessonGroupLog.setCreateTime(date);
            videoLessonGroupLog.setUpdateTime(date);
            videoLessonGroupLog.setModifierId(sysUser.getId());
            videoLessonGroupLog.setVideoDetailJson(JsonUtil.toJSONString(lessonList));
            videoLessonGroupLog.setVersion(videoLessonGroupLogService.queryMaxVersion(lessonGroup.getId()) + 1);

            videoLessonGroupLogService.insert(videoLessonGroupLog);
        }
        return lessonGroup.getId();
    }

    /**
     * @Description: 学员详情-查询视频课列表
     * @Author: cy
     * @Date: 2022/4/2
     */
    @Override
    public IPage<VideoLessonStudentDetailVo> selectStudentPage(IPage<VideoLessonStudentDetailVo> page, VideoLessonSearch search) {
        return page.setRecords(baseMapper.selectStudentPage(page, search));
    }

    /**
     * @Description: 老师详情-查询视频课列表
     * @Author: cy
     * @Date: 2022/4/6
     */
    @Override
    public IPage<VideoLessonTeacherVo> selectTeacherPage(IPage<VideoLessonTeacherVo> page, VideoLessonSearch search) {
        List<VideoLessonTeacherVo> videoLessonTeacherVos = baseMapper.selectTeacherPage(page, search);
        for (VideoLessonTeacherVo videoLessonGroupVo : videoLessonTeacherVos) {
            if (new BigDecimal(videoLessonGroupVo.getLessonPrice()).compareTo(BigDecimal.ZERO) == 0) {
                videoLessonGroupVo.setCountStudent(videoLessonGroupVo.getCountStudent() + videoLessonGroupVo.getVirtualNumber());
            }
        }
        return page.setRecords(videoLessonTeacherVos);
    }

    /**
     * @Description: 老师详情-视频课详情-查询购买学员列表
     * @Author: cy
     * @Date: 2022/4/6
     */
    @Override
    public IPage<VideoLessonPurchaseVo> selectPurchaseStudent(IPage<VideoLessonPurchaseVo> page, VideoLessonSearch search) {
        return page.setRecords(baseMapper.selectPurchaseStudent(page, search));
    }

    /**
     * @Description: 根据组id查询视频课&视频课组
     * @Author: cy
     * @Date: 2022/4/7
     */
    @Override
    public VideoLessonStudentVo selectVideoLesson(Long groupId) {
        VideoLessonStudentVo lessonStudentVo = new VideoLessonStudentVo();

        VideoLessonGroupVo videoLessonGroupVo = detail(groupId);
        if (videoLessonGroupVo == null) return lessonStudentVo;

        Teacher teacher = teacherService.getById(videoLessonGroupVo.getTeacherId());
        if (teacher != null) {
            lessonStudentVo.setTeacherFlag(teacher.getTeacherFlag());
            lessonStudentVo.setDegreeFlag(teacher.getDegreeFlag());
        }

        lessonStudentVo.setLessonGroup(videoLessonGroupVo);
        VideoLessonSearch search = new VideoLessonSearch();
        search.setVideoLessonGroupId(groupId);
        lessonStudentVo.setDetailList(videoLessonGroupDetailDao.selectPage(null, search));

        // 课程关联曲目/专辑信息
        List<CourseRelationMusicAlbum> recordInfos = courseRelationMusicAlbumService.lambdaQuery()
                .eq(CourseRelationMusicAlbum::getCourseGroupId, groupId)
                .list();

        List<CourseRelationWrapper.MusicAlbumInfo> musicAlbumInfos;
        if (CollectionUtils.isNotEmpty(recordInfos)) {

            musicAlbumInfos = videoLessonGroupDetailService.getCourseRelationMusicAlbumInfos(recordInfos);

            // 填充课程关联曲目、专辑信息
            videoLessonGroupDetailService.updateCourseRelationMusicAlbumInfo(lessonStudentVo.getDetailList(), musicAlbumInfos);
        }
        //lessonStudentVo.setMusicAlbumInfos(musicAlbumInfos);

        return lessonStudentVo;
    }

    private VideoLessonGroupVo detail(Long groupId) {
        VideoLessonGroupSearch query = new VideoLessonGroupSearch();
        query.setGroupId(groupId);
        List<VideoLessonGroupVo> lessonGroup = videoLessonGroupDao.selectPage(null, query);
        if (CollectionUtils.isEmpty(lessonGroup)) {
            return null;
        }
        VideoLessonGroupVo videoLessonGroupVo = lessonGroup.get(0);
        if (videoLessonGroupVo.getLessonPrice().compareTo(BigDecimal.ZERO) == 0) {
            videoLessonGroupVo.setCountStudent(videoLessonGroupVo.getCountStudent() + videoLessonGroupVo.getVirtualNumber());
        }
        return videoLessonGroupVo;
    }

    /**
     * @Description: 修改视频课组&视频课
     * @Author: cy
     * @Date: 2022/4/7
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public VideoLessonVo update(VideoLessonVo lessonVo, SysUser sysUser) {
        VideoLessonGroup lessonGroup = lessonVo.getLessonGroup();
        List<VideoLessonGroupDetailDto> lessonList = lessonVo.getLessonList();
        if (CollectionUtils.isEmpty(lessonList)) {
            lessonList = new ArrayList<>();
        }
        lessonGroup.setLessonCount(lessonList.size());
        lessonGroup.setTeacherId(sysUser.getId());
        //判断是否有正在审核中
        QueryWrapper<VideoLessonAuthRecord> wrapper = new QueryWrapper<VideoLessonAuthRecord>();
        wrapper.eq("video_group_id_", lessonGroup.getId()).eq("audit_status_", AuthStatusEnum.DOING.getCode());
        
        List<VideoLessonAuthRecord> videoLessonAuthRecords = recordDao.selectList(wrapper);
        if(CollectionUtils.isNotEmpty(videoLessonAuthRecords)){
        	throw new BizException("正在审核中，无法修改");
        }

        //校验声部
        Long subjectId = Long.valueOf(lessonGroup.getLessonSubject());
        List<Subject> subjectList = teacherDao.querySubject(sysUser.getId());
        List<Long> longList = subjectList.stream().map(Subject::getId).collect(Collectors.toList());
        if (!longList.contains(subjectId)) {
            throw new BizException("该声部无法选择");
        }
        
        Date date = new Date();

        /*//创建新的评审记录
        VideoLessonAuthRecord authRecord = new VideoLessonAuthRecord();
        authRecord.setGroupId(lessonGroup.getId());
        authRecord.setAuditStatus(AuthStatusEnum.DOING.getCode());
        authRecord.setAuthType(AuthTypeEnum.MODIFY);
        authRecord.setVideoGroupId(lessonGroup.getId());
        //提交审核
        recordDao.insert(authRecord);*/

        // 提交第一页不删除课程
        if (lessonVo.getPage() == 2) {
            videoLessonGroupDetailDao.deleteByGroupId(lessonGroup.getId());
            if (lessonList != null && lessonList.size() > 0) {
                for (VideoLessonGroupDetail detail : lessonList) {
                    detail.setVideoLessonGroupId(lessonGroup.getId());
                    detail.setTeacherId(sysUser.getId());
                    detail.setUpdateBy(sysUser.getId());
                }
                // 添加课程
                videoLessonGroupDetailDao.insertVideoLesson(lessonList);
            }
        }


        // 草稿状态不审核
        if (lessonGroup.getDraftFlag() == null) {
            lessonGroup.setDraftFlag(YesOrNoEnum.NO);
        }

        //修改课程组记录
        lessonGroup.setAuditVersion(YesOrNoEnum.NO);
        lessonGroup.setAuditStatus(AuthStatusEnum.DOING);

        if (lessonGroup.getDraftFlag().equals(YesOrNoEnum.YES)) {
            lessonGroup.setAuditStatus(null);
            lessonGroup.setShelvesFlag(0);
            this.lambdaUpdate()
                    .eq(VideoLessonGroup::getId,lessonGroup.getId())
                    .set(VideoLessonGroup::getAuditStatus,null)
                    .update();
        }
        lessonGroup.setUpdateTime(date);
        videoLessonGroupDao.updateById(lessonGroup);

        // 设置关联曲目
        if (lessonVo.getPage() == 2) {
            courseMusicAlbumRelation(lessonList, lessonGroup.getId(), lessonVo.getUserBy());
        }

        if (lessonGroup.getDraftFlag().equals(YesOrNoEnum.NO)) {

            VideoLessonGroupLog videoLessonGroupLog = new VideoLessonGroupLog();

            try {
                org.springframework.beans.BeanUtils.copyProperties(lessonGroup, videoLessonGroupLog);
            } catch (Exception e) {
                throw new BizException("属性复制失败");
            }
            videoLessonGroupLog.setId(null);
            videoLessonGroupLog.setVideoLessonGroupId(lessonGroup.getId());
            videoLessonGroupLog.setCreateTime(date);
            videoLessonGroupLog.setUpdateTime(date);
            videoLessonGroupLog.setModifierId(sysUser.getId());
            videoLessonGroupLog.setVideoDetailJson(JsonUtil.toJSONString(lessonList));
            videoLessonGroupLog.setVersion(videoLessonGroupLogService.queryMaxVersion(lessonGroup.getId()) + 1);

            videoLessonGroupLogService.insert(videoLessonGroupLog);
        }

        //刷新统计
        VideoLessonGroupUpVo groupUpVo = new VideoLessonGroupUpVo();
        groupUpVo.setId(lessonGroup.getId());
        videoLessonGroupDao.updateGroup(groupUpVo);
        return lessonVo;
    }

    /**
     * @Description: 查询视频课组
     * @Author: cy
     * @Date: 2022/4/11
     */
    @Override
    public IPage<LessonGroupVo> selectLessonGroup(IPage<LessonGroupVo> page, VideoLessonGroupSearch query) {
        query.setAuditStatus(AuthStatusEnum.PASS.getCode());
        query.setShelvesFlag(1);
        List<LessonGroupVo> lessonGroupVos = baseMapper.selectLessonGroup(page, query);
        if (CollectionUtils.isNotEmpty(lessonGroupVos)) {
            //获取直播课关联的曲目数量
            List<Long> videoLessonGroupIds = lessonGroupVos.stream().map(LessonGroupVo::getId).collect(Collectors.toList());
            List<Mapper> musicNum = this.baseMapper.countMusicAlbum(videoLessonGroupIds);
            Map<Long,Long> map = musicNum.stream().collect(Collectors.toMap(e->Long.parseLong(e.getKey().toString()), e->Long.parseLong(e.getValue().toString())));
            for (LessonGroupVo videoLessonGroupVo : lessonGroupVos) {
                if (videoLessonGroupVo.getLessonPrice().compareTo(BigDecimal.ZERO) == 0) {
                    videoLessonGroupVo.setCountStudent(videoLessonGroupVo.getCountStudent() + videoLessonGroupVo.getVirtualNumber());
                }
                videoLessonGroupVo.setMusicNum(map.get(videoLessonGroupVo.getId()));
            }
        }
        return page.setRecords(lessonGroupVos);
    }

    /**
     * @Description: 查询所有视频课组
     * @Author: cy
     * @Date: 2022/4/20
     */
    @Override
    public IPage<VideoLessonAuthGroup> queryGroupList(IPage<VideoLessonAuthGroup> page, VideoGroupSearch query) {
        if(org.apache.commons.lang3.StringUtils.isNotBlank(query.getAuditStatus())){
        	
        	if(query.getAuditStatus().equals(AuthStatusEnum.DOING.getCode())){
            	query.setShelvesFlag(null);
        	}else if(query.getAuditStatus().equals(AuthStatusEnum.UNPASS.getCode())){
            	query.setShelvesFlag(null);
        	}else{
        		if(query.getAuditStatus().equals(AuthStatusEnum.OUT_SALE.getCode())){
                    query.setAuditStatus(AuthStatusEnum.PASS.getCode());
                    query.setShelvesFlag(0);
                }else if(query.getAuditStatus().equals(AuthStatusEnum.PASS.getCode())){
                    query.setShelvesFlag(1);
                }
        	}
        	
        }
        return page.setRecords(baseMapper.queryGroupList(page, query));
    }

    @Override
    public IPage<VideoLessonAuthGroup> queryGroupHistoryList(IPage<VideoLessonAuthGroup> page, VideoGroupSearch query) {
    	List<VideoLessonAuthGroup> list = baseMapper.queryGroupHistoryList(page, query);
    	for(VideoLessonAuthGroup g : list){
            List<VideoLessonGroupDetailDto> videoLessonGroupDetailDtoList = JsonUtil.parseArray(g.getVideoDetailJson(),
                                                                                                VideoLessonGroupDetailDto.class);
            g.setVideoList(videoLessonGroupDetailDtoList);

            if (CollectionUtils.isEmpty(videoLessonGroupDetailDtoList)) {
                continue;
            }

            List<CourseRelationMusicAlbum> recordInfos = videoLessonGroupDetailDtoList.stream()
                                  .filter(x -> CollectionUtils.isNotEmpty(x.getCourseRelationMusicAlbumList()))
                                  .flatMap(x -> x.getCourseRelationMusicAlbumList().stream()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(recordInfos)) {
                // 设置曲目关联信息
                setCourseRelationInfo(videoLessonGroupDetailDtoList, recordInfos);
            }
    	}
        return page.setRecords(list);
    }

    @Override
    public VideoLessonAuthGroup authGroupDetil(Long videoGroupId) {
        VideoLessonAuthGroup videoLessonAuthGroup = baseMapper.authGroupDetil(videoGroupId);
        
        List<VideoLessonGroupDetailDto> details = videoLessonGroupDetailDao.queryByVideoLessonGroupId(videoGroupId);
        videoLessonAuthGroup.setVideoList(details);

        // 查询当前的关联曲目
        List<CourseRelationMusicAlbum> list = courseRelationMusicAlbumService.lambdaQuery()
                             .eq(CourseRelationMusicAlbum::getCourseGroupId,  videoGroupId)
                             .ne(CourseRelationMusicAlbum::getDelFlog, 0) .list();
        // 设置曲目关联信息
        setCourseRelationInfo(details, list);

        //查询上一次的提交
        VideoLessonGroupLog lastDetil = videoLessonGroupLogService.queryByVideoLessonGroupId(videoGroupId, videoLessonAuthGroup.getVersion());
        videoLessonAuthGroup.setLastVideoLessonGroupLog(lastDetil);
        
        if(lastDetil != null){
            List<VideoLessonGroupDetailDto> videoLessonGroupDetailDtoList = JsonUtil.parseArray(
                    lastDetil.getVideoDetailJson(), VideoLessonGroupDetailDto.class);
            lastDetil.setVideoList(videoLessonGroupDetailDtoList);


            List<CourseRelationMusicAlbum> recordInfos = videoLessonGroupDetailDtoList.stream()
                            .filter(x -> CollectionUtils.isNotEmpty(x.getCourseRelationMusicAlbumList()))
                            .flatMap(x -> x.getCourseRelationMusicAlbumList().stream()).collect(Collectors.toList());
            // 设置曲目关联信息
            setCourseRelationInfo(videoLessonGroupDetailDtoList, recordInfos);
        }
        
        return videoLessonAuthGroup;
    }

    private void setCourseRelationInfo(List<VideoLessonGroupDetailDto> details, List<CourseRelationMusicAlbum> list) {
        if (CollectionUtils.isNotEmpty(list)) {

            List<CourseRelationWrapper.MusicAlbumInfo> musicAlbumInfos = videoLessonGroupDetailService.getCourseRelationMusicAlbumInfos(
                    list);

            // 填充课程关联曲目、专辑信息
            videoLessonGroupDetailService.updateCourseRelationMusicAlbumInfo(details, musicAlbumInfos);
        }
    }

    /**
     * @Description: 学生端-我的-我的课程-购买的视频课组
     * @Author: cy
     * @Date: 2022/4/20
     */
    @Override
    public IPage<LessonGroupVo> selectLessonGroupById(IPage<LessonGroupVo> page, VideoLessonGroupSearch query) {
        List<LessonGroupVo> lessonGroupVos = baseMapper.queryMyLessonGroup(page, query);
        if (CollectionUtils.isEmpty(lessonGroupVos)) {
            return page.setRecords(lessonGroupVos);
        }
        List<Long> idList = lessonGroupVos.stream().map(LessonGroupVo::getId).collect(Collectors.toList());
        Map<Long, Integer> idMap = videoLessonGroupDao.selectBatchIds(idList)
                                                        .stream()
                                                        .collect(Collectors.toMap(VideoLessonGroup::getId,
                                                                                  VideoLessonGroup::getVirtualNumber));
        //获取直播课关联的曲目数量
        List<Mapper> musicNum = this.baseMapper.countMusicAlbum(idList);
        Map<Long,Long> map = musicNum.stream().collect(Collectors.toMap(e->Long.parseLong(e.getKey().toString()), e->Long.parseLong(e.getValue().toString())));
        for (LessonGroupVo videoLessonGroupVo : lessonGroupVos) {
            if (videoLessonGroupVo.getLessonPrice().compareTo(BigDecimal.ZERO) == 0) {
                videoLessonGroupVo.setCountStudent(videoLessonGroupVo.getCountStudent() + idMap.get(videoLessonGroupVo.getId()));
            }
            videoLessonGroupVo.setMusicNum(map.get(videoLessonGroupVo.getId()));
        }
        return page.setRecords(lessonGroupVos);
    }

    /**
     * @Description: 首页-视频课统计
     * @Author: cy
     * @Date: 2022/5/7
     */
    public CountVideoGroupVo countVideoGroup() {
        CountVideoGroupVo countVideoGroup = baseMapper.countVideoGroup();
        countVideoGroup.setVideoLessonList(baseMapper.selectVideoLesson());
        return countVideoGroup;
    }

    @Override
    public ShareProfitVo shareVideoCourseProfit(SysUser sysUser, Long videoGroupId) {
        VideoLessonStudentVo videoLessonStudentVo = videoLessonGroupDetailService.selectVideoLesson(videoGroupId,0L);

        String teacherVideoGroupShareProfitUrl= sysConfigService.findConfigValue(SysConfigConstant.TEACHER_VIDEO_GROUP_SHARE_PROFIT_URL);

        ShareProfitVo result = new ShareProfitVo();
        result.setType("VIDEO");
        result.setTeacherId(sysUser.getId());
        result.setVideoGroup(videoLessonStudentVo);
        result.setUrl(MessageFormatter.arrayFormat(teacherVideoGroupShareProfitUrl, videoGroupId, sysUser.getId()));
        result.setName(sysUser.getUsername());
        result.setAvatar(sysUser.getAvatar());
        return result;

    }

    @Override
    public Boolean top(Long videoLessonGroupId) {
        VideoLessonGroup videoLessonGroup = getById(videoLessonGroupId);
        if (videoLessonGroup == null) {
            throw new BizException("未找到视频课信息");
        }
        VideoLessonGroup lessonGroup = new VideoLessonGroup();
        lessonGroup.setTopFlag(videoLessonGroup.getTopFlag() == 1?0:1);
        lessonGroup.setId(videoLessonGroupId);
        return this.updateById(lessonGroup);

    }

    @Override
    public IPage<CourseRelationWrapper.MusicAlbumInfo> queryRelationMusicAlbum(IPage<CourseRelationWrapper.MusicAlbumInfo> page, CourseRelationQueryInfo queryInfo) {
        IPage courseRelationMusicAlbumIPage = new Page<>(page.getCurrent(),page.getSize());
        courseRelationMusicAlbumIPage = courseRelationMusicAlbumService.lambdaQuery()
                           .eq(CourseRelationMusicAlbum::getCourseGroupId,queryInfo.getCourseGroupId())
                            .eq(CourseRelationMusicAlbum::getCourseType, queryInfo.getCourseType())
                            .ne(CourseRelationMusicAlbum::getDelFlog,0)
                           .orderByAsc(CourseRelationMusicAlbum::getCourseId)
                           .orderByDesc( CourseRelationMusicAlbum::getId)
                           .page(courseRelationMusicAlbumIPage);
        List<CourseRelationMusicAlbum> records = courseRelationMusicAlbumIPage.getRecords();
        List<CourseRelationWrapper.MusicAlbumInfo> courseRelationMusicAlbumInfos = videoLessonGroupDetailService.getCourseRelationMusicAlbumInfos(
                records);

        // 课程id集合
        List<Long> courseIdList = courseRelationMusicAlbumInfos.stream()
                                                          .map(CourseRelationWrapper.MusicAlbumInfo::getCourseId)
                                                          .collect(Collectors.toList());
        // 查询课程名
        List<VideoLessonGroupDetail> list = videoLessonGroupDetailService.lambdaQuery()
                                                                         .in(VideoLessonGroupDetail::getId,courseIdList)
                                                                         .list();

        Map<Long, String> collect = list.stream()
                                        .collect(Collectors.toMap(VideoLessonGroupDetail::getId,
                                                                  VideoLessonGroupDetail::getVideoTitle));
        for (CourseRelationWrapper.MusicAlbumInfo courseRelationMusicAlbumInfo : courseRelationMusicAlbumInfos) {
            courseRelationMusicAlbumInfo.setVideoTitle(collect.get(courseRelationMusicAlbumInfo.getCourseId()));
        }
        //查询标签
        List<Long> tagIdList =  courseRelationMusicAlbumInfos.stream()
                                                             .map(CourseRelationWrapper.MusicAlbumInfo::getTagIds)
                                                             .map(s -> Arrays.asList(s.split(",")))
                                                             .flatMap(Collection::stream)
                                                             .filter(StringUtils::isNotEmpty)
                                                             .map(Long::parseLong).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(tagIdList)) {
            List<MusicTag> musicTagList = musicTagService.lambdaQuery()
                                                         .in(MusicTag::getId, tagIdList)
                                                         .eq(MusicTag::getDelFlag, 0)
                                                         .list();
            Map<String, String> musicTagIdNameMap = musicTagList.stream()
                                                                .collect(Collectors.toMap(o -> o.getId().toString(),
                                                                                          MusicTag::getName));
            for (CourseRelationWrapper.MusicAlbumInfo courseRelationMusicAlbumInfo : courseRelationMusicAlbumInfos) {
                String tagIds = courseRelationMusicAlbumInfo.getTagIds();
                String tagName = Arrays.stream(tagIds.split(","))
                                       .map(musicTagIdNameMap::get)
                                       .collect(Collectors.joining(","));
                courseRelationMusicAlbumInfo.setTagName(tagName);
            }
        }

        courseRelationMusicAlbumIPage.setRecords(courseRelationMusicAlbumInfos);
        return courseRelationMusicAlbumIPage;

    }

    @Override
    public void setVirtualNumber() {

        List<VideoLessonGroup> videoLessonGroups = this.lambdaQuery()
                .select(VideoLessonGroup::getId,VideoLessonGroup::getVirtualNumber)
                                                .eq(VideoLessonGroup::getAuditStatus, AuthStatusEnum.PASS)
                                                .eq(VideoLessonGroup::getDraftFlag, 0)
                                                .eq(VideoLessonGroup::getLessonPrice, BigDecimal.ZERO)
                                                .eq(VideoLessonGroup::getAuditVersion, 0)
                                                .eq(VideoLessonGroup::getShelvesFlag, 1)
                                                .list();
        if (CollectionUtils.isEmpty(videoLessonGroups)) {
            return;
        }
        //给每个曲目设置增长值
        String value = sysConfigService.findConfigValue(SysConfigConstant.VIDEO_VIRTUAL_NUMBER);
        for (VideoLessonGroup videoLessonGroup : videoLessonGroups) {
            int i = (int) (Math.random() * Integer.parseInt(value));
            videoLessonGroup.setVirtualNumber(i +videoLessonGroup.getVirtualNumber());
        }

        // 保存虚拟人数
        this.updateBatchById(videoLessonGroups,100);


    }


}