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

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beust.jcommander.internal.Lists;
import com.dayaedu.cbs.common.enums.school.ECourseType;
import com.dayaedu.cbs.common.enums.school.EKnowledgeType;
import com.dayaedu.cbs.common.enums.school.EMaterialType;
import com.dayaedu.cbs.openfeign.client.CoursewareFeignService;
import com.dayaedu.cbs.openfeign.client.MusicFeignClientService;
import com.dayaedu.cbs.openfeign.wrapper.courseware.CbsCourseTypeWrapper;
import com.dayaedu.cbs.openfeign.wrapper.courseware.CbsLessonCoursewareDetailWrapper;
import com.dayaedu.cbs.openfeign.wrapper.courseware.CbsLessonCoursewareWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.SourceTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.SubjectTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.TenantAlbumMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantAlbumMusicMapper;
import com.yonge.cooleshow.biz.dal.mapper.UserTenantAlbumRecordMapper;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.wrapper.LessonCoursewareDetailWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.LessonCoursewareWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumMusicWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumWrapper;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.toolset.base.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * 机构专辑曲目
 * 2023-07-21 17:32:49
 */
@Slf4j
@Service
public class TenantAlbumMusicServiceImpl extends ServiceImpl<TenantAlbumMusicMapper, TenantAlbumMusic> implements TenantAlbumMusicService {


    @Autowired
    private UserTenantAlbumRecordService userTenantAlbumRecordService;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private MusicTagService musicTagService;

    @Autowired
    private MusicFeignClientService musicFeignClientService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private TenantAlbumMusicMapper tenantAlbumMusicMapper;

    @Autowired
    private TenantAlbumMusicService tenantAlbumMusicService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MusicFavoriteService musicFavoriteService;

    @Autowired
    private TenantAlbumCategoryDetailService tenantAlbumCategoryDetailService;

    @Autowired
    private CoursewareFeignService coursewareFeignService;

    @Autowired
    private TenantAlbumMapper tenantAlbumMapper;

    @Value("${openfeign-client.app-id:1745637981387108354}")
    public Long applicationId;

    /**
     * 查询详情
     * @param id 详情ID
     * @return TenantAlbumMusic
     */
    @Override
    public TenantAlbumMusic detail(Long id) {
        
        return baseMapper.selectById(id);
    }
    
    /**
     * 分页查询
     * @param page IPage<TenantAlbumMusic>
     * @param query TenantAlbumMusicWrapper.TenantAlbumMusicQuery
     * @return IPage<TenantAlbumMusic>
     */
    @Override
    public IPage<TenantAlbumMusicWrapper.StudentTenantAlbumMusic> selectPage(IPage<TenantAlbumMusicWrapper.StudentTenantAlbumMusic> page,
                                                                             TenantAlbumMusicWrapper.StudentTenantAlbumMusicQuery query) {
        List<TenantAlbumMusicWrapper.StudentTenantAlbumMusic> musicSheets = new ArrayList<>();
        if (query.getSubjectType() != SubjectTypeEnum.COURSEWARE) {

            musicSheets = tenantAlbumMusicMapper.selectPage(page, query);
            if (CollectionUtils.isEmpty(musicSheets)) {
                return page.setRecords(musicSheets);
            }
            CbsMusicSheetWrapper.MusicSheetApplicationQuery cbsQuery = musicSheetService.getMusicSheetApplicationQuery(SourceTypeEnum.TENANT);
            List<Long> cbsMusicSheetIds = musicSheets.stream().map(e -> e.getCbsMusicSheetId()).collect(Collectors.toList());
            cbsQuery.setMusicSheetIds(cbsMusicSheetIds);
            cbsQuery.setRows(cbsMusicSheetIds.size());
            List<CbsMusicSheetWrapper.MusicSheetApplication> rows = musicSheetService.queryCbsMusicSheetApplication(cbsQuery);
            if (CollectionUtils.isEmpty(rows)) {
                throw new BizException("查询内容平台曲目失败");
            }
            Map<Long,CbsMusicSheetWrapper.MusicSheetApplication> recordMap = rows.stream().collect(Collectors.toMap(CbsMusicSheetWrapper.MusicSheetApplication::getId, o -> o));

            // 设置上传人
            List<Long> userIds = musicSheets.stream()
                .map(TenantAlbumMusicWrapper.StudentTenantAlbumMusic::getUserId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
            Map<Long, SysUser> userMap = sysUserService.getMapByIds(userIds);

            // 设置是否收藏
            List<Long> musicSheetIds = musicSheets.stream()
                .map(TenantAlbumMusicWrapper.StudentTenantAlbumMusic::getId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
            List<Long> favoriteIds = new ArrayList<>();
            if (query.getUserId() != null && query.getClientType() != null) {
                List<MusicFavorite> favoriteList = musicFavoriteService.lambdaQuery()
                    .in(MusicFavorite::getMusicSheetId, musicSheetIds)
                    .eq(MusicFavorite::getUserId, query.getUserId())
                    .eq(MusicFavorite::getClientType, query.getClientType().equals(ClientEnum.TENANT_STUDENT) ? ClientEnum.STUDENT : query.getClientType())
                    .eq(MusicFavorite::getProviderType,"TENANT")
                    .list();
                favoriteIds = favoriteList.stream().map(MusicFavorite::getMusicSheetId).distinct().collect(Collectors.toList());
            }

            for (TenantAlbumMusicWrapper.StudentTenantAlbumMusic m : musicSheets) {
                CbsMusicSheetWrapper.MusicSheetApplication sheetApplication = recordMap.get(m.getCbsMusicSheetId());
                if (sheetApplication != null) {
                    m.setMusicSubjectName(sheetApplication.getSubjectNames());
                    m.setTitleImg(sheetApplication.getMusicCover());
                    m.setXmlFileUrl(sheetApplication.getXmlFileUrl());
                    m.setMusicImg(sheetApplication.getMusicImg());
                    m.setFirstTone(sheetApplication.getMusicFirstImg());
                    m.setFixedTone(sheetApplication.getMusicJianImg());
                    m.setIsMixBeat(sheetApplication.getIsMixBeat());
                    m.setMusicPdfUrl(sheetApplication.getMusicPdfUrl());
                    m.setFirstPdfUrl(sheetApplication.getFirstPdfUrl());
                    m.setJianPdfUrl(sheetApplication.getJianPdfUrl());

                    // 设置曲目原音
                    List<CbsMusicSheetWrapper.MusicSheetSound> soundList = sheetApplication.getMusicSheetSoundList();
                    if (CollectionUtils.isNotEmpty(soundList)) {
                        List<MusicSheetAccompaniment> background = new ArrayList<>();
                        for (CbsMusicSheetWrapper.MusicSheetSound sound : soundList) {
                            MusicSheetAccompaniment accompaniment = new MusicSheetAccompaniment();
                            accompaniment.setMusicSheetId(m.getId());
                            accompaniment.setAudioFileUrl(sound.getAudioFileUrl());
                            accompaniment.setSortNumber(sound.getSortNumber());
                            accompaniment.setTrack(sound.getTrack());
                            accompaniment.setMusicalInstrumentId(sound.getMusicalInstrumentId());
                            accompaniment.setMusicPdfUrl(sound.getMusicPdfUrl());
                            accompaniment.setFirstPdfUrl(sound.getFirstPdfUrl());
                            accompaniment.setJianPdfUrl(sound.getJianPdfUrl());
                            background.add(accompaniment);
                        }
                        m.setBackground(background);
                    }
                }
                SysUser sysUser = userMap.get(m.getUserId());
                if (sysUser != null) {
                    m.setUserName(sysUser.getUsername());
                }
                if (CollectionUtils.isNotEmpty(favoriteIds)) {
                    m.setFavorite(favoriteIds.contains(m.getId()));
                }
            }
        } else {
            // 查询专辑课件
            List<TenantAlbumMusic> list = tenantAlbumMusicService.lambdaQuery()
                .eq(TenantAlbumMusic::getTenantAlbumId, query.getAlbumId())
                .eq(TenantAlbumMusic::getSubjectType, SubjectTypeEnum.COURSEWARE)
                .eq(TenantAlbumMusic::getDelFlag, false)
                .orderByAsc(TenantAlbumMusic::getSortNumber)
                .list();
            if (CollectionUtils.isEmpty(list)) {
                return page.setRecords(musicSheets);
            }
            List<Long> coursewareIds = list.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());

            try {
                List<ECourseType> courseTypeList = courseTypeBySubject(query.getSubjectId());

                PageInfo<CbsLessonCoursewareWrapper.LessonCourseware> lessonCoursewarePageInfo = coursewareFeignService.lessonCoursewarePage(CbsLessonCoursewareWrapper.LessonCoursewareQuery.builder()
                    .page(query.getPage()).rows(query.getRows()).lessonCoursewareIds(coursewareIds).courseTypes(courseTypeList).keyword(query.getKeyword()).enableFlag(true)
                    .courseTypeCode(StringUtils.isNotBlank(query.getCourseTypeCode())?ECourseType.valueOf(query.getCourseTypeCode()):null).build()
                ).feignData();
                List<CbsLessonCoursewareWrapper.LessonCourseware> rows = lessonCoursewarePageInfo.getRows();
                if (CollectionUtils.isEmpty(rows)) {
                    return page.setRecords(musicSheets);
                }
                // 转map
                Map<Long, CbsLessonCoursewareWrapper.LessonCourseware> coursewareMap = rows.stream().collect(Collectors.toMap(CbsLessonCoursewareWrapper.LessonCourseware::getId, o -> o,(o1,o2)->o1));

                for (Long coursewareId : coursewareIds) {
                    CbsLessonCoursewareWrapper.LessonCourseware row = coursewareMap.get(coursewareId);
                    if (row == null) {
                        continue;
                    }
                    TenantAlbumMusicWrapper.StudentTenantAlbumMusic studentTenantAlbumMusic = new TenantAlbumMusicWrapper.StudentTenantAlbumMusic();
                    studentTenantAlbumMusic.setId(row.getId());
                    studentTenantAlbumMusic.setTenantAlbumId(query.getAlbumId());
                    studentTenantAlbumMusic.setMusicSheetName(row.getName());
                    studentTenantAlbumMusic.setTitleImg(row.getCoverImg());
                    studentTenantAlbumMusic.setMusicSubject(row.getCourseTypeCode());
                    studentTenantAlbumMusic.setMusicSubjectName(ECourseType.valueOf(row.getCourseTypeCode()).getName());
                    musicSheets.add(studentTenantAlbumMusic.courseNum(row.getCourseNum()).unitTestNum(row.getUnitTestNum()));

                }

                page.setRecords(musicSheets);
                page.setTotal(lessonCoursewarePageInfo.getTotal());
                return page;
            }catch (Exception e) {
                log.error("查询课件失败", e);
                throw new BizException("内容平台查询课件异常");
            }

        }
        return page.setRecords(musicSheets);
    }

    /**
     * 添加
     * @param tenantAlbumMusic TenantAlbumMusicWrapper.TenantAlbumMusic
     * @return Boolean
     */
    @Override
    public Boolean add(TenantAlbumMusicWrapper.TenantAlbumMusic tenantAlbumMusic) {

        return this.save(JSON.parseObject(tenantAlbumMusic.jsonString(), TenantAlbumMusic.class));
    }

    /**
     * 更新
     * @param tenantAlbumMusic TenantAlbumMusicWrapper.TenantAlbumMusic
     * @return Boolean
     */
    @Override
    public Boolean update(TenantAlbumMusicWrapper.TenantAlbumMusic tenantAlbumMusic){

        return this.updateById(JSON.parseObject(tenantAlbumMusic.jsonString(), TenantAlbumMusic.class));       
    }


    /**
     * 获取机构专辑曲目查询条件
     */
    @Override
    public TenantAlbumMusicWrapper.TenantAlbumMusicSelectData getTenantAlbumMusicQuery(TenantAlbumMusicWrapper.TenantAlbumMusicSelect query) {

        TenantAlbumMusicWrapper.TenantAlbumMusicSelectData data = new TenantAlbumMusicWrapper.TenantAlbumMusicSelectData();

        // 获取学生的专辑
//        List<Long> albumIds = userTenantAlbumRecordService.getUseAlbumIdsByUserId(query.getUserId(), ClientEnum.STUDENT);
//        if (CollectionUtils.isEmpty(albumIds)) {
//            return data;
//        }

        // 专辑曲目关联数据
        List<TenantAlbumMusic> list = tenantAlbumMusicMapper.getList(query, Lists.newArrayList(query.getTenantAlbumId()));
        if (CollectionUtils.isEmpty(list)) {
            return data;
        }

        List<Long> coursewareIds = list.stream().filter(o -> o.getSubjectType() == SubjectTypeEnum.COURSEWARE)
            .map(TenantAlbumMusic::getMusicSheetId).distinct().collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(coursewareIds) ) {
            CbsLessonCoursewareWrapper.LambdaQuery lambdaQuery = CbsLessonCoursewareWrapper.LambdaQuery.builder().ids(coursewareIds)
                .delFlag(false).enableFlag(true).build();
            List<CbsLessonCoursewareWrapper.Entity> entities = coursewareFeignService.lessonCoursewareLambdaQuery(lambdaQuery).feignData();

            List<ECourseType> courseTypeList = courseTypeBySubject(query.getSubjectId());
            List<String> courseTypes = entities.stream()
                .map(CbsLessonCoursewareWrapper.Entity::getCourseTypeCode)
                .filter(courseTypeCode -> courseTypeList.contains(ECourseType.valueOf(courseTypeCode)))
                .distinct().collect(Collectors.toList());
            data.setCourseTypeList(courseTypes);
        }

        List<Long> musicSheetIds = list.stream().filter(o -> o.getSubjectType() != SubjectTypeEnum.COURSEWARE)
            .map(TenantAlbumMusic::getMusicSheetId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(musicSheetIds)) {
            return data;
        }

        Collection<MusicSheet> musicSheets = musicSheetService.listByIds(musicSheetIds);
        if (CollectionUtils.isEmpty(musicSheets)) {
            return data;
        }

        // 类型
        List<Long> typeIds =list.stream().map(TenantAlbumMusic::getType).distinct().filter(StringUtils::isNotBlank)
                .filter(NumberUtil::isNumber).map(Long::valueOf).collect(Collectors.toList());
        if (!typeIds.isEmpty()) {
            List<TenantAlbumCategoryDetail> typeList = tenantAlbumCategoryDetailService.lambdaQuery()
                    .in(TenantAlbumCategoryDetail::getId, typeIds).list();
            List<String> typeNameList = typeList.stream()
                    .map(TenantAlbumCategoryDetail::getValue).collect(Collectors.toList());
            data.setTypes(typeNameList);
            data.setTypeList(typeList);
        } else {
            data.setTypes(new ArrayList<>());
        }
        // 级别
        List<Long> levelIds =list.stream().map(TenantAlbumMusic::getLevel).distinct().filter(StringUtils::isNotBlank)
                .filter(NumberUtil::isNumber).map(Long::valueOf).collect(Collectors.toList());
        if (!levelIds.isEmpty()) {
            List<TenantAlbumCategoryDetail> levelList = tenantAlbumCategoryDetailService.lambdaQuery()
                    .in(TenantAlbumCategoryDetail::getId, levelIds).list();
            List<String> levelNameList = levelList.stream()
                    .map(TenantAlbumCategoryDetail::getValue).collect(Collectors.toList());
            data.setLevels(levelNameList);
            data.setLevelList(levelList);
        } else {
            data.setLevels(new ArrayList<>());
        }

        // 声部
        String subjectIds = musicSheets.stream()
                .map(MusicSheet::getMusicSubject)
                .filter(StringUtils::isNotBlank).distinct().collect(Collectors.joining(","));
        if (StringUtils.isNotEmpty(subjectIds)) {
            List<Subject> subjects = subjectService.findBySubjectByIdList(subjectIds);
            data.setSubjects(subjects);
        }

//        // 标签
//        List<Long> musicTagIds = musicSheets.stream().flatMap(o -> {
//            if (StringUtils.isNotBlank(o.getMusicTag())) {
//                return Arrays.stream(o.getMusicTag().split(","));
//            }
//            return Stream.empty();
//
//        }).filter(StringUtils::isNotBlank).distinct().map(Long::parseLong).collect(Collectors.toList());
//        if (!CollectionUtils.isEmpty(musicTagIds)) {
//
//            List<MusicTag> tagList = musicTagService.listByIds(musicTagIds).parallelStream().collect(Collectors.toList());
//            data.setTags(tagList);
//        }
        data.setSubjects(new ArrayList<>());

        return data;

    }

    private List<ECourseType> courseTypeBySubject(Long subjectId) {
        List<ECourseType> courseTypeList = new ArrayList<>();

        // 有声部， 根据声部查询对应的课件类型
        List<CbsCourseTypeWrapper.CourseType> courseTypes = coursewareFeignService.courseTypeList().feignData();
        if (subjectId != null) {
            String configValue = sysConfigService.findConfigValue(SysConfigConstant.COURSE_SUBJECT_MAP);
            Map<String, String> map= new HashMap<>();
            if (StringUtils.isNotBlank(configValue)) {
                map = JSON.parseObject(configValue, Map.class);
            }
            Subject subject = subjectService.get(subjectId);
            for (CbsCourseTypeWrapper.CourseType courseType : courseTypes) {
                if (StringUtils.isNotBlank(courseType.getSubjectIds()) ) {
                    if (subject !=null && subject.getCbsSubjectId() !=null) {
                        subject.setCbsSubjectId(Long.parseLong(map.getOrDefault(subject.getCbsSubjectId().toString(),subject.getCbsSubjectId().toString())));
                        boolean contains = Arrays.asList(courseType.getSubjectIds().split(",")).contains(subject.getCbsSubjectId().toString());
                        if (contains) {
                            courseTypeList.add(ECourseType.valueOf(courseType.getTypeCode()));
                        }
                    }

                }  else {
                    courseTypeList.add(ECourseType.valueOf(courseType.getTypeCode()));
                }
            }
        }else {
            return courseTypes.stream().map(CbsCourseTypeWrapper.CourseType::getTypeCode).distinct()
                .map(ECourseType::valueOf).collect(Collectors.toList());
        }
        return courseTypeList;
    }

    @Override
    public List<Long> getTenantAlbumMusicIdsByIds(List<Long> tenantAlbumIds, List<SubjectTypeEnum> subjectTypes) {

        if (CollectionUtils.isEmpty(tenantAlbumIds)) {
            return Collections.emptyList();
        }

        return baseMapper.getTenantAlbumMusicIdsByIds(tenantAlbumIds, subjectTypes);
    }

    @Override
    public List<Long> getMusicIdsByIds(List<Long> tenantAlbumIds) {

        return getTenantAlbumMusicIdsByIds(tenantAlbumIds,Arrays.asList(SubjectTypeEnum.MUSIC, SubjectTypeEnum.ENSEMBLE,SubjectTypeEnum.SUBJECT));
    }


    /**
     * 获取机构专辑曲目ID集合
     *
     * @param tenantId 机构ID
     */
    @Override
    public List<Long> getMusicIdsByTenantIds(Long tenantId) {
        return baseMapper.selectMusicIdsByTenantIds(tenantId);
    }

    @Override
    public LessonCoursewareWrapper.LessonCourseware getLessonCoursewareDetail(LessonCoursewareWrapper.LessonCourseQuery query) {
        CbsLessonCoursewareWrapper.LessonCourseware lessonCourseware = coursewareFeignService.lessonCoursewareDetail(query.getLessonCoursewareId()).feignData();
        if (lessonCourseware == null) {
            throw new BizException("课件不存在");
        }

        LessonCoursewareWrapper.LessonCourseware lessonCoursewareDto = JSON.parseObject(JSON.toJSONString(lessonCourseware), LessonCoursewareWrapper.LessonCourseware.class);
        lessonCoursewareDto.setPlay(false);

        if (query.getClient() == ClientEnum.STUDENT) {
            // 判断学生有咩有购买
            if (query.getAlbumId() != null) {
                UserTenantAlbumRecord albumRecord = userTenantAlbumRecordService.getNewestByTenantAlbumId(query.getAlbumId(), query.getUserId(), query.getClient());
                if (albumRecord != null && albumRecord.getEndTime().after(new Date())) {
                    lessonCoursewareDto.setPlay(true);
                }
            } else {
                List<Long> useAlbumIdsByUserId = userTenantAlbumRecordService.getUseAlbumIdsByUserId(query.getUserId(), query.getClient());
                if (CollectionUtils.isNotEmpty(useAlbumIdsByUserId)) {
                    List<Long> list = tenantAlbumMusicService.getTenantAlbumMusicIdsByIds(useAlbumIdsByUserId, Collections.singletonList(SubjectTypeEnum.COURSEWARE));
                    if (list.contains(query.getLessonCoursewareId())) {
                        lessonCoursewareDto.setPlay(true);
                    }
                }
            }
        } else {
            lessonCoursewareDto.setPlay(true);
        }

        return lessonCoursewareDto;
    }

    @Override
    public LessonCoursewareDetailWrapper.LessonCoursewareDetail getLessonCourseDetail(String lessonCoursewareDetailId) {
        CbsLessonCoursewareDetailWrapper.LessonCoursewareDetail cbsLessonCoursewareDetail = coursewareFeignService.lessonCoursewareDetailDetail(Long.parseLong(lessonCoursewareDetailId)).feignData();
        if (cbsLessonCoursewareDetail == null) {
            throw new BizException("课件不存在");
        }
        LessonCoursewareDetailWrapper.LessonCoursewareDetail lessonCoursewareDetail = JSON.parseObject(JSON.toJSONString(cbsLessonCoursewareDetail), LessonCoursewareDetailWrapper.LessonCoursewareDetail.class);


        // 过滤调未应用到项目的去练习曲目
        List<LessonCoursewareDetailWrapper.KnowledgePointSmall> knowledgePointList = lessonCoursewareDetail.getKnowledgePointList();
        List<LessonCoursewareDetailWrapper.AddMaterialRef> addMaterialRefs = getMaterialRefList(knowledgePointList);
        List<LessonCoursewareDetailWrapper.MaterialSmall> musicMaterialSmalls = getMaterialSmalls(knowledgePointList);
        if (CollectionUtils.isNotEmpty(musicMaterialSmalls)) {
            List<Long> cbsMaterialMusicIds = musicMaterialSmalls.stream().map(LessonCoursewareDetailWrapper.MaterialSmall::getContent)
                .filter(StringUtils::isNotBlank).map(Long::parseLong).collect(Collectors.toList());
            Map<Long, Long> idMap = musicSheetService.lambdaQuery()
                .in(MusicSheet::getCbsMusicSheetId, cbsMaterialMusicIds)
                .eq(MusicSheet::getTenantDelFlag, false)
                .eq(MusicSheet::getTenantState, 1)
                .list()
                .stream()
                .collect(Collectors.toMap(MusicSheet::getCbsMusicSheetId, MusicSheet::getId,(o1,o2)->o1));

            // 过滤掉没有对应的曲目
            filterMusicMaterialList(knowledgePointList,new ArrayList<>(idMap.keySet()));
            for (LessonCoursewareDetailWrapper.MaterialSmall musicMaterialSmall : musicMaterialSmalls) {
                musicMaterialSmall.setContent(idMap.getOrDefault(Long.parseLong(musicMaterialSmall.getContent()),-1L).toString());
            }
        }
        List<Long> cbsMusicSheetIdList =
            addMaterialRefs.stream().filter(next -> EKnowledgeType.MUSIC.equals(next.getKnowledgeType()))
                .map(LessonCoursewareDetailWrapper.AddMaterialRef::getResourceId).distinct().collect(Collectors.toList());
        if (!org.springframework.util.CollectionUtils.isEmpty(cbsMusicSheetIdList)) {
            Map<Long, Long> idMap = musicSheetService.lambdaQuery()
                .in(MusicSheet::getCbsMusicSheetId, cbsMusicSheetIdList)
                .eq(MusicSheet::getTenantDelFlag, false)
                .eq(MusicSheet::getTenantState, 1)
                .list()
                .stream()
                .collect(Collectors.toMap(MusicSheet::getCbsMusicSheetId, MusicSheet::getId,(o1,o2)->o1));

            for (LessonCoursewareDetailWrapper.AddMaterialRef addMaterialRef : addMaterialRefs) {
                Long resourceId = addMaterialRef.getResourceId();
                if (idMap.containsKey(resourceId)) {
                    addMaterialRef.setResourceId(idMap.get(resourceId));
                    addMaterialRef.setResourceIdStr(idMap.getOrDefault(resourceId,-1L).toString());
                }
            }
            // 过滤掉没有对应的曲目
            filterMaterialRefList(knowledgePointList,new ArrayList<>(idMap.values()));
        }

        return lessonCoursewareDetail;
    }

    /**
     * 关联课程类型
     *
     * @param query
     */
    @Override
    public List<LessonCoursewareDetailWrapper.RefLevelDetailInfo> refLevel(LessonCoursewareDetailWrapper.RefLevelQuery query) {
        if (query.getTenantId() == null) {
            return new ArrayList<>();
        }
        // 查询机构可用专辑
        TenantAlbumWrapper.TenantAlbumQuery build = TenantAlbumWrapper.TenantAlbumQuery.builder()
            .status(true)
            .tenantId(query.getTenantId())
            .build();
        List<TenantAlbumWrapper.TenantAlbum> tenantAlbums = tenantAlbumMapper.selectPage(new Page<>(1, -1), build);
        if (CollectionUtils.isEmpty(tenantAlbums)) {
            return new ArrayList<>();
        }
        List<String> tenantAlbumIds = tenantAlbums.stream().map(TenantAlbumWrapper.TenantAlbum::getId).collect(Collectors.toList());

        List<LessonCoursewareDetailWrapper.RefLevelDetailInfo> result = new ArrayList<>();
        // 查询出机构下的所有可用教材
        List<TenantAlbumMusic> detail = tenantAlbumMusicService.lambdaQuery()
            .eq(TenantAlbumMusic::getTenantId, query.getTenantId())
            .in(TenantAlbumMusic::getTenantAlbumId, tenantAlbumIds)
            .eq(TenantAlbumMusic::getSubjectType, SubjectTypeEnum.COURSEWARE)
            .eq(TenantAlbumMusic::getDelFlag, false)
            .list();
        if (CollectionUtils.isEmpty(detail)) {
            return new ArrayList<>();
        }


        // 根据机构，查询机构可以查看的所有课件，然后根据课件查询对应的课程类型
        List<CbsLessonCoursewareDetailWrapper.Entity> entities = coursewareFeignService.lessonCoursewareDetailLambdaQuery(CbsLessonCoursewareDetailWrapper.LambdaQuery.builder()
            .id(query.getLessonCoursewareDetailId())
            .build()).feignData();
        if (CollectionUtils.isEmpty(entities)) {
            throw new BizException("课件不存在");
        }
        CbsLessonCoursewareDetailWrapper.Entity lessonCoursewareDetail = entities.get(0);

        List<CbsLessonCoursewareWrapper.Entity> lessonCoursewareEntityList = coursewareFeignService.lessonCoursewareLambdaQuery(CbsLessonCoursewareWrapper.LambdaQuery.builder()
            .id(lessonCoursewareDetail.getLessonCoursewareId())
            .build()).feignData();
        if (CollectionUtils.isEmpty(lessonCoursewareEntityList)) {
            throw new BizException("课件不存在");
        }
        CbsLessonCoursewareWrapper.Entity lessonCourseware = lessonCoursewareEntityList.get(0);

        CbsLessonCoursewareWrapper.LessonCoursewareQuery cbsQuery = new CbsLessonCoursewareWrapper.LessonCoursewareQuery();
        cbsQuery.setEnableFlag(true);
//        cbsQuery.setOrchestraType(lessonCourseware.getOrchestraType());
        cbsQuery.setLessonCoursewareIds(detail.stream().map(TenantAlbumMusic::getMusicSheetId).distinct().collect(Collectors.toList()));
        cbsQuery.setPage(1);
        cbsQuery.setRows(9999);
        cbsQuery.setLevel(lessonCourseware.getLevel());

        List<CbsLessonCoursewareWrapper.LessonCourseware> lessonCoursewareList = coursewareFeignService.lessonCoursewarePage(cbsQuery).feignData().getRows();

        // 转map
        Map<Long, CbsLessonCoursewareWrapper.LessonCourseware> lessonCoursewareMap = lessonCoursewareList.stream().collect(Collectors.toMap(CbsLessonCoursewareWrapper.LessonCourseware::getId, o -> o));
        List<Long> lessonCoursewareIds = lessonCoursewareList.stream().map(CbsLessonCoursewareWrapper.LessonCourseware::getId).collect(Collectors.toList());

        // 查询可用的课件详情信息
        if (lessonCoursewareDetail.getLevel() != null) {
            List<CbsLessonCoursewareDetailWrapper.Entity> lessonCoursewareDetails = coursewareFeignService
                .lessonCoursewareDetailLambdaQuery(CbsLessonCoursewareDetailWrapper.LambdaQuery.builder()
                    .level(lessonCoursewareDetail.getLevel())
                    .lessonCoursewareIds(lessonCoursewareIds)
                    .build()).feignData();
            if (org.springframework.util.CollectionUtils.isEmpty(lessonCoursewareDetails)) {
                return new ArrayList<>();
            }
            for (CbsLessonCoursewareDetailWrapper.Entity coursewareDetail : lessonCoursewareDetails) {
                LessonCoursewareDetailWrapper.RefLevelDetailInfo refLevelDetailInfo = new LessonCoursewareDetailWrapper.RefLevelDetailInfo();
                refLevelDetailInfo.setId(coursewareDetail.getId().toString());
                refLevelDetailInfo.setLessonCoursewareId(coursewareDetail.getLessonCoursewareId().toString());
                CbsLessonCoursewareWrapper.LessonCourseware lessonCourseware1 = lessonCoursewareMap.get(coursewareDetail.getLessonCoursewareId());
                if (lessonCourseware1 == null) {
                    continue;
                }
                refLevelDetailInfo.setCoverImg(lessonCourseware1.getCoverImg());
                refLevelDetailInfo.setCourseTypeCode(lessonCourseware1.getCourseTypeCode());
                refLevelDetailInfo.setLockFlag(false);
                refLevelDetailInfo.setLessonCoursewareName(lessonCourseware1.getName());
                refLevelDetailInfo.setUseFlag(coursewareDetail.getId().equals(query.getLessonCoursewareDetailId()));
                result.add(refLevelDetailInfo);
            }
        } else {
            LessonCoursewareDetailWrapper.RefLevelDetailInfo refLevelDetailInfo = new LessonCoursewareDetailWrapper.RefLevelDetailInfo();
            refLevelDetailInfo.setId(lessonCoursewareDetail.getId().toString());
            refLevelDetailInfo.setLessonCoursewareId(lessonCoursewareDetail.getLessonCoursewareId().toString());
            refLevelDetailInfo.setCoverImg(lessonCourseware.getCoverImg());
            refLevelDetailInfo.setCourseTypeCode(lessonCourseware.getCourseTypeCode());
            refLevelDetailInfo.setLockFlag(false);
            refLevelDetailInfo.setLessonCoursewareName(lessonCourseware.getName());
            refLevelDetailInfo.setUseFlag(true);
            result.add(refLevelDetailInfo);
        }
        return result;

    }

    private void filterMusicMaterialList(List<LessonCoursewareDetailWrapper.KnowledgePointSmall> knowledgePointList, List<Long> cbsMusicSheetIds) {
        if (CollectionUtils.isNotEmpty(knowledgePointList)) {
            for (LessonCoursewareDetailWrapper.KnowledgePointSmall knowledgePointSmall : knowledgePointList) {

                if (CollectionUtils.isNotEmpty(knowledgePointSmall.getChildren())) {
                    filterMusicMaterialList(knowledgePointSmall.getChildren(),cbsMusicSheetIds);
                }
                List<LessonCoursewareDetailWrapper.MaterialSmall> materialList = knowledgePointSmall.getMaterialList();
                if (CollectionUtils.isNotEmpty(materialList)) {
                    materialList.removeIf(next -> (EMaterialType.SONG.equals(next.getType()) && !cbsMusicSheetIds.contains(Long.parseLong(next.getContent()))));
                    knowledgePointSmall.setMaterialList(materialList);
                }
            }
        }
    }

    private List<LessonCoursewareDetailWrapper.MaterialSmall> getMaterialSmalls(List<LessonCoursewareDetailWrapper.KnowledgePointSmall> knowledgePointList) {
        List<LessonCoursewareDetailWrapper.MaterialSmall> materialRefList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(knowledgePointList)) {
            for (LessonCoursewareDetailWrapper.KnowledgePointSmall knowledgePointSmall : knowledgePointList) {

                if (CollectionUtils.isNotEmpty(knowledgePointSmall.getChildren())) {
                    materialRefList.addAll(getMaterialSmalls(knowledgePointSmall.getChildren()));
                }
                List<LessonCoursewareDetailWrapper.MaterialSmall> materialList = knowledgePointSmall.getMaterialList();
                if (CollectionUtils.isNotEmpty(materialList)) {
                    for (LessonCoursewareDetailWrapper.MaterialSmall materialSmall : materialList) {
                        if (materialSmall.getType() == EMaterialType.SONG) {
                            materialRefList.add(materialSmall);
                        }
                    }
                }
            }
        }
        return materialRefList;
    }

    private void filterMaterialRefList(List<LessonCoursewareDetailWrapper.KnowledgePointSmall> knowledgePointList,List<Long> cbsMusicSheetIds) {
        if (CollectionUtils.isNotEmpty(knowledgePointList)) {
            for (LessonCoursewareDetailWrapper.KnowledgePointSmall knowledgePointSmall : knowledgePointList) {

                if (CollectionUtils.isNotEmpty(knowledgePointSmall.getChildren())) {
                    filterMaterialRefList(knowledgePointSmall.getChildren(),cbsMusicSheetIds);
                }
                List<LessonCoursewareDetailWrapper.MaterialSmall> materialList = knowledgePointSmall.getMaterialList();
                if (CollectionUtils.isNotEmpty(materialList)) {
                    for (LessonCoursewareDetailWrapper.MaterialSmall materialSmall : materialList) {
                        if (CollectionUtils.isNotEmpty(materialSmall.getMaterialRefs())) {
                            List<LessonCoursewareDetailWrapper.AddMaterialRef> refList = materialSmall.getMaterialRefs().stream()
                                .filter(next -> !(EKnowledgeType.MUSIC.equals(next.getKnowledgeType()) && !cbsMusicSheetIds.contains(next.getResourceId())))
                                .collect(Collectors.toList());
                            materialSmall.setMaterialRefs(refList);
                        }
                    }
                }
            }
        }
    }

    private List<LessonCoursewareDetailWrapper.AddMaterialRef> getMaterialRefList(List<LessonCoursewareDetailWrapper.KnowledgePointSmall> knowledgePointList) {
        List<LessonCoursewareDetailWrapper.AddMaterialRef> materialRefList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(knowledgePointList)) {
            for (LessonCoursewareDetailWrapper.KnowledgePointSmall knowledgePointSmall : knowledgePointList) {

                if (CollectionUtils.isNotEmpty(knowledgePointSmall.getChildren())) {
                    materialRefList.addAll(getMaterialRefList(knowledgePointSmall.getChildren()));
                }
                List<LessonCoursewareDetailWrapper.MaterialSmall> materialList = knowledgePointSmall.getMaterialList();
                if (CollectionUtils.isNotEmpty(materialList)) {
                    for (LessonCoursewareDetailWrapper.MaterialSmall materialSmall : materialList) {
                        if (CollectionUtils.isNotEmpty(materialSmall.getMaterialRefs())) {
                            materialRefList.addAll(materialSmall.getMaterialRefs());
                        }
                    }
                }
            }
        }
        return materialRefList;
    }
}