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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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.EClientType;
import com.dayaedu.cbs.common.enums.music.*;
import com.dayaedu.cbs.common.enums.school.EMusicSheetType;
import com.dayaedu.cbs.openfeign.client.MusicFeignClientService;
import com.dayaedu.cbs.openfeign.properties.OpenFeignClientConfigProperties;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetApplicationExtendClientWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.google.common.collect.Maps;
import com.microsvc.toolkit.common.response.paging.PageInfo;
import com.microsvc.toolkit.common.response.paging.QueryInfo;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.MusicAlbumDao;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetDao;
import com.yonge.cooleshow.biz.dal.dto.MusicImgDto;
import com.yonge.cooleshow.biz.dal.dto.MusicSheetPayDto;
import com.yonge.cooleshow.biz.dal.dto.ReasonDto;
import com.yonge.cooleshow.biz.dal.dto.UserAccountRecordDto;
import com.yonge.cooleshow.biz.dal.dto.req.OrderReq;
import com.yonge.cooleshow.biz.dal.dto.search.*;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.*;
import com.yonge.cooleshow.biz.dal.enums.album.PurchaseRecordTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.TenantAlbumMusicMapper;
import com.yonge.cooleshow.biz.dal.mapper.TenantGroupAlbumMapper;
import com.yonge.cooleshow.biz.dal.mapper.UserTenantAlbumRecordMapper;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.cooleshow.biz.dal.vo.res.OrderCreateRes;
import com.yonge.cooleshow.biz.dal.wrapper.*;
import com.yonge.cooleshow.biz.dal.wrapper.music.MusicCompareWrapper;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.ActivityShareEnum;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
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.base.util.StringUtil;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * MusicSheetService服务实现类
 *
 * @author yzp
 * @version v1.0
 * @date 2022-03-26 00:01:37
 **/
@Service
public class MusicSheetServiceImpl extends ServiceImpl<MusicSheetDao, MusicSheet> implements MusicSheetService {

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

    @Resource
    private MusicSheetDao musicSheetDao;
    @Resource
    private MusicFavoriteService musicFavoriteService;
    @Resource
    private ActivityPlanService  activityPlanService;
    @Resource
    private SysConfigService sysConfigService;
    @Resource
    private MusicSheetPurchaseRecordService musicSheetPurchaseRecordService;
    @Resource
    private MusicSheetPracticeRecordService musicSheetPracticeRecordService;
    @Resource
    private MusicAlbumService musicAlbumService;
    @Resource
    private StudentService studentService;
    @Resource
    private MusicSheetAuthRecordService musicSheetAuthRecordService;
    @Resource
    private AlbumMusicRelateService albumMusicRelateService;
    @Resource
    private SysUserFeignService sysUserFeignService;
    @Resource
    private TeacherTotalService totalService;
    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private UserAccountService userAccountService;
    @Resource
    private MusicTagService musicTagService;
    @Resource
    private SubjectService subjectService;
    @Resource
    private InstrumentService instrumentService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private CourseCoursewareService courseCoursewareService;
    @Resource
    private PlatformCashAccountRecordService platformCashAccountRecordService;
    @Resource
    private StudentStarService studentStarService;
    @Resource
    private UserOrderService userOrderService;
    @Resource
    private MusicAlbumDao musicAlbumMapper;
    @Resource
    private MusicSheetService musicSheetService;
    @Resource
    private AlbumFavoriteService albumFavoriteService;
    @Resource
    private TenantInfoService tenantInfoService;
    @Resource
    private UserTenantAlbumRecordMapper userTenantAlbumRecordMapper;
    @Resource
    private TenantAlbumMusicService tenantAlbumMusicService;
    @Resource
    private TenantGroupAlbumMapper tenantGroupAlbumMapper;
    @Resource
    private TenantAlbumMusicMapper tenantAlbumMusicMapper;
    @Resource
    private MusicSheetAccompanimentService musicSheetAccompanimentService;
    @Resource
    private MusicFeignClientService musicFeignClientService;
    @Resource
    private OpenFeignClientConfigProperties openFeignClientConfigProperties;

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

    public MusicSheetDao getDao() {
        return musicSheetDao;
    }

    @Override
    public IPage<MusicSheetVo> selectPage(IPage<MusicSheetVo> page, MusicSheetSearch query) {

        List<MusicSheetVo> records = baseMapper.selectPage(page, query);

        if (CollectionUtils.isNotEmpty(records)) {

            // 更新曲目专辑数量
            musicSheetService.updateMusicAlbumNumInfo(records);
        }

        // 来源为机构的曲目设置机构名称
        List<Long> tenantIds = records.stream()
                .filter(o -> o.getSourceType() != null && o.getSourceType().equals(SourceTypeEnum.TENANT))
                .map(o -> o.getUserId()).distinct()
                .collect(Collectors.toList());

        Map<Long, TenantInfo> tenantInfoMap = tenantInfoService.getMapByIds(tenantIds);
        for (MusicSheetVo record : records) {
            if (record.getSourceType() == null) {
                break;
            }
            switch (record.getSourceType()) {
                case TENANT:
                    TenantInfo tenantInfo = tenantInfoMap.get(record.getUserId());
                    if (tenantInfo != null) {
                        record.setSourceName(tenantInfo.getName());
                    }
                    break;
                case TEACHER:

                case PLATFORM:
                    record.setSourceName(record.getSourceType().getMsg());
                default:
                    break;
            }
        }

        return page.setRecords(records);
    }

    @Override
    public IPage<MusicSheetVoResult> selectCbsPage(IPage<MusicSheetVo> page, MusicSheetSearch query) {
        List<MusicSheetVo> musicSheets = baseMapper.selectPage(page, query);
        IPage<MusicSheetVo> info = page.setRecords(musicDataFormat(musicSheets,query.getProviderType()));
        List<MusicSheetVo> rows = info.getRecords();
        List<MusicSheetVoResult> musicSheetVoResults = new ArrayList<>();
        for (MusicSheetVo row : rows) {
            MusicSheetVoResult musicSheetVoResult = JSON.parseObject(JSON.toJSONString(row), MusicSheetVoResult.class);
            musicSheetVoResult.setCbsMusicSheetId(row.getCbsMusicSheetId().toString());
            musicSheetVoResults.add(musicSheetVoResult);
        }
        return com.yonge.cooleshow.biz.dal.dto.PageUtil.transPageInfo(info, musicSheetVoResults);
    }

    public List<MusicSheetVo> musicDataFormat(List<MusicSheetVo> musicSheets,SourceTypeEnum sourceType) {
        if (CollectionUtils.isEmpty(musicSheets)) {
            return musicSheets;
        }
        List<Long> cbsMusicSheetIds = musicSheets.stream().map(MusicSheet::getCbsMusicSheetId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(cbsMusicSheetIds)) {
            return new ArrayList<>();
        }
        Long appId = Long.parseLong(openFeignClientConfigProperties.getAppId());
        if (sourceType!=null && sourceType==SourceTypeEnum.TENANT) {
            appId = Long.parseLong(sysConfigService.findConfigValue(SysConfigConstant.CBS_TENANT_APP_ID));
        }
        // 调用内容平台查询曲目信息
        R<PageInfo<CbsMusicSheetWrapper.MusicSheetApplication>> pageInfoR = musicFeignClientService
                .musicSheetPageByApplication(CbsMusicSheetWrapper.MusicSheetApplicationQuery.builder()
                        .musicSheetIds(cbsMusicSheetIds).detailFlag(false).rows(-1).delFlag(true)
                        .applicationId(appId).build());
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows;
        try {
            PageInfo<CbsMusicSheetWrapper.MusicSheetApplication> musicSheetApplicationPageInfo = pageInfoR.feignData();
            rows = musicSheetApplicationPageInfo.getRows();
        }catch (Exception e) {
            log.error("调用内容平台服务异常", e);
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("内容平台服务异常");
        }
        if (CollectionUtils.isEmpty(rows)) {
            return new ArrayList<>();
        }
        //  rows 转 map
        Map<Long, CbsMusicSheetWrapper.MusicSheetApplication> musicSheetApplicationMap = Maps.uniqueIndex(rows, CbsMusicSheetWrapper.MusicSheetApplication::getId);
        // 曲目信息转换
        for (MusicSheetVo musicSheet : musicSheets) {
            CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication = musicSheetApplicationMap.get(musicSheet.getCbsMusicSheetId());
            if (musicSheetApplication == null) {
                continue;
            }
            musicSheetApplicationToMusicSheet(musicSheetApplication, musicSheet);
        }
        return musicSheets;
    }

    @Override
    public IPage<MusicSheetVo> queryRelatedList(IPage<MusicSheetVo> page, MusicSheetRelatedQueryInfo queryInfo) {


        MusicSheet musicSheet = baseMapper.selectById(queryInfo.getMusicSheetId());
        if (queryInfo.getAlbumId() == null) {
            // 查询专辑下的所有曲目


            if (musicSheet != null) {
                MusicAlbumDetailSearch query = new MusicAlbumDetailSearch();
                query.setMusicTagIds(musicSheet.getMusicTag());
                query.setAuditVersion(musicSheet.getAuditVersion());
                query.setMusicSheetType(musicSheet.getMusicSheetType());
                if (queryInfo.getSubjectId() !=null) {
                    query.setSubjectIdList(Lists.newArrayList(queryInfo.getSubjectId()));
                }
                query.setState(YesOrNoEnum.YES);
                query.setProviderType(SourceTypeEnum.PLATFORM);
                query.setExcludeMusicIds(Lists.newArrayList(queryInfo.getMusicSheetId()));
                if (StringUtils.isNotBlank(musicSheet.getMusicSubject())) {
                    List<Long> subjectIds = Arrays.stream(musicSheet.getMusicSubject().split(",")).filter(StringUtils::isNotBlank).map(Long::parseLong).collect(Collectors.toList());
                    query.setMustMatchSubjectIds(subjectIds);
                }
                return page.setRecords(baseMapper.selectPage(page, query));
            }
        } else {
            // 查询带有当前曲目标签的所有曲目
            MusicAlbumDetailSearch query = new MusicAlbumDetailSearch();
            query.setId(queryInfo.getAlbumId());
            query.setState(YesOrNoEnum.YES);
            query.setType(2);
            if (queryInfo.getSubjectId() !=null) {
                query.setSubjectIdList(Lists.newArrayList(queryInfo.getSubjectId()));
            }
            query.setExcludeMusicIds(Lists.newArrayList(queryInfo.getMusicSheetId()));
            if (StringUtils.isNotBlank(musicSheet.getMusicSubject())) {
                List<Long> subjectIds = Arrays.stream(musicSheet.getMusicSubject().split(",")).filter(StringUtils::isNotBlank).map(Long::parseLong).collect(Collectors.toList());
                query.setMustMatchSubjectIds(subjectIds);
            }
            query.setExcludeMusicIds(Lists.newArrayList(queryInfo.getMusicSheetId()));
            return page.setRecords(baseMapper.selectAlbumDetailPage(page, query));
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean state(Long id, String reason, ClientEnum client) {
        MusicSheet musicSheet = this.getById(id);
        if (musicSheet == null) {
            throw new BizException("未找到曲目信息");
        }
        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = this.getMusicSheetApplicationQuery();
        query.setMusicSheetIds(Collections.singletonList(musicSheet.getCbsMusicSheetId()));
        query.setRows(1);
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows = this.queryCbsMusicSheetApplication(query);
        if (CollectionUtils.isEmpty(rows)) {
            throw new BizException("获取曲目信息失败");
        }
        CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication = rows.get(0);
        CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtendStatus extendStatus = new CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtendStatus();
        extendStatus.setIds(musicSheetApplication.getApplicationExtendId().toString());
        extendStatus.setStatus(!musicSheet.getClientState());
        R<JSONObject> jsonObjectR = musicFeignClientService.musicSheetApplicationExtendStatus(extendStatus);
        if (jsonObjectR.getCode() != 200) {
            throw new BizException("修改曲目状态失败,{}", jsonObjectR.getMessage());
        }
        return true;
    }

    private void sendOutSaleMessage(String reason, MusicSheet musicSheet) {
        try {
            if(musicSheet.getSourceType().equals(SourceTypeEnum.TEACHER)) {
                SysUser sysUser = getSysUser(musicSheet.getUserId());
                // 推送老师
                Map<Long, String> teacherReceivers = new HashMap<>();
                teacherReceivers.put(sysUser.getId(), sysUser.getPhone());

                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSIC_SHEET_OUT_SALE_REASON, teacherReceivers, null,
                                                   0, null, ClientEnum.TEACHER.getCode(), musicSheet.getMusicSheetName(),reason);
            }
        } catch (Exception e) {
            log.error("曲目下架失败 -->{}",e.fillInStackTrace());
        }

    }

    @Override
    public IPage<MusicSheetVo> selectAlbumDetailPage(IPage<MusicSheetVo> page, MusicAlbumDetailSearch query) {
        IPage<MusicSheetVo> musicSheetVoIPage = page.setRecords(baseMapper.selectAlbumDetailPage(page, query));

        List<MusicSheetVo> records = musicSheetVoIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return musicSheetVoIPage;
        }
        // 是否关注
        if (query.getStudentId() != null) {
            List<Long> musicIdList = records.stream().map(MusicSheetVo::getId).collect(Collectors.toList());
            List<MusicFavorite> musicFavoriteList = musicFavoriteService.lambdaQuery()
                    .eq(MusicFavorite::getUserId, query.getStudentId())
                    .eq(MusicFavorite::getClientType, query.getClientType())
                    .in(MusicFavorite::getMusicSheetId, musicIdList)
                    .list();
            if (CollectionUtils.isNotEmpty(musicFavoriteList)) {
                Set<Long> set = musicFavoriteList.stream()
                        .map(MusicFavorite::getMusicSheetId)
                        .collect(Collectors.toSet());
                for (MusicSheetVo record : records) {
                    record.setFavorite(set.contains(record.getId())?YesOrNoEnum.YES:YesOrNoEnum.NO);
                }
            }
        }

        return musicSheetVoIPage;
    }

    @Override
    public MusicSheetShareVo shareMusicSheet(SysUser sysUser) {
        MusicSheetSearch query = new MusicSheetSearch();
        // 设置只查老师用户
        query.setCreateBy(sysUser.getId());
        query.setAuditStatus(null);
        query.setState(YesOrNoEnum.YES);
        query.setDelFlag(false);
        query.setSourceType(SourceTypeEnum.TEACHER);
        // 只查3条
        query.setRows(3);
        IPage<MusicSheetVo> musicSheetVoIPage = selectPage(PageUtil.getPage(query), query);
        MusicSheetShareVo musicSheetShareVo = new MusicSheetShareVo();
        musicSheetShareVo.setMusicSheetCount(musicSheetVoIPage.getTotal());
        musicSheetShareVo.setMusicSheetVoList(musicSheetVoIPage.getRecords());
        musicSheetShareVo.setName(sysUser.getUsername());
        musicSheetShareVo.setAvatar(sysUser.getAvatar());

        String teacherMusicShareUrl = sysConfigService.findConfigValue(SysConfigConstant.TEACHER_MUSIC_SHEET_SHARE_URL);
        musicSheetShareVo.setUrl(MessageFormatter.arrayFormat(teacherMusicShareUrl, sysUser.getId()));

        return musicSheetShareVo;
    }

    public MusicSheetDetailVo getCbsDetail(Long id,SourceTypeEnum sourceTypeEnum) {
        MusicSheet musicSheet = this.baseMapper.get(id);
        if (musicSheet == null) {
            throw new BizException("未找到曲目信息");
        }
        if(musicSheet.getCbsMusicSheetId() == null){
            throw new BizException("曲目信息未同步");
        }
        MusicSheetDetailVo detailVo = JSON.parseObject(JSON.toJSONString(musicSheet), MusicSheetDetailVo.class);
        this.initMusicSheetDetailVo(detailVo,musicSheet,sourceTypeEnum);
        detailVo.setProviderType(musicSheet.getProviderType());
        return detailVo;
    }

    @Override
    public MusicSheetDetailVo getAuditDetail(Long id) {
        MusicSheet musicSheet = this.baseMapper.get(id);
        if (musicSheet == null) {
            throw new BizException("未找到曲目信息");
        }
        MusicSheetDetailVo detailVo = JSON.parseObject(JSON.toJSONString(musicSheet), MusicSheetDetailVo.class);
        List<MusicSheetAccompaniment> list = musicSheetAccompanimentService.lambdaQuery().eq(MusicSheetAccompaniment::getMusicSheetId, id).list();
        detailVo.setBackground(list);
        //声部名称
        List<Subject> subjectList = subjectService.findBySubjectByIdList(musicSheet.getMusicSubject());
        detailVo.setSubjectNames(subjectList.stream().map(e->e.getName()).collect(Collectors.joining(",")));
        //曲目标签
        if(StringUtils.isNotEmpty(musicSheet.getMusicTag())){
            List<MusicTag> musicTagList = musicTagService.lambdaQuery()
                    .in(MusicTag::getId, Arrays.stream(musicSheet.getMusicTag().split(","))
                            .map(Long::parseLong).collect(Collectors.toList())).list();
            detailVo.setMusicTagNames(musicTagList.stream().map(MusicTag::getName).collect(Collectors.joining(",")));
        }
        return detailVo;
    }


    public void initMusicSheetDetailVo(MusicSheetDetailVo detailVo,MusicSheet musicSheet,SourceTypeEnum sourceTypeEnum) {
        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = this.getMusicSheetApplicationQuery(sourceTypeEnum);
        query.setRows(1);
        query.setDelFlag(true);
        query.setMusicSheetIds(Collections.singletonList(musicSheet.getCbsMusicSheetId()));
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows = this.queryCbsMusicSheetApplication(query);
        if(CollectionUtils.isEmpty(rows)){
            throw new BizException("获取曲目信息失败");
        }
        CbsMusicSheetWrapper.MusicSheetApplication musicSheet1 = rows.get(0);
        CbsMusicSheetWrapper.MusicSheetExtend musicSheetExtend = musicSheet1.getMusicSheetExtend();
        if (musicSheetExtend != null && musicSheetExtend.getUserId() != null) {
            detailVo.setUserName(musicSheetExtend.getUserName());
            detailVo.setUserId(musicSheetExtend.getUserId());
            //获取用户头像
            SysUser sysUser = sysUserFeignService.queryUserById(musicSheetExtend.getUserId());
            if (sysUser != null) {
                detailVo.setUserAvatar(sysUser.getAvatar());
                detailVo.setUserName(sysUser.getUsername());
            }
        }
        detailVo.setSpeedBeatUnit(musicSheet1.getSpeedBeatUnit());
        if (musicSheet1.getScoreType() !=null) {
            detailVo.setScoreType(musicSheet1.getScoreType().name());
        }
        if (musicSheet1.getIsConvertibleScore() !=null) {
            detailVo.setNotation(musicSheet1.getIsConvertibleScore()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        detailVo.setCategoryId(musicSheet1.getMusicCategoryId()!=null?musicSheet1.getMusicCategoryId().toString():"");
        detailVo.setMusicPrice(musicSheet1.getMusicPrice());
        detailVo.setSubjectNames(musicSheet1.getSubjectNames());
        detailVo.setCode(musicSheet1.getSubjectCodes());
        detailVo.setId(musicSheet.getId());
        detailVo.setCbsMusicSheetId(musicSheet1.getId());
        detailVo.setMp3Type(AudioTypeEnum.valueOf(musicSheet1.getIsPlayBeat()&&musicSheet1.getIsUseSystemBeat()?"MP3":"MP3_METRONOME"));
        detailVo.setIsPlayBeat(musicSheet1.getIsPlayBeat());
        detailVo.setAudioType(AudioTypeEnum.valueOf(musicSheet1.getPlayMode().getCode()));
        detailVo.setCanEvaluate(musicSheet1.getIsEvaluated() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        detailVo.setShowFingering(musicSheet1.getIsShowFingering() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        detailVo.setMusicTagNames(musicSheet1.getMusicTagNames());
        detailVo.setMusicImg(musicSheet1.getMusicImg());
        detailVo.setTitleImg(musicSheet1.getMusicCover());
        detailVo.setPlaySpeed(musicSheet1.getPlaySpeed());
        detailVo.setIsMixBeat(musicSheet1.getIsMixBeat());
        detailVo.setMusicPdfUrl(musicSheet1.getMusicPdfUrl());
        detailVo.setFirstPdfUrl(musicSheet1.getFirstPdfUrl());
        detailVo.setJianPdfUrl(musicSheet1.getJianPdfUrl());
        List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = musicSheet1.getMusicSheetAccompanimentList();
        if (CollectionUtils.isNotEmpty(accompanimentList)) {
            CbsMusicSheetWrapper.MusicSheetAccompaniment accompaniment = accompanimentList.get(0);
            detailVo.setMetronomeUrl(accompaniment.getAudioFileUrl());
            detailVo.setAccMusicPdfUrl(accompaniment.getMusicPdfUrl());
            detailVo.setAccFirstPdfUrl(accompaniment.getFirstPdfUrl());
            detailVo.setAccJianPdfUrl(accompaniment.getJianPdfUrl());
        }
        detailVo.setXmlFileUrl(musicSheet1.getXmlFileUrl());
        detailVo.setMidiUrl(musicSheet1.getMidiFileUrl());
        detailVo.setAuditVersion(musicSheet1.getAppAuditFlag() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        detailVo.setHasBeat((musicSheet1.getIsPlayBeat() && !musicSheet1.getIsUseSystemBeat()) ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        detailVo.setExtConfigJson(musicSheet1.getExtConfigJson());
        detailVo.setMusicJSON(musicSheet1.getMusicJson());
        detailVo.setMusicJianSvg(musicSheet1.getMusicJianSvg());
        detailVo.setMusicFirstSvg(musicSheet1.getMusicFirstSvg());
        detailVo.setFirstTone(musicSheet1.getMusicFirstImg());
        detailVo.setFixedTone(musicSheet1.getMusicJianImg());
        List<CbsMusicSheetWrapper.MusicSheetSound> soundList = musicSheet1.getMusicSheetSoundList();
        if (CollectionUtils.isNotEmpty(soundList)) {
            List<MusicSheetAccompaniment> background = new ArrayList<>();
            for (CbsMusicSheetWrapper.MusicSheetSound sound : soundList) {
                MusicSheetAccompaniment accompaniment = new MusicSheetAccompaniment();
                accompaniment.setMusicSheetId(musicSheet.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);
            }
            //按照sortNumber排序
//            background.sort(Comparator.comparing(MusicSheetAccompaniment::getSortNumber));
            detailVo.setBackground(background);
            //获取乐器名称
            String instrumentIds = background.stream().map(e -> e.getMusicalInstrumentId()).filter(StringUtils::isNotEmpty).collect(Collectors.joining(","));
            if (StringUtils.isNotEmpty(instrumentIds)) {
                List<Long> instrumentIsList = Arrays.stream(instrumentIds.split(",")).map(Long::valueOf).distinct().collect(Collectors.toList());
                List<InstrumentWrapper.Instrument> instruments = instrumentService.getInstruments(instrumentIsList);
                Map<Long,InstrumentWrapper.Instrument> instrumentMap =
                        instruments.stream().collect(Collectors.toMap(InstrumentWrapper.Instrument::getId, o -> o, (o1, o2) -> o1));
                for (MusicSheetAccompaniment accompaniment : background) {
                    if (StringUtils.isNotEmpty(accompaniment.getMusicalInstrumentId())){
                        StringBuffer sb = new StringBuffer();
                        for (String s : accompaniment.getMusicalInstrumentId().split(",")) {
                            InstrumentWrapper.Instrument instrument = instrumentMap.get(Long.parseLong(s));
                            if (instrument != null){
                                if(sb.length() > 0) {
                                    sb.append(",");
                                }
                                sb.append(instrument.getName());
                            }
                        }
                        accompaniment.setMusicalInstrumentName(sb.toString());
                    }
                }
            }
        }
    }

    @Override
    public MusicSheetDetailVo detail(Long id, SysUser sysUser, ClientEnum userType) {
        return detail(id.toString(), sysUser, userType,null);
    }

    private void musicSheetApplicationToMusicSheet(CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication, MusicSheetVo sheet) {
        sheet.setMusicSheetName(musicSheetApplication.getName());
        if (musicSheetApplication.getMusicSheetType() != null) {
            sheet.setMusicSheetType(MusicSheetTypeEnum.valueOf(musicSheetApplication.getMusicSheetType().name()));
        }
        sheet.setTitleImg(musicSheetApplication.getMusicCover());
        sheet.setMusicImg(musicSheetApplication.getMusicImg());
        sheet.setUserId(musicSheetApplication.getUserId());
//        if(musicSheetApplication.getAvailableType() != null){
//            sheet.setProviderType(musicSheetApplication.getAvailableType() == EMusicAvailableType.PERSON ? SourceTypeEnum.TEACHER :
//                    musicSheetApplication.getAvailableType() == EMusicAvailableType.ORG ? SourceTypeEnum.TENANT :SourceTypeEnum.PLATFORM);
//        }
        sheet.setMusicPrice(musicSheetApplication.getMusicPrice());
        sheet.setComposer(musicSheetApplication.getComposer());
        sheet.setAudioType(AudioTypeEnum.valueOf(musicSheetApplication.getPlayMode().getCode()));
        if(musicSheetApplication.getScoreType() != null){
            sheet.setScoreType(musicSheetApplication.getScoreType().getCode());
        }
        if (StringUtils.isNotEmpty(musicSheetApplication.getPlaySpeed())) {
            sheet.setPlaySpeed(musicSheetApplication.getPlaySpeed());
        }
        if (musicSheetApplication.getIsConvertibleScore() != null){
            sheet.setNotation(musicSheetApplication.getIsConvertibleScore()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        if (musicSheetApplication.getIsEvaluated() != null){
            sheet.setCanEvaluate(musicSheetApplication.getIsEvaluated()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        if (musicSheetApplication.getIsShowFingering() != null){
            sheet.setShowFingering(musicSheetApplication.getIsShowFingering()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        if (musicSheetApplication.getAudioType() != null) {
            sheet.setAccompanimentType(AccompanimentTypeEnum.valueOf(musicSheetApplication.getAudioType().getCode()));
        }
        sheet.setCategoryName(musicSheetApplication.getMusicSheetCategoryName());
        sheet.setMusicTagNames(musicSheetApplication.getMusicTagNames());
        sheet.setSubjectNames(musicSheetApplication.getSubjectNames());
        sheet.setPaymentType(musicSheetApplication.getPaymentType());
        sheet.setSortNumber(musicSheetApplication.getSortNo());
        if (musicSheetApplication.getTopFlag() != null){
            sheet.setTopFlag(musicSheetApplication.getTopFlag()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        if (musicSheetApplication.getExquisiteFlag() != null){
            sheet.setExquisiteFlag(musicSheetApplication.getExquisiteFlag()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        sheet.setMusicPrice(musicSheetApplication.getMusicPrice());
        if (CollectionUtils.isNotEmpty(musicSheetApplication.getMusicSheetAccompanimentList())) {
            CbsMusicSheetWrapper.MusicSheetAccompaniment accompaniment = musicSheetApplication.getMusicSheetAccompanimentList().get(0);
            sheet.setAudioFileUrl(accompaniment.getAudioFileUrl());
            sheet.setMetronomeUrl(accompaniment.getAudioFileUrl());
            sheet.setAccMusicPdfUrl(accompaniment.getMusicPdfUrl());
            sheet.setAccFirstPdfUrl(accompaniment.getFirstPdfUrl());
            sheet.setAccJianPdfUrl(accompaniment.getJianPdfUrl());
        }
        sheet.setXmlFileUrl(musicSheetApplication.getXmlFileUrl());
        sheet.setMidiUrl(musicSheetApplication.getMidiFileUrl());
        if (musicSheetApplication.getAppAuditFlag() != null){
            sheet.setAuditVersion(musicSheetApplication.getAppAuditFlag()?YesOrNoEnum.YES:YesOrNoEnum.NO);
        }
        sheet.setHasBeat((musicSheetApplication.getIsPlayBeat() && !musicSheetApplication.getIsUseSystemBeat()) ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        sheet.setMp3Type((musicSheetApplication.getIsPlayBeat() && musicSheetApplication.getIsUseSystemBeat()) ? AudioTypeEnum.MP3 : AudioTypeEnum.MP3_METRONOME);
        sheet.setUpdateBy(musicSheetApplication.getUpdateBy());
        sheet.setExtConfigJson(musicSheetApplication.getExtConfigJson());
        sheet.setMusicJSON(musicSheetApplication.getMusicJson());
        sheet.setMusicSvg(musicSheetApplication.getMusicSvg());
        sheet.setMusicJianSvg(musicSheetApplication.getMusicJianImg());
        sheet.setMusicFirstSvg(musicSheetApplication.getMusicFirstImg());
        if(musicSheetApplication.getMusicSheetType() != null){
            sheet.setMusicSheetType(musicSheetApplication.getMusicSheetType() == EMusicSheetType.SINGLE ? MusicSheetTypeEnum.SINGLE : MusicSheetTypeEnum.CONCERT);
        }
        if(musicSheetApplication.getMusicSheetExtend() != null){
            sheet.setAddName(musicSheetApplication.getMusicSheetExtend().getUserName());
        }
    }

    @Override
    public MusicSheetDetailVo detail(String id, SysUser sysUser, ClientEnum userType,String tenantAlbumId) {
        MusicSheetDetailVo detailVo = baseMapper.detail(Long.parseLong(id));
        if (detailVo == null) {
            MusicSheetDetailVo result = musicSheetAuthRecordService.auditDetail(id);
            if (result != null) {
                if(StringUtils.isNotEmpty(result.getMusicSheetJson())){
                    return result;
                }else {
                    MusicSheetAuthRecord authRecord = musicSheetAuthRecordService.getById(id);
                    detailVo = baseMapper.detail(authRecord.getMusicSheetId());
                    if(detailVo == null){
                        throw new BizException("未找到曲目信息");
                    }
                    id = authRecord.getMusicSheetId().toString();
                }
            }
            if(result == null){
                throw new BizException("未找到曲目信息");
            }
        }
        boolean tenantFlag =false;
        MusicSheetDetailVo detail ;
        if (sysUser == null || userType == ClientEnum.SYSTEM) {

            try {
                if (StringUtil.isEmpty(tenantAlbumId)) {
                    detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.PLATFORM);
                } else {
                    detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.TENANT);
                }
            } catch (Exception e) {
                throw new BizException("未找到曲目信息");
            }
        } else
        if (StringUtil.isEmpty(tenantAlbumId)) {

            // 如果是机构用户，判断机构专辑

            // 机构学生，查询购买过的机构专辑，是否存在当前曲目
            Long tenantId = userTenantId(sysUser.getId(), userType);

            if (tenantId >0L) {
                if (userType == ClientEnum.STUDENT) {
                    detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.TENANT);
                    tenantFlag = true;
                } else {
                    if (detailVo.getProviderType().contains(SourceTypeEnum.PLATFORM.getCode())) {
                        detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.PLATFORM);

                    } else {
                        detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.TENANT);
                        tenantFlag = true;
                    }
                }

            } else {
                detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.PLATFORM);
            }
        } else {

            detail = this.getCbsDetail(Long.parseLong(id),SourceTypeEnum.TENANT);
            tenantFlag = true;
        }
        detail.setPlay(YesOrNoEnum.NO);
        detail.setTenantFlag(false);
        //兼容审批数据
        MusicSheetAuthRecord one = musicSheetAuthRecordService.lambdaQuery().eq(MusicSheetAuthRecord::getMusicSheetId, detail.getId()).last("limit 1").one();
        if (one != null) {
            detail.setMusicSheetAuthRecordId(one.getId().toString());
        }
        // 设置收藏人数
        detail.setFavoriteCount(detail.getFavoriteCount() + detail.getVirtualNumber());

        if (sysUser == null || userType == ClientEnum.SYSTEM) {
            return detail;
        }

        // 设置课件
        List<CourseCourseware> list = courseCoursewareService.lambdaQuery()
                                                             .eq(CourseCourseware::getClientType, userType)
                                                             .eq(CourseCourseware::getMusicSheetId, id)
                                                             .eq(CourseCourseware::getUserId, sysUser.getId())
                                                             .eq(CourseCourseware::getDelFlag, false)
                                                             .list();
        if (CollectionUtils.isNotEmpty(list)) {
            detail.setCoursewareStatus(YesOrNoEnum.YES);
            detail.setCoursewareId(list.get(0).getId());
        }


        // 收藏
        YesOrNoEnum favorite = musicFavoriteService.checkFavorite(Long.parseLong(id),sysUser.getId(),userType,tenantFlag?"TENANT":"PLATFORM");
        detail.setFavorite(favorite);

        // 播放状态
        if (AuthStatusEnum.UNPASS.getCode().equals(detail.getAuditStatus().getCode())) {
            String reason = musicSheetAuthRecordService.selectAuditReason(Long.parseLong(id));
            detail.setReason(reason);
        }
        if (StringUtil.isEmpty(tenantAlbumId)) {

            // 如果是机构用户，判断机构专辑

            // 机构学生，查询购买过的机构专辑，是否存在当前曲目
            Long tenantId = userTenantId(sysUser.getId(), userType);

            if (tenantId >0L) {

                if (detail.getProviderType().contains(SourceTypeEnum.TENANT.getCode())) {
                    if (userType == ClientEnum.STUDENT) {
                        detail.setTenantFlag(true);
                        // 机构学生
                        List<Long> tenantAlbumIds = userTenantAlbumRecordMapper.selectTenantIds(sysUser.getId());
                        if (CollectionUtils.isNotEmpty(tenantAlbumIds)) {
                            List<Long> musicSheetIds = tenantAlbumMusicService.getMusicIdsByIds(tenantAlbumIds);
                            if (musicSheetIds.contains(detail.getId())) {
                                detail.setPlay(YesOrNoEnum.YES);
                                detail.setBuyed(true);
                            }
                        }
                    } else {
                        // 老师所在机构启用的专辑
                        Teacher teacher = teacherService.getById(sysUser.getId());
                        if (teacher.getTenantId() >0) {
//                            List<Long> musicSheetIds = tenantAlbumMusicService.getMusicIdsByTenantIds(teacher.getTenantId());
//                            if (musicSheetIds.contains(detail.getId())) {
//                                detail.setPlay(YesOrNoEnum.YES);
//                                detail.setBuyed(true);
//                                detail.setTenantFlag(true);
//                            }
                        }
                        if (detail.getPlay() ==YesOrNoEnum.NO) {
                            platformMusicUseCheck(sysUser, userType, detail);
                        }
                    }
                }else {
                    if (!detail.getProviderType().contains(SourceTypeEnum.PLATFORM.getCode())) {
                        return detail;
                    }
                    platformMusicUseCheck(sysUser, userType, detail);
                }
            } else {
                if (!detail.getProviderType().contains(SourceTypeEnum.PLATFORM.getCode())) {
                    return detail;
                }
                platformMusicUseCheck(sysUser, userType, detail);
            }
        } else {
            detail.setTenantFlag(true);
            if (!detail.getProviderType().contains(SourceTypeEnum.TENANT.getCode())) {
                return detail;
            }
            // 机构专辑购买
            List<Long> collected = Arrays.stream(tenantAlbumId.split(",")).map(Long::parseLong).collect(Collectors.toList());

            // 学生生效中的机构专辑
            if (ClientEnum.STUDENT == userType) {
                List<Long> tenantAlbumIds = userTenantAlbumRecordMapper.selectTenantIds(sysUser.getId());
                if (CollectionUtils.isNotEmpty(tenantAlbumIds)) {
                    // tenantAlbumIds collected 取交集到 新的集合
                    List<Long> collect = tenantAlbumIds.stream().filter(collected::contains).collect(Collectors.toList());
                    List<Long> musicSheetIds = tenantAlbumMusicService.getMusicIdsByIds(collect);
                    if (CollectionUtils.isNotEmpty(musicSheetIds) && musicSheetIds.contains(detail.getId())) {
                        detail.setPlay(YesOrNoEnum.YES);
                        detail.setBuyed(true);
                    }
                }
            } else if (ClientEnum.TEACHER == userType) {
                // 老师所在机构启用的专辑
                Teacher teacher = teacherService.getById(sysUser.getId());
                if (teacher.getTenantId() !=null) {
                    List<Long> musicSheetIds = tenantAlbumMusicService.getMusicIdsByTenantIds(teacher.getTenantId());
                    if (musicSheetIds.contains(detail.getId())) {
                        detail.setPlay(YesOrNoEnum.YES);
                        detail.setBuyed(true);
                    }
                }
            }
        }
        if (detail.getTenantFlag()) {
            detail.setNotation(detail.getTenantNotation() !=null&& detail.getTenantNotation()?YesOrNoEnum.YES:YesOrNoEnum.NO);
            detail.setScoreType(detail.getTenantScoreType());

        }
        return detail;
    }

    private void platformMusicUseCheck(SysUser sysUser, ClientEnum userType, MusicSheetDetailVo detail) {
        if (!detail.getProviderType().contains(SourceTypeEnum.PLATFORM.getCode())) {
            return;
        }
        if (detail.getPaymentType().contains(ChargeTypeEnum.FREE.getCode())) {
            detail.setPlay(YesOrNoEnum.YES);
        } else if (ClientEnum.STUDENT.getCode().equals(userType.getCode())
            || ClientEnum.TEACHER.getCode().equals(userType.getCode())) {
            // 2022 7 20  老师也能购买曲目
            if (ClientEnum.TEACHER.getCode().equals(userType.getCode()) && sysUser.getId().equals(detail.getUserId())) {
                detail.setPlay(YesOrNoEnum.YES);
            } else {
                setMusicSheetPlay(sysUser.getId(), detail, userType);
            }
        } else {
            detail.setPlay(YesOrNoEnum.YES);
        }
    }

    private Long userTenantId(Long userId, ClientEnum userType) {
        if (ClientEnum.STUDENT == userType) {
            Student student = studentService.getById(userId);
            if (student != null&& student.getTenantId() !=null && student.getTenantId() >0) {
                return student.getTenantId();
            }
        } else if (ClientEnum.TEACHER == userType) {
            Teacher teacher = teacherService.getById(userId);
            if (teacher != null && teacher.getTenantId() !=null && teacher.getTenantId() >0) {
                return teacher.getTenantId();
            }
        }
        return -1L;

    }

    /**
     * 设置学生曲目信息
     * <p>
     * 2022 7 20  老师也能购买曲目
     *
     * @param studentId 学生id
     * @param detail    曲目详情
     * @param userType  用户类型
     */
    private void setMusicSheetPlay(Long studentId, MusicSheetDetailVo detail, ClientEnum userType) {
//        detail.setPlay(YesOrNoEnum.NO);
        // 单曲购买 判断购买记录，有记录课播放
        if (detail.getPaymentType().contains(ChargeTypeEnum.CHARGE.getCode())) {
            // 学生须判断是否能播放曲目
            MusicSheetPurchaseRecord musicSheetPurchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                    studentId, detail.getId(), userType, PurchaseRecordTypeEnum.MUSIC);
            if (musicSheetPurchaseRecord != null) {
                detail.setOrderStatus(musicSheetPurchaseRecord.getOrderStatus());
                detail.setOrderNo(musicSheetPurchaseRecord.getOrderNo());
                if (OrderStatusEnum.PAID.getCode().equals(musicSheetPurchaseRecord.getOrderStatus().getCode())) {
                    detail.setPlay(YesOrNoEnum.YES);
                    detail.setBuyed(true);
                    return;
                }
            }
        }
        if (detail.getPaymentType().contains(ChargeTypeEnum.VIP.getCode())) {
            // 先判断是否购买过
            MusicSheetPurchaseRecord musicSheetPurchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                    studentId, detail.getId(), userType, PurchaseRecordTypeEnum.MUSIC);
            if (musicSheetPurchaseRecord != null && OrderStatusEnum.PAID.getCode().equals(musicSheetPurchaseRecord.getOrderStatus().getCode())) {
                detail.setPlay(YesOrNoEnum.YES);
            } else
            // 会员 判断是否为会员， 会员可播放
            if (userType.equals(ClientEnum.STUDENT)) {
                StudentVo studentVo = studentService.detail(studentId);
                if (studentVo != null && studentVo.getUserVip().getVipType() !=EVipType.NOT_VIP) {
                    detail.setPlay(YesOrNoEnum.YES);
                }
            } else if (userType.equals(ClientEnum.TEACHER)) {
                TeacherVo teacher = teacherService.detail(studentId);
                if (teacher != null && teacher.getUserVip().getVipType() !=EVipType.NOT_VIP) {
                    detail.setPlay(YesOrNoEnum.YES);
                }
            }
        }

        if (detail.getPlay().equals(YesOrNoEnum.YES)) {
            return;
        }

        if (detail.getDelFlag() ||detail.getState() == YesOrNoEnum.NO) {
            return;
        }

        // 判断专辑购买

        // 1 查询曲目所在的专辑
        List<AlbumMusicRelate> albumMusicRelateList = albumMusicRelateService.lambdaQuery()
                                                             .eq(AlbumMusicRelate::getMusicSheetId, detail.getId())
                                                             .list();
        if (!CollectionUtils.isEmpty(albumMusicRelateList)) {

            List<Long> albumIdList = albumMusicRelateList.stream()
                    .map(AlbumMusicRelate::getAlbumId)
                    .collect(Collectors.toList());

            // 2 检查是否购买过专辑
            Integer count = musicSheetPurchaseRecordService.lambdaQuery()
                    .eq(MusicSheetPurchaseRecord::getClientType, userType)
                    .eq(MusicSheetPurchaseRecord::getOrderStatus,
                            OrderStatusEnum.PAID)
                    .in(MusicSheetPurchaseRecord::getMusicSheetId, albumIdList)
                    .eq(MusicSheetPurchaseRecord::getPurchaseType,
                            PurchaseRecordTypeEnum.ALBUM)
                    .eq(MusicSheetPurchaseRecord::getStudentId, studentId)
                    .count();
            if (count > 0) {
                detail.setPlay(YesOrNoEnum.YES);
                detail.setBuyed(true);
            }
        }
    }

    public void initMusicSheetVo(MusicSheetVo record,CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication){
        record.setSubjectNames(musicSheetApplication.getSubjectNames());
        record.setMusicPrice(musicSheetApplication.getMusicPrice());
        record.setCbsMusicSheetId(musicSheetApplication.getId());
        record.setAudioType(AudioTypeEnum.valueOf(musicSheetApplication.getPlayMode().getCode()));
        record.setCanEvaluate(musicSheetApplication.getIsEvaluated() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        record.setShowFingering(musicSheetApplication.getIsShowFingering() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        record.setMusicTagNames(musicSheetApplication.getMusicTagNames());
        List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = musicSheetApplication.getMusicSheetAccompanimentList();
        if (CollectionUtils.isNotEmpty(accompanimentList)) {
            CbsMusicSheetWrapper.MusicSheetAccompaniment accompaniment = accompanimentList.get(0);
            record.setMetronomeUrl(accompaniment.getAudioFileUrl());
            record.setAccMusicPdfUrl(accompaniment.getMusicPdfUrl());
            record.setAccFirstPdfUrl(accompaniment.getFirstPdfUrl());
            record.setAccJianPdfUrl(accompaniment.getJianPdfUrl());
        }
        record.setXmlFileUrl(musicSheetApplication.getXmlFileUrl());
        record.setMidiUrl(musicSheetApplication.getMidiFileUrl());
        record.setAuditVersion(musicSheetApplication.getAppAuditFlag() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        record.setHasBeat((musicSheetApplication.getIsPlayBeat() && !musicSheetApplication.getIsUseSystemBeat()) ? YesOrNoEnum.YES : YesOrNoEnum.NO);
        record.setMp3Type((musicSheetApplication.getIsPlayBeat() && musicSheetApplication.getIsUseSystemBeat()) ? AudioTypeEnum.MP3 : AudioTypeEnum.MP3_METRONOME);
        record.setExtConfigJson(musicSheetApplication.getExtConfigJson());
        record.setMusicJSON(musicSheetApplication.getMusicJson());
        record.setMusicJianSvg(musicSheetApplication.getMusicJianSvg());
        record.setMusicFirstSvg(musicSheetApplication.getMusicFirstSvg());
        record.setFirstTone(musicSheetApplication.getMusicFirstImg());
        record.setFixedTone(musicSheetApplication.getMusicJianImg());
        record.setMusicSheetExtend(musicSheetApplication.getMusicSheetExtend());
        record.setMusicImg(musicSheetApplication.getMusicImg());
        record.setTitleImg(musicSheetApplication.getMusicCover());
    }

    public void initMusicSheetVos(List<MusicSheetVo> records) {
        initMusicSheetVos(records,SourceTypeEnum.PLATFORM);
    }

    public void initMusicSheetVos(List<MusicSheetVo> records,SourceTypeEnum sourceTypeEnum) {
        if(CollectionUtils.isNotEmpty(records)){
            List<Long> cbsMusicSheetIds = records.stream().map(e -> e.getCbsMusicSheetId()).collect(Collectors.toList());
            Map<Long, CbsMusicSheetWrapper.MusicSheetApplication> musicSheetApplicationMap = getMusicSheetApplicationMapByCbsIds(sourceTypeEnum, cbsMusicSheetIds);
            if (musicSheetApplicationMap == null) return;
            for (MusicSheetVo record : records) {
                CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication = musicSheetApplicationMap.get(record.getCbsMusicSheetId());
                if(musicSheetApplication != null){
                    this.initMusicSheetVo(record,musicSheetApplication);
                }
            }
        }

    }

    @Nullable
    private Map<Long, CbsMusicSheetWrapper.MusicSheetApplication> getMusicSheetApplicationMapByCbsIds(SourceTypeEnum sourceTypeEnum, List<Long> cbsMusicSheetIds) {
        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = this.getMusicSheetApplicationQuery(sourceTypeEnum);
        query.setRows(cbsMusicSheetIds.size());
        query.setMusicSheetIds(cbsMusicSheetIds);
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows = this.queryCbsMusicSheetApplication(query);
        if(CollectionUtils.isEmpty(rows)){
            return null;
        }
        Map<Long, CbsMusicSheetWrapper.MusicSheetApplication> musicSheetApplicationMap = rows
                .stream().collect(Collectors.toMap(CbsMusicSheetWrapper.MusicSheetApplication::getId, Function.identity()));
        return musicSheetApplicationMap;
    }

    @Override
    public IPage<MusicSheetVo> selectStudentPage(IPage<MusicSheetVo> page, StudentMusicSheetSearch query, ClientEnum clientType) {
        List<MusicSheetVo> records = baseMapper.selectStudentMusicPage(page, query, clientType);
        //设置内容平台曲目信息
        this.initMusicSheetVos(records,query.getProviderType());
        if (CollectionUtils.isNotEmpty(records)) {

            // 统计单曲归属专辑数
            updateMusicAlbumNumInfo(records);
            // 是否关注
            if (query.getStudentId() != null) {
                List<Long> musicIdList = records.stream().map(MusicSheetVo::getId).collect(Collectors.toList());
                List<MusicFavorite> musicFavoriteList = musicFavoriteService.lambdaQuery()
                                                                .eq(MusicFavorite::getUserId, query.getStudentId())
                                                                .eq(MusicFavorite::getClientType, clientType)
                                                                .in(MusicFavorite::getMusicSheetId, musicIdList)
                                                                .in(MusicFavorite::getProviderType, "PLATFORM" )
                                                                .list();
                if (CollectionUtils.isNotEmpty(musicFavoriteList)) {
                    Set<Long> set = musicFavoriteList.stream()
                                                          .map(MusicFavorite::getMusicSheetId)
                                                          .collect(Collectors.toSet());
                    for (MusicSheetVo record : records) {
                        record.setFavorite(set.contains(record.getId())?YesOrNoEnum.YES:YesOrNoEnum.NO);
                    }
                }
            }

        }
        return page.setRecords(records);

    }

    /**
     * 更新曲目专辑数
     * @param records List<MusicSheetVo>
     * @return List<MusicSheetVo>
     */
    public List<MusicSheetVo> updateMusicAlbumNumInfo(List<MusicSheetVo> records) {
        for (MusicSheetVo record : records) {
            // 设置收藏人数
            record.setFavoriteCount(record.getFavoriteCount() + record.getVirtualNumber());
        }
        List<Long> musicIds = records.stream()
                .map(MusicSheet::getId).distinct().collect(Collectors.toList());

        Map<Long, Integer> collect = getBaseMapper().selectMusicAlbumStatInfo(musicIds).stream()
                .collect(Collectors.toMap(StatGroupWrapper::getId, StatGroupWrapper::getTotal, (o, n) -> n));

        for (MusicSheetVo item : records) {

            item.setAlbumNums(collect.getOrDefault(item.getId(), 0));
        }

        return records;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setFavorite(Long userId, Long musicSheetId, ClientEnum clientType,String providerType) {
        List<MusicFavorite> musicFavorites = musicFavoriteService.getFavorite(userId, musicSheetId, clientType,providerType);
        if (CollectionUtils.isEmpty(musicFavorites)) {
            MusicFavorite musicFavorite = new MusicFavorite();
            musicFavorite.setMusicSheetId(musicSheetId);
            musicFavorite.setClientType(clientType);
            musicFavorite.setUserId(userId);
            musicFavorite.setFavoriteTime(new Date());
            musicFavorite.setProviderType(providerType);
            musicSheetDao.updateFavoriteCount(musicSheetId,YesOrNoEnum.YES);
            return musicFavoriteService.save(musicFavorite);
        } else {
            List<Long> ids = musicFavorites.stream().map(MusicFavorite::getId).collect(Collectors.toList());
            musicSheetDao.updateFavoriteCount(musicSheetId,YesOrNoEnum.NO);
            return musicFavoriteService.removeByIds(ids);
        }
    }

    @Override
    public IPage<MusicSheetVo> myMusic(IPage<MusicSheetVo> page, StudentMusicSheetSearch query) {
        query.setDelFlag(null);
        query.setProviderType(SourceTypeEnum.PLATFORM);

        List<MusicSheetVo> records = baseMapper.selectMyMusicPage(page, query);
        //设置内容平台曲目信息
        this.initMusicSheetVos(records);

        // 统计曲目专辑数
        if (CollectionUtils.isNotEmpty(records)) {

            // 更新曲目专辑数量
            musicSheetService.updateMusicAlbumNumInfo(records);
        }

        return page.setRecords(records);
    }

    @Override
    public IPage<MusicSheetVo> favoriteMusic(IPage<MusicSheetVo> page, StudentMusicSheetSearch query, ClientEnum clientType) {

        List<MusicSheetVo> records = baseMapper.selectFavoriteMusicPage(page, query, clientType);

        if (CollectionUtils.isNotEmpty(records)) {
            this.initMusicSheetVos(records);

            // 更新曲目专辑数量
            musicSheetService.updateMusicAlbumNumInfo(records);
        }

        return page.setRecords(records);
    }

    @Override
    public IPage<MusicSheetVo> practiceMusic(IPage<MusicSheetVo> page, StudentMusicSheetSearch query) {
        // 预计最近练习表数据量会很多
        // 先找到最近练习的曲目id 在根据曲目id进行精确查找
        IPage<Long> practiceMusicIdPage = musicSheetPracticeRecordService.selectPracticeMusic(query, page.getCurrent(), page.getSize());
        List<Long> practiceMusicIdList = practiceMusicIdPage.getRecords();
        if (CollectionUtils.isEmpty(practiceMusicIdList)) {
            page.setRecords(new ArrayList<>());
            return page;
        }

        // 设置学生端收藏联系
        query.setClientType(ClientEnum.STUDENT);
        query.setState(null);
        query.setDelFlag(null);
        // 构建分页信息
        List<MusicSheetVo> musicSheetVos = baseMapper.selectPracticeMusicPage(query, practiceMusicIdList);
        //设置内容平台曲目信息
        this.initMusicSheetVos(musicSheetVos);
        page.setRecords(musicSheetVos);
        page.setPages(practiceMusicIdPage.getPages());
        page.setCurrent(practiceMusicIdPage.getCurrent());
        page.setSize(practiceMusicIdPage.getSize());
        page.setTotal(practiceMusicIdPage.getTotal());

        if (CollectionUtils.isNotEmpty(page.getRecords())) {

            // 更新曲目专辑数量
            musicSheetService.updateMusicAlbumNumInfo(page.getRecords());
        }
        for (MusicSheetVo record : page.getRecords()) {
            // 1失效 0 有效
            MusicSheetDetailVo detail = detail(record.getId(), sysUserFeignService.queryUserById(query.getStudentId()), ClientEnum.STUDENT);
            record.setTitleImg(detail.getTitleImg());
            record.setPlay(YesOrNoEnum.YES);
            if (query.getProviderType() == SourceTypeEnum.PLATFORM) {
                if (Boolean.TRUE.equals(detail.getBuyed())) {
                    record.setPlay(YesOrNoEnum.NO);
                } else if(detail.getProviderType().contains(SourceTypeEnum.PLATFORM.getCode())) {
                    record.setPlay(detail.getState() ==YesOrNoEnum.YES && !detail.getDelFlag()?YesOrNoEnum.NO:YesOrNoEnum.YES);
                }
            }else {
                record.setPlay(detail.getPlay()==YesOrNoEnum.YES?YesOrNoEnum.NO:YesOrNoEnum.YES);
            }
        }
        return page;
    }

    @Override
    public IPage<StudentMusicSheetOrderVo> selectStudentOrderPage(IPage<StudentMusicSheetOrderVo> page, StudentMusicSheetOrderSearch query) {
        return page.setRecords(baseMapper.selectStudentOrderPage(page, query));
    }

    @Override
    public IPage<TeacherMusicSheetVo> selectTeacherPage(IPage<TeacherMusicSheetVo> page, TeacherMusicSheetSearch query) {
        return page.setRecords(baseMapper.selectTeacherPage(page, query));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id) {
        MusicSheet musicSheet = this.lambdaQuery().eq(MusicSheet::getCbsMusicSheetId, id).last("limit 1").one();
        if (musicSheet == null) {
            throw new BizException("曲目不存在");
        }
        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = this.getMusicSheetApplicationQuery();
        query.setMusicSheetIds(Collections.singletonList(musicSheet.getCbsMusicSheetId()));
        query.setRows(1);
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows = this.queryCbsMusicSheetApplication(query);
        if (CollectionUtils.isEmpty(rows)) {
            throw new BizException("获取曲目信息失败");
        }
        CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication = rows.get(0);
        R<JSONObject> jsonObjectR = musicFeignClientService.musicSheetApplicationExtendDel(musicSheetApplication.getApplicationExtendId());
        if (jsonObjectR.getCode() != 200) {
            throw new BizException("曲目删除失败,{}", jsonObjectR.getMessage());
        }
        return true;
    }

    @Override
    public Integer countTeacherMusicSheet(SysUser sysUser) {
        return this.lambdaQuery()
                .eq(MusicSheet::getAuditStatus, AuthStatusEnum.PASS)
                .eq(MusicSheet::getCreateBy, sysUser.getId())
                .eq(MusicSheet::getState, YesOrNoEnum.YES)
                .eq(MusicSheet::getDelFlag, YesOrNoEnum.NO)
                .eq(MusicSheet::getSourceType, SourceTypeEnum.TEACHER.getCode())
                .count();
    }

    @Override
    public HttpResponseResult<OrderCreateRes> buyMusicSheetCheck(OrderReq.OrderReqInfo orderReqInfo) {

        // 下单前的验证
        getSysUser(orderReqInfo.getUserId());

        MusicSheetPayDto musicSheetPayDto = JSON.parseObject(
                JSON.toJSONString(orderReqInfo.getBizContent()), MusicSheetPayDto.class);

        OrderCreateRes orderCreateRes = new OrderCreateRes();
        orderCreateRes.setGoodType(orderCreateRes.getGoodType());
        orderCreateRes.setGoodNum(1);
        orderCreateRes.setOrderType(orderReqInfo.getOrderType());

        switch (orderReqInfo.getGoodType()) {
            case MUSIC: // 单曲
                {
                    MusicSheet musicSheet = this.getById(musicSheetPayDto.getMusicSheetId());
                    if (musicSheet == null) {
                        throw new BizException("不存在曲目信息");
                    }

                    orderCreateRes.setRes(true);
                    if (!musicSheet.getSourceType().getCode().equals(SourceTypeEnum.PLATFORM.getCode())) {
                        orderCreateRes.setMerchId(musicSheet.getUserId());
                    }
                    orderCreateRes.setSourceType(musicSheet.getSourceType());


                    orderCreateRes.setBizId(musicSheet.getId());
                    orderCreateRes.setOriginalPrice(musicSheet.getMusicPrice());
                    orderCreateRes.setExpectPrice(musicSheet.getMusicPrice());
                }
                break;
            case ALBUM: // 专辑
                {
                    MusicAlbum album = musicAlbumMapper.selectById(musicSheetPayDto.getMusicSheetId());

                    if (Objects.isNull(album)) {
                        throw new BizException("无效的专辑信息");
                    }
                    orderCreateRes.setSourceType(SourceTypeEnum.PLATFORM);

                    orderCreateRes.setRes(true);
                    orderCreateRes.setMerchId(0L);
                    orderCreateRes.setBizId(album.getId());
                    orderCreateRes.setOriginalPrice(BigDecimal.valueOf(album.getAlbumPrice()));
                    orderCreateRes.setExpectPrice(BigDecimal.valueOf(album.getAlbumPrice()));
                }
                break;
            default:
                break;
        }

        // 检查已经购买，抛出已购买异常
        checkoutPay(orderReqInfo.getUserId(), musicSheetPayDto.getMusicSheetId(), musicSheetPayDto.getClientType(),
                PurchaseRecordTypeEnum.valueOf(orderReqInfo.getGoodType().getCode()));

        return HttpResponseResult.succeed(orderCreateRes);

    }

    /**
     * 检查是否已购买当前曲目
     *
     * @param userId       用户id
     * @param musicSheetId 曲目id
     * @param clientType
     */
    private void checkoutPay(Long userId, Long musicSheetId, String clientType, PurchaseRecordTypeEnum purchaseType) {
        List<MusicSheetPurchaseRecord> list = musicSheetPurchaseRecordService
                .lambdaQuery()
                .eq(MusicSheetPurchaseRecord::getMusicSheetId, musicSheetId)
                .eq(MusicSheetPurchaseRecord::getStudentId, userId)
                .eq(MusicSheetPurchaseRecord::getClientType, clientType)
                .eq(MusicSheetPurchaseRecord::getPurchaseType, purchaseType)
                .eq(MusicSheetPurchaseRecord::getOrderStatus, OrderStatusEnum.PAID)
                .list();
        if (!CollectionUtils.isEmpty(list)) {
            throw new BizException(MessageFormat.format("已经购买了当前{0}", purchaseType.getMsg()));
        }
    }

    @Override
    @Transactional
    public void buyMusicSheetSuccess(UserOrderDetailVo userOrderDetailVo) {
        // 曲目服务费比例
        String musicSheetServiceFee = sysConfigService.findConfigValue(SysConfigConstant.MUSIC_SHEET_SERVICE_FEE);
        BigDecimal serviceFee = new BigDecimal(musicSheetServiceFee).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
        //支付金额
        BigDecimal actualPrice = userOrderDetailVo.getActualPrice();
        BigDecimal expectPrice = userOrderDetailVo.getExpectPrice();

        //服务费  原价的平台服务费 ，减去优惠券金额
        BigDecimal serviceFeeAmount = expectPrice.multiply(serviceFee).subtract(userOrderDetailVo.getCouponAmount()).setScale(2, RoundingMode.HALF_UP);
        if (serviceFeeAmount.compareTo(BigDecimal.ZERO) <0) {
            serviceFeeAmount = BigDecimal.ZERO;
        }

        // 保存购买记录
        addMusicSheetPurchaseRecord(userOrderDetailVo, actualPrice, serviceFeeAmount);

        // 曲目判断老师收入
        if (userOrderDetailVo.getOrderType().equals(OrderTypeEnum.MUSIC)) {
            MusicSheet musicSheet = this.getById(userOrderDetailVo.getBizId());
            if (!musicSheet.getSourceType().getCode().equals(SourceTypeEnum.PLATFORM.getCode())) {

                // 老师收入
                BigDecimal teacherAmount = BigDecimal.ONE.subtract(serviceFee).multiply(expectPrice).setScale(2, RoundingMode.HALF_UP);

                // 判断是否结算给老师，不结算，不写入老师入账记录
                Teacher teacher = teacherService.getById(musicSheet.getUserId());
                if (teacher != null && teacher.getIsSettlement() != null && teacher.getIsSettlement()) {
                    // 加入账户
                    addTeacherAccount(userOrderDetailVo, teacherAmount, userOrderDetailVo.getBizId());
                }
            }
        }

        // 消息通知
        try {
            sendBuyMessage(userOrderDetailVo.getMerchId(), userOrderDetailVo.getUserId(), userOrderDetailVo.getBizId(), userOrderDetailVo.getOrderClient(),userOrderDetailVo.getOrderType());
        } catch (Exception e) {
            log.warn("购买曲目消息推送失败 {}", e.getMessage());
        }
    }

    /**
     * 发送购买消息通知
     *  @param teacherId    老师id
     * @param studentId    学生id
     * @param musicSheetId 曲目id
     * @param orderClient
     * @param orderType
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean sendBuyMessage(Long teacherId, Long studentId, Long musicSheetId, ClientEnum orderClient, OrderTypeEnum orderType) {

        String name = null;
        MusicSheet musicSheet = null;
        MessageTypeEnum messageType = null;
        MessageTypeEnum smsMessageType = null;
        if (orderType.equals(OrderTypeEnum.MUSIC)) {
            musicSheet = this.getById(musicSheetId);
            name = musicSheet.getMusicSheetName();
            if (orderClient.equals(ClientEnum.STUDENT)) {
                messageType = MessageTypeEnum.STUDENT_BUY_MUSIC_SHEET_SUCCESS;
            } else {
                messageType = MessageTypeEnum.TEACHER_BUY_MUSIC_SHEET_SUCCESS;
            }
            smsMessageType = MessageTypeEnum.SMS_STUDENT_BUY_MUSIC_SHEET_SUCCESS;
        } else if (orderType.equals(OrderTypeEnum.ALBUM)) {
            name = musicAlbumService.getById(musicSheetId).getAlbumName();
            if (orderClient.equals(ClientEnum.STUDENT)) {
                messageType = MessageTypeEnum.STUDENT_BUY_MUSIC_ALBUM_SUCCESS;
            } else {
                messageType = MessageTypeEnum.TEACHER_BUY_MUSIC_ALBUM_SUCCESS;
            }
            smsMessageType = MessageTypeEnum.SMS_STUDENT_BUY_MUSIC_ALBUM_SUCCESS;
        } else {
            return false;
        }

        SysUser student = sysUserFeignService.queryUserById(studentId);
        if (orderType.equals(OrderTypeEnum.MUSIC) && musicSheet.getSourceType().equals(SourceTypeEnum.TEACHER)) {
            SysUser teacher = sysUserFeignService.queryUserById(teacherId);
            if (StringUtil.isEmpty(teacher.getPhone())) {
                log.warn("teacher id {} name {} 手机号不存在，消息推送失败", teacher.getId(), teacher.getUsername());
            }

            // 推送老师
            Map<Long, String> teacherReceivers = new HashMap<>();
            teacherReceivers.put(teacherId, teacher.getPhone());

            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.STUDENT_BUY_TEACHER_MUSIC_SHEET, teacherReceivers, null,
                                               0, null, ClientEnum.TEACHER.getCode(), student.getUsername(), name);

        }
        // 推送学生
        Map<Long, String> studentReceivers = new HashMap<>(1);
        studentReceivers.put(studentId,student.getPhone());

        try {
            Student studentInfo = studentService.getById(studentId);
            if (studentInfo != null && orderClient.equals(ClientEnum.STUDENT) &&
                    studentInfo.getTenantId() != null && studentInfo.getTenantId() > 0 && orderType.equals(OrderTypeEnum.MUSIC)) {
                try {
                    sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TENANT_MUSIC_BUY,
                            studentReceivers, null, 0, null, ClientEnum.TENANT_STUDENT.getCode(), name);
                } catch (Exception e) {
                    log.error("学生购买曲目推送失败,", e);
                }
            } else {

//                String url = sysMessageService.selectConfigUrl(messageType.getCode());

                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG,
                        messageType, studentReceivers, null,
                        0, null, orderClient.getCode(), name);
                // 推送学生
                Map<Long, String> studentSMS = new HashMap<>();
                studentSMS.put(studentId, student.getPhone());
                // 推送短信
//                url = sysMessageService.selectConfigUrl(smsMessageType.getCode());
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, smsMessageType,
                        studentSMS, null, 0, null, null, name);
            }
        } catch (Exception e) {
            log.error("购买曲目消息推送失败,", e);
        }
        return true;
    }

    /**
     * 保存购买记录
     *
     * @param userOrderDetailVo 订单信息
     * @param actualPrice       付款价格
     * @param serviceFeeAmount  服务费
     */
    @Transactional
    @Override
    public void addMusicSheetPurchaseRecord(UserOrderDetailVo userOrderDetailVo, BigDecimal actualPrice, BigDecimal serviceFeeAmount) {
        MusicSheetPurchaseRecord musicSheetPurchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                userOrderDetailVo.getUserId(),
                userOrderDetailVo.getBizId(),
                userOrderDetailVo.getOrderClient(),
                PurchaseRecordTypeEnum.valueOf(userOrderDetailVo.getOrderType().getCode()));
        if (musicSheetPurchaseRecord == null) {
            musicSheetPurchaseRecord = new MusicSheetPurchaseRecord();
        }
        musicSheetPurchaseRecord.setClientType(userOrderDetailVo.getOrderClient());
        musicSheetPurchaseRecord.setMusicSheetId(userOrderDetailVo.getBizId());
        musicSheetPurchaseRecord.setOrderNo(userOrderDetailVo.getOrderNo());
        musicSheetPurchaseRecord.setPurchasePrice(actualPrice);
        musicSheetPurchaseRecord.setPurchaseTime(new Date());
        musicSheetPurchaseRecord.setTeacherId(userOrderDetailVo.getMerchId());
        musicSheetPurchaseRecord.setOriginalPrice(userOrderDetailVo.getOriginalPrice());
        musicSheetPurchaseRecord.setMusicSheetServiceFee(serviceFeeAmount);
        musicSheetPurchaseRecord.setOrderStatus(OrderStatusEnum.PAID);
        musicSheetPurchaseRecord.setStudentId(userOrderDetailVo.getUserId());
        musicSheetPurchaseRecord.setPurchaseType(PurchaseRecordTypeEnum.valueOf(userOrderDetailVo.getGoodType().getCode()));
        musicSheetPurchaseRecord.setCourseMusicAlbumId(0L);
        musicSheetPurchaseRecordService.saveOrUpdate(musicSheetPurchaseRecord);
    }

    /**
     * 添加金额到老师账户
     *
     * @param userOrderDetailVo 订单信息
     * @param transAmount       老师收入
     * @param musicSheetId      曲目id
     */
    private void addTeacherAccount(UserOrderDetailVo userOrderDetailVo, BigDecimal transAmount,
                                   Long musicSheetId) {
        //获取账期时间
        Date accountPeriodTime = userOrderService.getAccountPeriodTime(userOrderDetailVo);

        //插入老师账户变更记录-老师预收
        userAccountService.accountRecord(
                new UserAccountRecordDto(userOrderDetailVo.getMerchId(), PostStatusEnum.WAIT, transAmount, InOrOutEnum.IN,
                        AccountBizTypeEnum.MUSIC, musicSheetId, userOrderDetailVo.getGoodName(), userOrderDetailVo.getOrderNo(), userOrderDetailVo.getUserId(), accountPeriodTime));

        // 插入平台账户 支出
        PlatformCashAccountRecord platformCashAccountRecord = new PlatformCashAccountRecord(userOrderDetailVo.getUserId(), transAmount,
                                                                                            InOrOutEnum.OUT, PostStatusEnum.WAIT, AccountBizTypeEnum.MUSIC, musicSheetId,
                                                                                            userOrderDetailVo.getOrderNo(), accountPeriodTime);
        platformCashAccountRecordService.save(platformCashAccountRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderAfterSheet(UserOrderDetailVo userOrderDetailVo) {
        // 保存购买记录
        MusicSheetPurchaseRecord musicSheetPurchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                userOrderDetailVo.getUserId(),
                userOrderDetailVo.getBizId(),
                userOrderDetailVo.getOrderClient(),
                PurchaseRecordTypeEnum.valueOf(userOrderDetailVo.getOrderType().getCode()));
        if (musicSheetPurchaseRecord == null) {
            musicSheetPurchaseRecord = new MusicSheetPurchaseRecord();
        }
        musicSheetPurchaseRecord.setClientType(userOrderDetailVo.getOrderClient());
        musicSheetPurchaseRecord.setMusicSheetId(userOrderDetailVo.getBizId());
        musicSheetPurchaseRecord.setOrderNo(userOrderDetailVo.getOrderNo());
        musicSheetPurchaseRecord.setTeacherId(userOrderDetailVo.getMerchId());
        musicSheetPurchaseRecord.setOriginalPrice(userOrderDetailVo.getOriginalPrice());
        musicSheetPurchaseRecord.setOrderStatus(OrderStatusEnum.WAIT_PAY);
        musicSheetPurchaseRecord.setStudentId(userOrderDetailVo.getUserId());
        musicSheetPurchaseRecord.setPurchaseType(PurchaseRecordTypeEnum.valueOf(userOrderDetailVo.getGoodType().getCode()));

        musicSheetPurchaseRecordService.saveOrUpdate(musicSheetPurchaseRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void buyMusicSheetCancel(UserOrderDetailVo userOrderDetailVo) {
        MusicSheetPurchaseRecord musicSheetPurchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                userOrderDetailVo.getUserId(),
                userOrderDetailVo.getBizId(),
                userOrderDetailVo.getOrderClient(),
                PurchaseRecordTypeEnum.valueOf(userOrderDetailVo.getGoodType().getCode()));

        if (musicSheetPurchaseRecord == null) return;
        musicSheetPurchaseRecordService.removeById(musicSheetPurchaseRecord.getId());
    }

    @Override
    public Integer getTeacherMusicSheetCount(Long userId) {
        return baseMapper.selectTeacherMusicSheetCount(userId);

    }

    @Override
    public HomeMusicSheetVo getMusicSheetHome() {

        HomeMusicSheetVo homeMusicSheetVo = baseMapper.selectMusicNum();
        homeMusicSheetVo.setMusicSheetSmallList(baseMapper.selectPayMusicSheet());

        return homeMusicSheetVo;
    }

    @Override
    public MusicSheetWebsiteDetailVo websiteDetail(Long musicSheetId, SysUser sysUser, ClientEnum clientType) {
        MusicSheetDetailVo detail = detail(musicSheetId, null, null);
        if (detail == null) {
            throw new BizException("曲目不存在");
        }
        MusicSheetWebsiteDetailVo musicSheetWebsiteDetailVo = new MusicSheetWebsiteDetailVo();
        BeanUtils.copyProperties(detail, musicSheetWebsiteDetailVo);

        // 老师信息
        TeacherVo teacherVo = teacherService.detail(detail.getUserId());
        TeacherMusicSheetListVo teacherMusicSheetListVo = new TeacherMusicSheetListVo();
        teacherMusicSheetListVo.setUserAvatar(teacherVo.getAvatar());
        teacherMusicSheetListVo.setUserName(teacherVo.getUsername());
        teacherMusicSheetListVo.setUserId(teacherVo.getUserId());
        teacherMusicSheetListVo.setEntryFlag(teacherVo.getEntryFlag());
        teacherMusicSheetListVo.setMusicianFlag(teacherVo.getMusicianFlag());
        teacherMusicSheetListVo.setTag(teacherVo.getTag());
        teacherMusicSheetListVo.setVipType(teacherVo.getVipType());

        TeacherTotal total = totalService.getTotalById(detail.getUserId());
        if (total != null) {
            teacherMusicSheetListVo.setFansNum(total.getFansNum());
        }
        teacherMusicSheetListVo.setIsVip(teacherVo.getIsVip());

        if (sysUser != null) {
            // 老师关注
            StudentStar studentStar = studentStarService.getByStudentIdAndTeacherId(sysUser.getId(), teacherVo.getUserId());
            if (studentStar != null) {
                teacherMusicSheetListVo.setStar(YesOrNoEnum.YES);
            }

            // 曲目收藏
            List<MusicFavorite> favorite = musicFavoriteService.getFavorite(sysUser.getId(), detail.getId(), clientType,"PLATFORM");
            if (!CollectionUtils.isEmpty(favorite)) {
                musicSheetWebsiteDetailVo.setFavorite(YesOrNoEnum.YES);
            }
        }
        Integer favoriteCount = detail.getFavoriteCount();
        if (favoriteCount == null) {
            favoriteCount = 0;
        }
        musicSheetWebsiteDetailVo.setFavoriteNum(Long.valueOf(favoriteCount));

        // 老师的曲目
        MusicSheetSearch musicSheetSearch = new MusicSheetSearch();
        musicSheetSearch.setCreateBy(teacherVo.getUserId());
        musicSheetSearch.setState(YesOrNoEnum.YES);
        musicSheetSearch.setAuditStatus(null);
        musicSheetSearch.setPage(1);
        musicSheetSearch.setRows(5);
        List<MusicSheetVo> musicSheetVos = baseMapper.selectPage(PageUtil.getPage(musicSheetSearch), musicSheetSearch);
        musicSheetVos = musicSheetVos .stream() .filter(musicAlbumVo -> !musicAlbumVo.getId()
                                                              .equals(musicSheetId))
                                                             .collect(Collectors.toList());
        if (musicSheetVos.size() > 4) {
            musicSheetVos = musicSheetVos.subList(0,4);
        }
        teacherMusicSheetListVo.setMusicSheetList(musicSheetVos);

        musicSheetWebsiteDetailVo.setTeacher(teacherMusicSheetListVo);
        return musicSheetWebsiteDetailVo;
    }

    @Override
    public TeacherAuditMusicSheetVo selectTeacherCount(Long userId) {
        return baseMapper.selectTeacherCount(userId);
    }

    @Override
    public List<TeacherTotalVo> queryTeacherTotal(Long userId) {
        return baseMapper.queryTeacherTotal(userId);
    }

    @Override
    public List<StudentTotalVo> queryStudentTotal(Long userId) {
        return baseMapper.queryStudentTotal(userId);
    }

    @Override
    public ShareProfitVo shareMusicSheetProfit(SysUser sysUser, Long musicSheetId) {
        ShareProfitVo result = new ShareProfitVo();
        MusicSheetDetailVo musicSheet = detail(musicSheetId, null, null);

        YesOrNoEnum discount = YesOrNoEnum.NO;
        if (musicSheet.getPaymentType().contains(ChargeTypeEnum.VIP.getCode())) {
            ActivityPlanVo activityPlanVo = activityPlanService.activityShare(ActivityShareEnum.VIP, sysUser.getId());
            if (activityPlanVo != null) {
                result.setActivityId(activityPlanVo.getId());
                discount = YesOrNoEnum.YES;
            }
        } else if (musicSheet.getPaymentType().contains(ChargeTypeEnum.CHARGE.getCode())) {
            ActivityPlanVo activityPlanVo = activityPlanService.activityShare(ActivityShareEnum.MUSIC_SHEET,
                                                                              sysUser.getId());
            if (activityPlanVo != null) {
                result.setActivityId(activityPlanVo.getId());
                discount = YesOrNoEnum.YES;
            }
        }
        result.setDiscount(discount);
        result.setTeacherId(sysUser.getId());
        result.setType("MUSIC");
        result.setMusicSheet(musicSheet);
        result.setAvatar(sysUser.getAvatar());
        result.setName(sysUser.getUsername());
        String teacherMusicShareProfitUrl = sysConfigService.findConfigValue(SysConfigConstant.TEACHER_MUSIC_SHEET_SHARE_PROFIT_URL);
        result.setUrl(MessageFormatter.arrayFormat(teacherMusicShareProfitUrl, musicSheetId, sysUser.getId()));
        return result;
    }

    @Override
    public Boolean top(Long musicSheetId) {
        MusicSheet musicSheet = getById(musicSheetId);
        if (musicSheet == null || musicSheet.getCbsMusicSheetId() == null) {
            throw new BizException("曲目不存在");
        }
        if (YesOrNoEnum.NO.equals(musicSheet.getState())) {
            throw new BizException("下架的曲目不能置顶");
        }
        CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend addMusicSheetApplicationExtend = new CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend();
        addMusicSheetApplicationExtend.setApplicationId(applicationId);
        addMusicSheetApplicationExtend.setMusicSheetId(musicSheet.getCbsMusicSheetId());
        addMusicSheetApplicationExtend.setTopFlag(musicSheet.getTopFlag() != YesOrNoEnum.YES);
        addMusicSheetApplicationExtend.setMusicTagIds(musicSheet.getMusicTag());
        addMusicSheetApplicationExtend.setMusicPrice(musicSheet.getMusicPrice());
        addMusicSheetApplicationExtend.setPaymentType(musicSheet.getPaymentType());
        addMusicSheetApplicationExtend.setAvailableType(StringUtils.isNotBlank(musicSheet.getProviderType())&& musicSheet.getProviderType().equals("TENANT")
            ?EMusicAvailableType.ORG:EMusicAvailableType.PLATFORM);
        addMusicSheetApplicationExtend.setExquisiteFlag(musicSheet.getExquisiteFlag() == YesOrNoEnum.YES);
        addMusicSheetApplicationExtend.setSortNo(musicSheet.getSortNumber());
        addMusicSheetApplicationExtend.setIsConvertibleScore(musicSheet.getNotation() == YesOrNoEnum.YES);
        if(StringUtils.isNotEmpty(musicSheet.getScoreType())){
            addMusicSheetApplicationExtend.setScoreType(EDefaultScoreType.valueOf(musicSheet.getScoreType()));
        }
        R<JSONObject> jsonObjectR = musicFeignClientService.musicSheetApplicationExtendUpdate(addMusicSheetApplicationExtend);
        if (jsonObjectR.getCode() != 200) {
            throw new BizException("修改失败,{}",jsonObjectR.getMessage());
        }
        return true;
    }

    @Override
    public Boolean stateList(ReasonDto reasonDto) {
        List<Long> musicSheets = Arrays.stream(reasonDto.getMusicSheetIds().split(",")).map(Long::parseLong).collect(Collectors.toList());
        List<MusicSheet> musicSheetList = musicSheetService.lambdaQuery().in(MusicSheet::getId, musicSheets).list();

        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = this.getMusicSheetApplicationQuery();
        query.setMusicSheetIds(musicSheetList.stream().map(MusicSheet::getCbsMusicSheetId).collect(Collectors.toList()));
        query.setRows(musicSheets.size());
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows = this.queryCbsMusicSheetApplication(query);
        if (CollectionUtils.isEmpty(rows)) {
            throw new BizException("获取曲目信息失败");
        }
        String applicationExtendIds = rows.stream().map(e -> e.getApplicationExtendId().toString()).collect(Collectors.joining(","));
        CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtendStatus extendStatus = new CbsMusicSheetApplicationExtendClientWrapper.MusicSheetApplicationExtendStatus();
        extendStatus.setIds(applicationExtendIds);
        extendStatus.setStatus(reasonDto.getState()==YesOrNoEnum.YES);
        R<JSONObject> jsonObjectR = musicFeignClientService.musicSheetApplicationExtendStatus(extendStatus);
        if (jsonObjectR.getCode() != 200) {
            throw new BizException("修改曲目状态失败,{}", jsonObjectR.getMessage());
        }
        // 发送推送
        if (reasonDto.getState().equals(YesOrNoEnum.YES)){
            return true;
        }
        for (MusicSheet musicSheet : musicSheetList) {
             if (SourceTypeEnum.TEACHER.equals(musicSheet.getSourceType())) {
                 sendOutSaleMessage(reasonDto.getReason(),musicSheet);
             }
        }
        return true;
    }

    @Override
    public void initMusicSheetDetailVo(List<MusicSheetDetailVo> sheetDetailVos){
        if(CollectionUtils.isEmpty(sheetDetailVos)){
            return;
        }
        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = this.getMusicSheetApplicationQuery();
        query.setMusicSheetIds(sheetDetailVos.stream().map(MusicSheet::getCbsMusicSheetId).collect(Collectors.toList()));
        query.setRows(query.getMusicSheetIds().size());
        List<CbsMusicSheetWrapper.MusicSheetApplication> rows = this.queryCbsMusicSheetApplication(query);
        if (CollectionUtils.isEmpty(rows)){
            throw new BizException("查询曲谱信息失败");
        }
        Map<Long,CbsMusicSheetWrapper.MusicSheetApplication> musicSheetMap =
                rows.stream().collect(Collectors.toMap(CbsMusicSheetWrapper.MusicSheetApplication::getId, Function.identity()));
        for (MusicSheetDetailVo record : sheetDetailVos) {
            CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication = musicSheetMap.get(record.getCbsMusicSheetId());
            if(musicSheetApplication == null){
                continue;
            }
            record.setSubjectNames(musicSheetApplication.getSubjectNames());
            record.setMusicPrice(musicSheetApplication.getMusicPrice());
            record.setCbsMusicSheetId(musicSheetApplication.getId());
            record.setAudioType(AudioTypeEnum.valueOf(musicSheetApplication.getPlayMode().getCode()));
            record.setCanEvaluate(musicSheetApplication.getIsEvaluated() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
            record.setShowFingering(musicSheetApplication.getIsShowFingering() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
            record.setMusicTag(musicSheetApplication.getMusicTagIds());
            record.setMusicTagNames(musicSheetApplication.getMusicTagNames());
            record.setXmlFileUrl(musicSheetApplication.getXmlFileUrl());
            record.setMidiUrl(musicSheetApplication.getMidiFileUrl());
            record.setAuditVersion(musicSheetApplication.getAppAuditFlag() ? YesOrNoEnum.YES : YesOrNoEnum.NO);
            record.setHasBeat((musicSheetApplication.getIsPlayBeat() && !musicSheetApplication.getIsUseSystemBeat()) ? YesOrNoEnum.YES : YesOrNoEnum.NO);
            record.setExtConfigJson(musicSheetApplication.getExtConfigJson());
            record.setMusicJSON(musicSheetApplication.getMusicJson());
            record.setMusicJianSvg(musicSheetApplication.getMusicJianSvg());
            record.setMusicFirstSvg(musicSheetApplication.getMusicFirstSvg());
            record.setFirstTone(musicSheetApplication.getMusicFirstImg());
            record.setFixedTone(musicSheetApplication.getMusicJianImg());
            List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = musicSheetApplication.getMusicSheetAccompanimentList();
            if (CollectionUtils.isNotEmpty(accompanimentList)) {
                List<MusicSheetAccompaniment> background = new ArrayList<>();
                for (CbsMusicSheetWrapper.MusicSheetAccompaniment accompaniment : accompanimentList) {
                    MusicSheetAccompaniment musicSheetAccompaniment = new MusicSheetAccompaniment();
                    musicSheetAccompaniment.setAudioFileUrl(accompaniment.getAudioFileUrl());
                    musicSheetAccompaniment.setMusicPdfUrl(accompaniment.getMusicPdfUrl());
                    musicSheetAccompaniment.setFirstPdfUrl(accompaniment.getFirstPdfUrl());
                    musicSheetAccompaniment.setJianPdfUrl(accompaniment.getJianPdfUrl());
                    background.add(musicSheetAccompaniment);
                }
            }
        }
    }

    @Override
    public void setVirtualNumber() {
        List<MusicSheet> musicSheets = this.lambdaQuery().select(MusicSheet::getId,MusicSheet::getVirtualNumber)
                                               .eq(MusicSheet::getState, 1)
                                               .eq(MusicSheet::getDelFlag, false)
                                               .eq(MusicSheet::getAuditVersion,0)
                                               .eq(MusicSheet::getAuditStatus, AuthStatusEnum.PASS)
                .list();
        if (CollectionUtils.isEmpty(musicSheets)) {
            return;
        }
        //给每个曲目设置增长值
        String value = sysConfigService.findConfigValue(SysConfigConstant.MUSIC_SHEET_VIRTUAL_NUMBER);
        for (MusicSheet musicSheet : musicSheets) {
            int i = (int) (Math.random() * Integer.parseInt(value));
            musicSheet.setVirtualNumber(i + musicSheet.getVirtualNumber());
        }

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

    /**
     * 购买曲目专辑
     *
     * @param orderGoodsInfo
     * @return
     */
    @Override
    public void buyMusicSheetCheck(UserPaymentOrderWrapper.OrderGoodsInfo orderGoodsInfo) {

        // 下单前的验证
        getSysUser(orderGoodsInfo.getUserId());

        MusicSheetPayDto musicSheetPayDto = JSON.parseObject(
                JSON.toJSONString(orderGoodsInfo.getBizContent()), MusicSheetPayDto.class);


        UserOrderDetail userOrderDetail = JSON.parseObject(JSON.toJSONString(orderGoodsInfo), UserOrderDetail.class);

        userOrderDetail.setGoodUrl(userOrderService.getGoodUrlByType(orderGoodsInfo.getGoodType()));


        switch (orderGoodsInfo.getGoodType()) {
            case MUSIC: // 单曲
            {
                MusicSheet musicSheet = this.getById(musicSheetPayDto.getMusicSheetId());
                if (musicSheet == null) {
                    throw new BizException("不存在曲目信息");
                }

                if (!musicSheet.getSourceType().getCode().equals(SourceTypeEnum.PLATFORM.getCode())) {
                    userOrderDetail.setMerchId(musicSheet.getUserId());
                }


                userOrderDetail.setBizId(musicSheet.getId());
                userOrderDetail.setOriginalPrice(musicSheet.getMusicPrice());
                userOrderDetail.setExpectPrice(musicSheet.getMusicPrice());
            }
            break;
            case ALBUM: // 专辑
            {
                MusicAlbum album = musicAlbumMapper.selectById(musicSheetPayDto.getMusicSheetId());

                if (Objects.isNull(album)) {
                    throw new BizException("无效的专辑信息");
                }
                userOrderDetail.setBizId(album.getId());
                userOrderDetail.setOriginalPrice(BigDecimal.valueOf(album.getAlbumPrice()));
                userOrderDetail.setExpectPrice(BigDecimal.valueOf(album.getAlbumPrice()));
            }
            break;
            default:
                break;
        }
        userOrderDetail.setCouponAmount(BigDecimal.ZERO);
        userOrderDetail.setActualPrice(userOrderDetail.getExpectPrice());

        // 检查已经购买，抛出已购买异常
        checkoutPay(orderGoodsInfo.getUserId(), musicSheetPayDto.getMusicSheetId(), musicSheetPayDto.getClientType(),
                PurchaseRecordTypeEnum.valueOf(orderGoodsInfo.getGoodType().getCode()));

        orderGoodsInfo.setUserOrderDetail(userOrderDetail);


        // 设置金额入账去向
        Long teacherId = null;
        if (orderGoodsInfo.getGoodType().equals(GoodTypeEnum.MUSIC)) {
            MusicSheet musicSheet = this.getById(orderGoodsInfo.getUserOrderDetail().getBizId());
            if (musicSheet != null && musicSheet.getSourceType().equals(SourceTypeEnum.TEACHER)) {
                teacherId = musicSheet.getUserId();
            }
        }
        userOrderDetail.setAccountConfig(teacherService.teacherSettlementFrom(teacherId,orderGoodsInfo.getRecomUserId()).jsonString());
        // 存入缓存

    }


    /**
     * 购买曲目专辑
     *
     * @param orderGoodsInfo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderAfterSheet(UserPaymentOrderWrapper.OrderGoodsInfo orderGoodsInfo) {
        // 保存购买记录
        MusicSheetPurchaseRecord musicSheetPurchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                orderGoodsInfo.getUserId(),
                orderGoodsInfo.getBizId(),
                orderGoodsInfo.getPaymentClient(),
                PurchaseRecordTypeEnum.valueOf(orderGoodsInfo.getGoodType().getCode()));
        if (musicSheetPurchaseRecord == null) {
            musicSheetPurchaseRecord = new MusicSheetPurchaseRecord();
        }
        musicSheetPurchaseRecord.setClientType(orderGoodsInfo.getPaymentClient());
        musicSheetPurchaseRecord.setMusicSheetId(orderGoodsInfo.getBizId());
        musicSheetPurchaseRecord.setOrderNo(orderGoodsInfo.getOrderNo());
        musicSheetPurchaseRecord.setTeacherId(orderGoodsInfo.getUserOrderDetail().getMerchId());
        musicSheetPurchaseRecord.setOriginalPrice(orderGoodsInfo.getUserOrderDetail().getOriginalPrice());
        musicSheetPurchaseRecord.setOrderStatus(OrderStatusEnum.WAIT_PAY);
        musicSheetPurchaseRecord.setStudentId(orderGoodsInfo.getUserId());
        musicSheetPurchaseRecord.setPurchaseType(PurchaseRecordTypeEnum.valueOf(orderGoodsInfo.getGoodType().getCode()));

        musicSheetPurchaseRecordService.saveOrUpdate(musicSheetPurchaseRecord);
    }

    @Override
    public List<MusicSheetUploadCountVo> countByUser(List<Long> userIds) {
        return this.getDao().countByUser(userIds);
    }

    @Override
    public Map<Long, MusicSheet> getMapByIds(List<Long> bizIds) {
        if (CollectionUtils.isEmpty(bizIds)) {
            return new HashMap<>();
        }
        List<MusicSheet> sheetList = this.lambdaQuery()
                .in(MusicSheet::getId, bizIds)
                .list();
        if (CollectionUtils.isEmpty(sheetList)) {
            return new HashMap<>();
        }
        return sheetList.stream().collect(Collectors.toMap(MusicSheet::getId, Function.identity()));

    }

    @Override
    public MusicCompareWrapper.SearchData search(MusicCompareWrapper.MusicSearch queryInfo) {
        MusicCompareWrapper.SearchData searchData= new MusicCompareWrapper.SearchData();
        List<MusicCompareWrapper.MusicName> musicNames = new ArrayList<>();
        if (StringUtil.isEmpty(queryInfo.getType()) || queryInfo.getType().equals("MUSIC")) {

            // 查询曲目列表
            List<Long> musicIds = musicSheetDao.searchMusic(PageUtil.getPage(queryInfo),queryInfo);

            if (CollectionUtils.isNotEmpty(musicIds)) {


                MusicSheetSearch musicSheetSearch = new MusicSheetSearch();
                musicSheetSearch.setMusicSheetIdlist(musicIds);
                IPage<MusicSheetVo> musicSheetVoIPage = selectPage(PageUtil.getPage(queryInfo), musicSheetSearch);
                List<MusicSheetVo> records = musicSheetVoIPage.getRecords();
                if (CollectionUtils.isNotEmpty(records)) {
                    for (MusicSheetVo record : records) {
                        MusicCompareWrapper.MusicName musicName = new MusicCompareWrapper.MusicName();
                        musicName.setId(record.getId());
                        musicName.setName(record.getMusicSheetName());
                        musicName.setType("MUSIC");
                        musicName.setHotFlag(record.getHotFlag() != null?record.getHotFlag():YesOrNoEnum.NO);
                        musicName.setSort(Optional.ofNullable(record.getFavoriteCount()).orElse(0));
                        musicNames.add(musicName);
                    }
                    searchData.setMusic(PageUtil.pageInfo(musicSheetVoIPage));
                }

                // 是否关注
                if (queryInfo.getUserId() != null) {
                    List<MusicFavorite> musicFavoriteList = musicFavoriteService.lambdaQuery()
                            .eq(MusicFavorite::getUserId, queryInfo.getUserId())
                            .eq(MusicFavorite::getClientType, ClientEnum.STUDENT)
                            .in(MusicFavorite::getMusicSheetId, musicIds)
                            .list();
                    if (CollectionUtils.isNotEmpty(musicFavoriteList)) {
                        Set<Long> set = musicFavoriteList.stream()
                                .map(MusicFavorite::getMusicSheetId)
                                .collect(Collectors.toSet());
                        for (MusicCompareWrapper.MusicName record : musicNames) {
                            record.setFavorite(set.contains(record.getId()) ? YesOrNoEnum.YES : YesOrNoEnum.NO);
                        }
                    }
                }
            }
        }
        if (StringUtil.isEmpty(queryInfo.getType()) || queryInfo.getType().equals("ALBUM")) {

            // 查询专辑列表
            List<Long> albumIds = musicSheetDao.searchAlbum(PageUtil.getPage(queryInfo),queryInfo);

            if (CollectionUtils.isNotEmpty(albumIds)) {
                MusicAlbumSearch musicSheetSearch = new MusicAlbumSearch();
                musicSheetSearch.setAlbumIds(albumIds);
                IPage<MusicAlbumVo> musicAlbumVoIPage = musicAlbumService.selectPage(PageUtil.getPage(queryInfo), musicSheetSearch);
                List<MusicAlbumVo> records = musicAlbumVoIPage.getRecords();
                albumIds = albumFavoriteService.selectFavorite(queryInfo.getUserId(), albumIds, ClientEnum.STUDENT);
                for (MusicAlbumVo record : records) {
                    if (albumIds.contains(record.getId())) {
                        record.setFavorite(YesOrNoEnum.YES);
                    } else {
                        record.setFavorite(YesOrNoEnum.NO);
                    }
                }
                if (CollectionUtils.isNotEmpty(records)) {
                    for (MusicAlbumVo record : records) {
                        MusicCompareWrapper.MusicName musicName = new MusicCompareWrapper.MusicName();
                        musicName.setId(record.getId());
                        musicName.setName(record.getAlbumName());
                        musicName.setType("ALBUM");
                        musicName.setHotFlag(record.getHotFlag() !=null?record.getHotFlag():YesOrNoEnum.NO);
                        musicName.setFavorite(record.getFavorite());
                        musicName.setSort(Optional.ofNullable(record.getAlbumFavoriteCount()).orElse(0));
                        musicNames.add(musicName);
                    }
                    searchData.setAlbum(PageUtil.pageInfo(musicAlbumVoIPage));
                }
            }
        }
        musicNames.sort(Comparator.comparing(MusicCompareWrapper.MusicName::getSort).reversed());
        if (musicNames.size() > queryInfo.getRows()) {
            musicNames = musicNames.subList(0,queryInfo.getRows());
        }
        searchData.setMusicNames(musicNames);
        return searchData;
    }

    @Override
    public MusicCompareWrapper.SearchData searchTenant(MusicCompareWrapper.MusicSearch queryInfo) {
        MusicCompareWrapper.SearchData searchData = new MusicCompareWrapper.SearchData();
        List<MusicCompareWrapper.MusicName> musicNames = new ArrayList<>();
        searchData.setMusicNames(musicNames);

        // 查询学生机构
        Student student = studentService.getById(queryInfo.getUserId());
        if (student == null) {
            throw new BizException("学生不存在");
        }
        if (student.getTenantId() == null || student.getTenantId() == -1 || student.getTenantGroupId() == null) {
            return searchData;
        }
        // 查询机构 小组下的专辑
        TenantGroupAlbumWrapper.BuyTenantAlbumQuery query = new TenantGroupAlbumWrapper.BuyTenantAlbumQuery();
        query.setTenantGroupId(student.getTenantGroupId());

        List<TenantGroupAlbumWrapper.BuyTenantAlbum> buyAlbumInfo = tenantGroupAlbumMapper.getBuyAlbumInfo(query);
        List<Long> albumIds;
        if (CollectionUtils.isNotEmpty(buyAlbumInfo)) {
            albumIds = buyAlbumInfo.stream().map(TenantGroupAlbumWrapper.BuyTenantAlbum::getId).distinct().collect(Collectors.toList());
        } else {
            return searchData;
        }

        List<TenantAlbumMusic> list = tenantAlbumMusicMapper.getByAlbumAndEnable(albumIds);
        // 过滤出曲目
        List<SubjectTypeEnum> enumList = Lists.newArrayList(SubjectTypeEnum.MUSIC, SubjectTypeEnum.SUBJECT, SubjectTypeEnum.ENSEMBLE);
        list = list.stream().filter(tenantAlbumMusic -> enumList.contains(tenantAlbumMusic.getSubjectType())).collect(Collectors.toList());

        // 根据曲目ID分组
        Map<Long, List<Long>> map = list.stream()
            .collect(Collectors.groupingBy(TenantAlbumMusic::getMusicSheetId, Collectors.mapping(TenantAlbumMusic::getTenantAlbumId, Collectors.toList())));

        queryInfo.setTenantAlbumIds(albumIds);

        // 查询曲目列表
        List<Long> musicIds = musicSheetDao.searchMusic(PageUtil.getPage(queryInfo),queryInfo);
        if (CollectionUtils.isNotEmpty(musicIds)) {


            MusicSheetSearch musicSheetSearch = new MusicSheetSearch();
            musicSheetSearch.setMusicSheetIdlist(musicIds);
            musicSheetSearch.setProviderType(SourceTypeEnum.TENANT);
            IPage<MusicSheetVo> musicSheetVoIPage = selectPage(PageUtil.getPage(queryInfo), musicSheetSearch);
            List<MusicSheetVo> records = musicSheetVoIPage.getRecords();
            if (CollectionUtils.isNotEmpty(records)) {
                for (MusicSheetVo record : records) {
                    MusicCompareWrapper.MusicName musicName = new MusicCompareWrapper.MusicName();
                    musicName.setId(record.getId());
                    musicName.setName(record.getMusicSheetName());
                    musicName.setType("MUSIC");
                    musicName.setHotFlag(record.getHotFlag() != null?record.getHotFlag():YesOrNoEnum.NO);
                    musicName.setSort(Optional.ofNullable(record.getFavoriteCount()).orElse(0));
                    musicName.setTenantAlbumId(Optional.ofNullable(map.get(record.getId())).orElse(new ArrayList<>()).stream().map(String::valueOf).collect(Collectors.joining(",")));
                    musicNames.add(musicName);
                    record.setTenantAlbumId(Optional.ofNullable(map.get(record.getId())).orElse(new ArrayList<>()).stream().map(String::valueOf).collect(Collectors.joining(",")));

                }
                musicSheetVoIPage.setRecords(records);
                searchData.setMusic(PageUtil.pageInfo(musicSheetVoIPage));
            }

            // 是否关注
            if (queryInfo.getUserId() != null) {
                List<MusicFavorite> musicFavoriteList = musicFavoriteService.lambdaQuery()
                        .eq(MusicFavorite::getUserId, queryInfo.getUserId())
                        .eq(MusicFavorite::getClientType, ClientEnum.STUDENT)
                        .in(MusicFavorite::getMusicSheetId, musicIds)
                        .list();
                if (CollectionUtils.isNotEmpty(musicFavoriteList)) {
                    Set<Long> set = musicFavoriteList.stream()
                            .map(MusicFavorite::getMusicSheetId)
                            .collect(Collectors.toSet());
                    for (MusicCompareWrapper.MusicName record : musicNames) {
                        record.setFavorite(set.contains(record.getId()) ? YesOrNoEnum.YES : YesOrNoEnum.NO);
                    }
                }
            }
        }

        musicNames.sort(Comparator.comparing(MusicCompareWrapper.MusicName::getSort).reversed());
        return searchData;
    }

    @Override
    public Boolean updateMusicImg(MusicImgDto musicImgDto, Long musicSheetId) {
        MusicSheet musicSheet = new MusicSheet();
        musicSheet.setMusicImg(musicImgDto.getMusicImg());
        musicSheet.setFirstTone(musicImgDto.getFirstTone());
        musicSheet.setFixedTone(musicImgDto.getFixedTone());
        musicSheet.setId(musicSheetId);
        this.updateById(musicSheet);

        return true;
    }

    /**
     * 曲目修复
     *
     * @param musicImgDto  MusicImgDto
     * @param musicSheetId 曲目Id
     * @return Boolean
     */
    @Override
    public Boolean updateMusicCorrect(MusicImgDto musicImgDto, Long musicSheetId) {
        MusicSheet musicSheet = new MusicSheet();
        musicSheet.setCorrectTime(DateTime.now().toDate());
        musicSheet.setFixedTone(musicImgDto.getFixedTone());
        musicSheet.setId(musicSheetId);
        this.updateById(musicSheet);
        return true;
    }

    private void initAddMusicSheet(CbsMusicSheetWrapper.AddMusicSheet addMusicSheet){
        if (addMusicSheet.getSourceType() == null) {
            addMusicSheet.setSourceType(EMusicSourceType.PERSON);
        }
        if (addMusicSheet.getAppAuditFlag() == null) {
            addMusicSheet.setAppAuditFlag(false);
        }
        if (addMusicSheet.getIsPlayBeat() == null) {
            addMusicSheet.setIsPlayBeat(true);
        }
        if (addMusicSheet.getIsConvertibleScore() == null) {
            addMusicSheet.setIsConvertibleScore(true);
        }
        if (addMusicSheet.getIsUseSystemBeat() == null) {
            addMusicSheet.setIsUseSystemBeat(true);
        }
        if (addMusicSheet.getIsShowFingering() == null) {
            addMusicSheet.setIsShowFingering(true);
        }
        if (addMusicSheet.getStatus() == null) {
            addMusicSheet.setStatus(true);
        }
        if (addMusicSheet.getMusicSheetType() == null) {
            addMusicSheet.setMusicSheetType(EMusicSheetType.SINGLE);
        }
        if (addMusicSheet.getMusicCategoryId() == null) {
            addMusicSheet.setMusicCategoryId(-2L);
        }
        if (addMusicSheet.getAudioType() == null) {
            addMusicSheet.setAudioType(EAudioType.HOMEMODE);
        }
        if (addMusicSheet.getIsUseSystemBeat() == null) {
            addMusicSheet.setIsUseSystemBeat(true);
        }
    }

    @Override
    public MusicSheet initMusicSheet(CbsMusicSheetWrapper.AddMusicSheet addMusicSheet) {
        Long userId = sysUserFeignService.queryUserInfo().getId();
        addMusicSheet.setCreateBy(userId);
        addMusicSheet.setUpdateBy(userId);
        //初始化曲目默认值
        this.initAddMusicSheet(addMusicSheet);
        MusicSheet musicSheetAudit = new MusicSheet();
        musicSheetAudit.setUserId(userId);
        musicSheetAudit.setCreateBy(userId);
        musicSheetAudit.setUpdateBy(userId);
        musicSheetAudit.setSubmitAuditTime(new Date());
        musicSheetAudit.setProviderType(SourceTypeEnum.PLATFORM.getCode());
        musicSheetAudit.setSourceType(SourceTypeEnum.TEACHER);
        musicSheetAudit.setAuditStatus(AuthStatusEnum.DOING);
        musicSheetAudit.setState(YesOrNoEnum.NO);
        musicSheetAudit.setDelFlag(true);
        musicSheetAudit.setMusicSheetName(addMusicSheet.getName());
        musicSheetAudit.setMusicSubject(addMusicSheet.getSubjectIds());
        musicSheetAudit.setMusicSvg(addMusicSheet.getMusicSvg());
        musicSheetAudit.setComposer(addMusicSheet.getComposer());
        musicSheetAudit.setTitleImg(addMusicSheet.getMusicCover());
        musicSheetAudit.setExtConfigJson(addMusicSheet.getExtConfigJson());
        musicSheetAudit.setRemark(addMusicSheet.getRemark());
        if(addMusicSheet.getAudioType() != null){
            musicSheetAudit.setAccompanimentType(AccompanimentTypeEnum.valueOf(addMusicSheet.getAudioType().getCode()));
        }
        musicSheetAudit.setPlaySpeed(addMusicSheet.getPlaySpeed());
        if(addMusicSheet.getIsConvertibleScore() != null){
            musicSheetAudit.setNotation(addMusicSheet.getIsConvertibleScore()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getMusicSheetType() != null){
            musicSheetAudit.setMusicSheetType(MusicSheetTypeEnum.valueOf(addMusicSheet.getMusicSheetType().getCode()));
        }
        if(addMusicSheet.getPlayMode() != null){
            musicSheetAudit.setAudioType(AudioTypeEnum.valueOf(addMusicSheet.getPlayMode().getCode()));
        }
        if(addMusicSheet.getIsShowFingering() != null){
            musicSheetAudit.setShowFingering(addMusicSheet.getIsShowFingering()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getIsEvaluated() != null){
            musicSheetAudit.setCanEvaluate(addMusicSheet.getIsEvaluated()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        //兼容审核流程修改，是否自带节拍器
        if(addMusicSheet.getIsUseSystemBeat() == null || !addMusicSheet.getIsUseSystemBeat()){
            musicSheetAudit.setHasBeat(YesOrNoEnum.NO);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3);
        }else {
            musicSheetAudit.setHasBeat(YesOrNoEnum.YES);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3_METRONOME);
        }
        List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = addMusicSheet.getMusicSheetAccompanimentList();
        if (CollectionUtils.isNotEmpty(accompanimentList)) {
            musicSheetAudit.setMetronomeUrl(accompanimentList.get(0).getAudioFileUrl());
        }
        musicSheetAudit.setXmlFileUrl(addMusicSheet.getXmlFileUrl());
        musicSheetAudit.setMidiUrl(addMusicSheet.getMidiFileUrl());
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> extend = addMusicSheet.getAddMusicSheetApplicationExtend();
        if(CollectionUtils.isNotEmpty(extend)){
            CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend applicationExtend = extend.get(0);
            musicSheetAudit.setMusicTag(applicationExtend.getMusicTagIds());
            if(applicationExtend.getPaymentType() != null){
                musicSheetAudit.setPaymentType(applicationExtend.getPaymentType());
                musicSheetAudit.setChargeType(ChargeTypeEnum.valueOf(applicationExtend.getPaymentType()));
            }
            if(applicationExtend.getTopFlag() != null){
                musicSheetAudit.setTopFlag(applicationExtend.getTopFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            if(applicationExtend.getExquisiteFlag() != null){
                musicSheetAudit.setExquisiteFlag(applicationExtend.getExquisiteFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            musicSheetAudit.setSortNumber(applicationExtend.getSortNo());
            musicSheetAudit.setMusicPrice(applicationExtend.getMusicPrice());
        }
        return musicSheetAudit;
    }

    @Override
    public void initMusicSheetDetailVo(CbsMusicSheetWrapper.AddMusicSheet addMusicSheet, MusicSheetWrapper.MusicSheetDetailVo musicSheetAudit) {
        musicSheetAudit.setProviderType(SourceTypeEnum.TEACHER);
        musicSheetAudit.setSourceType(SourceTypeEnum.TEACHER);
        musicSheetAudit.setMusicSheetName(addMusicSheet.getName());
        musicSheetAudit.setMusicSubject(addMusicSheet.getSubjectIds());
        musicSheetAudit.setMusicSvg(addMusicSheet.getMusicSvg());
        musicSheetAudit.setComposer(addMusicSheet.getComposer());
        musicSheetAudit.setTitleImg(addMusicSheet.getMusicCover());
        musicSheetAudit.setExtConfigJson(addMusicSheet.getExtConfigJson());
        musicSheetAudit.setRemark(addMusicSheet.getRemark());
        if (CollectionUtils.isNotEmpty(addMusicSheet.getAddMusicSheetApplicationExtend())) {
            EDefaultScoreType scoreType = addMusicSheet.getAddMusicSheetApplicationExtend().get(0).getScoreType();
            musicSheetAudit.setScoreType(scoreType!=null?scoreType.name():EDefaultScoreType.STAVE.getCode());
        }
        if(addMusicSheet.getAudioType() != null){
            musicSheetAudit.setAccompanimentType(AccompanimentTypeEnum.valueOf(addMusicSheet.getAudioType().getCode()));
        }
        musicSheetAudit.setPlaySpeed(addMusicSheet.getPlaySpeed());
        if(addMusicSheet.getIsConvertibleScore() != null){
            musicSheetAudit.setNotation(addMusicSheet.getIsConvertibleScore()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getMusicSheetType() != null){
            musicSheetAudit.setMusicSheetType(MusicSheetTypeEnum.valueOf(addMusicSheet.getMusicSheetType().getCode()));
        }
        if(addMusicSheet.getPlayMode() != null){
            musicSheetAudit.setAudioType(AudioTypeEnum.valueOf(addMusicSheet.getPlayMode().getCode()));
        }
        if(addMusicSheet.getIsShowFingering() != null){
            musicSheetAudit.setShowFingering(addMusicSheet.getIsShowFingering()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getIsEvaluated() != null){
            musicSheetAudit.setCanEvaluate(addMusicSheet.getIsEvaluated()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        //兼容审核流程修改，是否自带节拍器
        if(addMusicSheet.getIsUseSystemBeat() == null || !addMusicSheet.getIsUseSystemBeat()){
            musicSheetAudit.setHasBeat(YesOrNoEnum.YES);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3_METRONOME);
        }else {
            musicSheetAudit.setHasBeat(YesOrNoEnum.NO);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3);
        }
        List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = addMusicSheet.getMusicSheetAccompanimentList();
        if (CollectionUtils.isNotEmpty(accompanimentList)) {
            musicSheetAudit.setMetronomeUrl(accompanimentList.get(0).getAudioFileUrl());
        }
        List<CbsMusicSheetWrapper.MusicSheetSound> soundList = addMusicSheet.getMusicSheetSoundList();
        if (CollectionUtils.isNotEmpty(soundList)) {
            List<MusicSheetAccompaniment> background = new ArrayList<>();
            for (CbsMusicSheetWrapper.MusicSheetSound sound : soundList) {
                MusicSheetAccompaniment musicSheetAccompaniment = new MusicSheetAccompaniment();
                musicSheetAccompaniment.setAudioFileUrl(sound.getAudioFileUrl());
                musicSheetAccompaniment.setSortNumber(sound.getSortNumber());
                musicSheetAccompaniment.setTrack(sound.getTrack());
                musicSheetAccompaniment.setMusicalInstrumentId(sound.getMusicalInstrumentId());
                background.add(musicSheetAccompaniment);
            }
            musicSheetAudit.setBackground(background);
        }
        musicSheetAudit.setXmlFileUrl(addMusicSheet.getXmlFileUrl());
        musicSheetAudit.setMidiUrl(addMusicSheet.getMidiFileUrl());
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> extend = addMusicSheet.getAddMusicSheetApplicationExtend();
        if(CollectionUtils.isNotEmpty(extend)){
            CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend applicationExtend = extend.get(0);
            musicSheetAudit.setMusicTag(applicationExtend.getMusicTagIds());
            if(applicationExtend.getPaymentType() != null){
                musicSheetAudit.setPaymentType(applicationExtend.getPaymentType());
                musicSheetAudit.setChargeType(ChargeTypeEnum.valueOf(applicationExtend.getPaymentType()));
            }
            if(applicationExtend.getTopFlag() != null){
                musicSheetAudit.setTopFlag(applicationExtend.getTopFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            if(applicationExtend.getExquisiteFlag() != null){
                musicSheetAudit.setExquisiteFlag(applicationExtend.getExquisiteFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            musicSheetAudit.setSortNumber(applicationExtend.getSortNo());
            musicSheetAudit.setMusicPrice(applicationExtend.getMusicPrice());
        }
    }

    @Override
    public void initMusicSheetDetailVo(CbsMusicSheetWrapper.AddMusicSheet addMusicSheet, MusicSheetWrapper.MusicSheetVo musicSheetAudit) {
        musicSheetAudit.setProviderType(SourceTypeEnum.TEACHER);
        musicSheetAudit.setSourceType(SourceTypeEnum.TEACHER);
        musicSheetAudit.setMusicSheetName(addMusicSheet.getName());
        musicSheetAudit.setMusicSubject(addMusicSheet.getSubjectIds());
        musicSheetAudit.setMusicSvg(addMusicSheet.getMusicSvg());
        musicSheetAudit.setComposer(addMusicSheet.getComposer());
        musicSheetAudit.setTitleImg(addMusicSheet.getMusicCover());
        musicSheetAudit.setExtConfigJson(addMusicSheet.getExtConfigJson());
        musicSheetAudit.setRemark(addMusicSheet.getRemark());
        if(addMusicSheet.getAudioType() != null){
            musicSheetAudit.setAccompanimentType(AccompanimentTypeEnum.valueOf(addMusicSheet.getAudioType().getCode()));
        }
        musicSheetAudit.setPlaySpeed(addMusicSheet.getPlaySpeed());
        if(addMusicSheet.getIsConvertibleScore() != null){
            musicSheetAudit.setNotation(addMusicSheet.getIsConvertibleScore()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getMusicSheetType() != null){
            musicSheetAudit.setMusicSheetType(MusicSheetTypeEnum.valueOf(addMusicSheet.getMusicSheetType().getCode()));
        }
        if(addMusicSheet.getPlayMode() != null){
            musicSheetAudit.setAudioType(AudioTypeEnum.valueOf(addMusicSheet.getPlayMode().getCode()));
        }
        if(addMusicSheet.getIsShowFingering() != null){
            musicSheetAudit.setShowFingering(addMusicSheet.getIsShowFingering()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getIsEvaluated() != null){
            musicSheetAudit.setCanEvaluate(addMusicSheet.getIsEvaluated()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        //兼容审核流程修改，是否自带节拍器
        if(addMusicSheet.getIsUseSystemBeat() == null || !addMusicSheet.getIsUseSystemBeat()){
            musicSheetAudit.setHasBeat(YesOrNoEnum.YES);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3_METRONOME);
        }else {
            musicSheetAudit.setHasBeat(YesOrNoEnum.NO);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3);
        }
        List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = addMusicSheet.getMusicSheetAccompanimentList();
        if (CollectionUtils.isNotEmpty(accompanimentList)) {
            musicSheetAudit.setMetronomeUrl(accompanimentList.get(0).getAudioFileUrl());
        }
        musicSheetAudit.setXmlFileUrl(addMusicSheet.getXmlFileUrl());
        musicSheetAudit.setMidiUrl(addMusicSheet.getMidiFileUrl());
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> extend = addMusicSheet.getAddMusicSheetApplicationExtend();
        if(CollectionUtils.isNotEmpty(extend)){
            CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend applicationExtend = extend.get(0);
            musicSheetAudit.setMusicTag(applicationExtend.getMusicTagIds());
            if(applicationExtend.getPaymentType() != null){
                musicSheetAudit.setPaymentType(applicationExtend.getPaymentType());
                musicSheetAudit.setChargeType(ChargeTypeEnum.valueOf(applicationExtend.getPaymentType()));
            }

            EDefaultScoreType scoreType = addMusicSheet.getAddMusicSheetApplicationExtend().get(0).getScoreType();
            musicSheetAudit.setScoreType(scoreType!=null?scoreType.name():EDefaultScoreType.STAVE.getCode());
            if(applicationExtend.getTopFlag() != null){
                musicSheetAudit.setTopFlag(applicationExtend.getTopFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            if(applicationExtend.getExquisiteFlag() != null){
                musicSheetAudit.setExquisiteFlag(applicationExtend.getExquisiteFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            musicSheetAudit.setSortNumber(applicationExtend.getSortNo());
            musicSheetAudit.setMusicPrice(applicationExtend.getMusicPrice());
        }
    }

    @Override
    public void initMusicSheetDetailVo(CbsMusicSheetWrapper.AddMusicSheet addMusicSheet, TeacherMusicSheetVo musicSheetAudit) {
        musicSheetAudit.setMusicSheetName(addMusicSheet.getName());
        musicSheetAudit.setComposer(addMusicSheet.getComposer());
        musicSheetAudit.setTitleImg(addMusicSheet.getMusicCover());
        if(addMusicSheet.getAudioType() != null){
            musicSheetAudit.setAccompanimentType(AccompanimentTypeEnum.valueOf(addMusicSheet.getAudioType().getCode()));
        }
        musicSheetAudit.setPlaySpeed(addMusicSheet.getPlaySpeed());
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> extend = addMusicSheet.getAddMusicSheetApplicationExtend();
        if(CollectionUtils.isNotEmpty(extend)){
            CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend applicationExtend = extend.get(0);
            musicSheetAudit.setMusicTag(applicationExtend.getMusicTagIds());
            if(applicationExtend.getExquisiteFlag() != null){
                musicSheetAudit.setExquisiteFlag(applicationExtend.getExquisiteFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            musicSheetAudit.setMusicPrice(applicationExtend.getMusicPrice());
        }
    }
    @Override
    public void initMusicSheetDetailVo(CbsMusicSheetWrapper.AddMusicSheet addMusicSheet, MusicSheetDetailVo musicSheetAudit) {
        musicSheetAudit.setProviderType(SourceTypeEnum.PLATFORM.getCode());
        musicSheetAudit.setSourceType(SourceTypeEnum.TEACHER);
        musicSheetAudit.setMusicSheetName(addMusicSheet.getName());
        musicSheetAudit.setMusicSubject(addMusicSheet.getSubjectIds());
        musicSheetAudit.setMusicSvg(addMusicSheet.getMusicSvg());
        musicSheetAudit.setComposer(addMusicSheet.getComposer());
        musicSheetAudit.setTitleImg(addMusicSheet.getMusicCover());
        musicSheetAudit.setExtConfigJson(addMusicSheet.getExtConfigJson());
        musicSheetAudit.setRemark(addMusicSheet.getRemark());
        if(addMusicSheet.getAudioType() != null){
            musicSheetAudit.setAccompanimentType(AccompanimentTypeEnum.valueOf(addMusicSheet.getAudioType().getCode()));
        }
        musicSheetAudit.setPlaySpeed(addMusicSheet.getPlaySpeed());
        if(addMusicSheet.getIsConvertibleScore() != null){
            musicSheetAudit.setNotation(addMusicSheet.getIsConvertibleScore()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getMusicSheetType() != null){
            musicSheetAudit.setMusicSheetType(MusicSheetTypeEnum.valueOf(addMusicSheet.getMusicSheetType().getCode()));
        }
        if(addMusicSheet.getPlayMode() != null){
            musicSheetAudit.setAudioType(AudioTypeEnum.valueOf(addMusicSheet.getPlayMode().getCode()));
        }
        if(addMusicSheet.getIsShowFingering() != null){
            musicSheetAudit.setShowFingering(addMusicSheet.getIsShowFingering()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        if(addMusicSheet.getIsEvaluated() != null){
            musicSheetAudit.setCanEvaluate(addMusicSheet.getIsEvaluated()? YesOrNoEnum.YES: YesOrNoEnum.NO);
        }
        //兼容审核流程修改，是否自带节拍器
        if(addMusicSheet.getIsUseSystemBeat() == null || !addMusicSheet.getIsUseSystemBeat()){
            musicSheetAudit.setHasBeat(YesOrNoEnum.YES);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3_METRONOME);
        }else {
            musicSheetAudit.setHasBeat(YesOrNoEnum.NO);
            musicSheetAudit.setMp3Type(AudioTypeEnum.MP3);
        }
        List<CbsMusicSheetWrapper.MusicSheetAccompaniment> accompanimentList = addMusicSheet.getMusicSheetAccompanimentList();
        if (CollectionUtils.isNotEmpty(accompanimentList)) {
            musicSheetAudit.setMetronomeUrl(accompanimentList.get(0).getAudioFileUrl());
        }
        List<CbsMusicSheetWrapper.MusicSheetSound> soundList = addMusicSheet.getMusicSheetSoundList();
        if (CollectionUtils.isNotEmpty(soundList)) {
            List<MusicSheetAccompaniment> background = new ArrayList<>();
            for (CbsMusicSheetWrapper.MusicSheetSound sound : soundList) {
                MusicSheetAccompaniment musicSheetAccompaniment = new MusicSheetAccompaniment();
                musicSheetAccompaniment.setAudioFileUrl(sound.getAudioFileUrl());
                musicSheetAccompaniment.setSortNumber(sound.getSortNumber());
                musicSheetAccompaniment.setTrack(sound.getTrack());
                musicSheetAccompaniment.setMusicalInstrumentId(sound.getMusicalInstrumentId());
                background.add(musicSheetAccompaniment);
            }
            musicSheetAudit.setBackground(background);
        }
        musicSheetAudit.setXmlFileUrl(addMusicSheet.getXmlFileUrl());
        musicSheetAudit.setMidiUrl(addMusicSheet.getMidiFileUrl());
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> extend = addMusicSheet.getAddMusicSheetApplicationExtend();
        if(CollectionUtils.isNotEmpty(extend)){
            CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend applicationExtend = extend.get(0);
            musicSheetAudit.setMusicTag(applicationExtend.getMusicTagIds());
            if(applicationExtend.getPaymentType() != null){
                musicSheetAudit.setPaymentType(applicationExtend.getPaymentType());
                musicSheetAudit.setChargeType(ChargeTypeEnum.valueOf(applicationExtend.getPaymentType()));
            }

            EDefaultScoreType scoreType = addMusicSheet.getAddMusicSheetApplicationExtend().get(0).getScoreType();
            musicSheetAudit.setScoreType(scoreType!=null?scoreType.name():EDefaultScoreType.STAVE.getCode());
            if(applicationExtend.getTopFlag() != null){
                musicSheetAudit.setTopFlag(applicationExtend.getTopFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            if(applicationExtend.getExquisiteFlag() != null){
                musicSheetAudit.setExquisiteFlag(applicationExtend.getExquisiteFlag()? YesOrNoEnum.YES: YesOrNoEnum.NO);
            }
            musicSheetAudit.setSortNumber(applicationExtend.getSortNo());
            musicSheetAudit.setMusicPrice(applicationExtend.getMusicPrice());
        }
    }


    @Override
    public void sync() {
        // 分页查询，每次100条
        int curPage = 1;
        int pageSize = 50;
        Date date = new Date();
        // 100个线程的无界线程池
        ThreadPoolExecutor executorService =  new ThreadPoolExecutor(50, 50,
            0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
//        while (true) {
            IPage<MusicSheet> page = baseMapper.selectSyncPage(new Page<>(1, -1));
            List<MusicSheet> records = page.getRecords();
            if (CollectionUtils.isEmpty(records)) {
                return;
            }
            for (MusicSheet record : records) {
                if (record.getCbsMusicSheetId() != null && !DateUtil.format(record.getCreateTime(),"yyyy-MM-dd HH:mm:ss").equals("2024-06-25 00:00:00")) {
                    continue;
                }

                executorService.submit(() ->
                    {

                        try {

                            syncMusicSheet(record, date);
                        }catch (Exception e) {
                            log.error("曲目同步异常，曲目ID：{}", record.getId(), e);
                        }
                    }
                );
            }

            curPage++;
//        }

        while (!executorService.getQueue().isEmpty()) {
            try {
                log.info("线程池中正在执行的任务数量：{},等待数量：{}", executorService.getActiveCount(),executorService.getQueue().size());
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                log.error("线程等待异常", e);
            }
        }
        log.info("-------------------- 曲目数据同步成功! -------------------------------");
        executorService.shutdown();
    }

    @Override
    public CbsMusicSheetWrapper.MusicSheetApplicationQuery getMusicSheetApplicationQuery() {
        return getMusicSheetApplicationQuery(SourceTypeEnum.PLATFORM);
    }
    @Override
    public CbsMusicSheetWrapper.MusicSheetApplicationQuery getMusicSheetApplicationQuery(SourceTypeEnum sourceType) {
        CbsMusicSheetWrapper.MusicSheetApplicationQuery query = new CbsMusicSheetWrapper.MusicSheetApplicationQuery();
        query.setDetailFlag(true);
        query.setDelFlag(true);
        query.setPage(1);
        query.setAudioPlayTypeFlag(false);
        if (sourceType == null || sourceType == SourceTypeEnum.PLATFORM) {
            query.setApplicationId(applicationId);
        } else {
            query.setApplicationId(Long.parseLong(sysConfigService.findConfigValue(SysConfigConstant.CBS_TENANT_APP_ID)));
        }
        return query;
    }

    @Override
    public com.yonge.toolset.base.page.PageInfo<CbsMusicSheetWrapper.MusicSheetAccApplication> queryCbsMusicSheetSoundApplication(CbsMusicSheetWrapper.MusicSheetApplicationQuery query) {
        R<com.microsvc.toolkit.common.response.paging.PageInfo<CbsMusicSheetWrapper.MusicSheetAccApplication>> pageInfoR =
                musicFeignClientService.musicSheetAccPageByApplication(query);
        if(pageInfoR.getCode() != 200){
            throw new BizException("获取曲目信息失败");
        }
        com.microsvc.toolkit.common.response.paging.PageInfo<CbsMusicSheetWrapper.MusicSheetAccApplication> pageInfo = pageInfoR.getData();
        return PageUtil.pageInfo(pageInfo);
    }

    @Override
    public List<CbsMusicSheetWrapper.MusicSheetApplication> queryCbsMusicSheetApplication(CbsMusicSheetWrapper.MusicSheetApplicationQuery query) {
        R<com.microsvc.toolkit.common.response.paging.PageInfo<CbsMusicSheetWrapper.MusicSheetApplication>> pageInfoR =
                musicFeignClientService.musicSheetPageByApplication(query);
        if(pageInfoR.getCode() != 200){
            throw new BizException("获取曲目信息失败");
        }
        com.microsvc.toolkit.common.response.paging.PageInfo<CbsMusicSheetWrapper.MusicSheetApplication> pageInfo = pageInfoR.getData();
        if(pageInfo != null && CollectionUtils.isNotEmpty(pageInfo.getRows())){
            return pageInfo.getRows();
        }
        return new ArrayList<>();
    }

    @Override
    public IPage<MusicSheetVo> queryTenantRelatedList(IPage<Object> page, MusicSheetRelatedQueryInfo queryInfo) {

        MusicSheet musicSheet = musicSheetDao.get(queryInfo.getMusicSheetId());
        if (musicSheet == null) {
            throw new BizException("曲目不存在");
        }
        queryInfo.setMusicSheetType(musicSheet.getMusicSheetType());
        return musicSheetDao.queryTenantRelatedList(page,queryInfo);
    }

    @Override
    public PageInfo<MusicSheetWrapper.MusicSheetApplication> tenantPage(CbsMusicSheetWrapper.MusicSheetApplicationQuery query) {
        String cbsTenantAppId = sysConfigService.findConfigValue(SysConfigConstant.CBS_TENANT_APP_ID);
        query.setApplicationId(Long.parseLong(cbsTenantAppId));
        try {
            PageInfo<CbsMusicSheetWrapper.MusicSheetApplication> feignedData = this.musicFeignClientService.musicSheetPageByApplication(query).feignData();
            PageInfo<MusicSheetWrapper.MusicSheetApplication> convert = feignedData.convert(o -> JSON.parseObject(JSON.toJSONString(o),MusicSheetWrapper.MusicSheetApplication.class));

            List<MusicSheetWrapper.MusicSheetApplication> rows = convert.getRows();
            if (CollectionUtils.isEmpty(rows)) {
                return convert;
            }
            // 查询曲目对应的业务ID
            List<Long> cbsMusicSheetIds = rows.stream().map(CbsMusicSheetWrapper.MusicSheetApplication::getId).collect(Collectors.toList());
            Map<Long, MusicSheet> mapByCbsIds = getMapByCbsIds(cbsMusicSheetIds);
            rows = rows.stream().map(o->{
                MusicSheet musicSheet = mapByCbsIds.get(o.getId());
                if (musicSheet != null) {
                    o.setBizId(musicSheet.getId());
                    return o;
                }
                return null;
            }).filter(Objects::nonNull).collect(Collectors.toList());


            convert.setRows(rows);
            return convert;
        } catch (Exception e) {
            log.error("查询曲目应用拓展表异常", e);
            if(e instanceof com.microsvc.toolkit.common.webportal.exception.BizException) {
                throw e;
            }
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("内容平台服务异常");
        }
    }

    @Override
    public void delPractice(Long musicSheetId,Long userId,ClientEnum clientEnum) {
        baseMapper.delPractice(musicSheetId,userId,clientEnum);
    }


    /**
     * @param musicSheetId 业务端曲目ID
     * @return CbsMusicSheetWrapper.MusicSheet
     */
    @Override
    public CbsMusicSheetWrapper.MusicSheet cbsDetail(Long cbsMusicSheetId) {
        try {

            R<CbsMusicSheetWrapper.MusicSheet> musicSheetR = musicFeignClientService.musicSheetDetail(cbsMusicSheetId , applicationId);

            return musicSheetR.feignData();
        } catch (Exception e) {
            log.error("调用音乐服务异常", e);
            throw new BizException("内容平台服务异常");
        }
    }

    @Override
    public IPage<MusicSheetWrapper.MusicSheetCloud> cloudPage(MusicSheetWrapper.MusicSheetCloudQuery query) {
        IPage<MusicSheetWrapper.MusicSheetCloud> musicSheetCloudIPage = musicSheetDao.cloudPage(QueryInfo.getPage(query), query);
        List<MusicSheetWrapper.MusicSheetCloud> records = musicSheetCloudIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return musicSheetCloudIPage;
        }
        List<Long> musicSheetIds = records.stream()
                .map(MusicSheetWrapper.MusicSheetCloud::getCbsMusicSheetId)
                .map(Long::parseLong)
                .collect(Collectors.toList());

        Map<Long, CbsMusicSheetWrapper.MusicSheetApplication> musicSheetApplicationMapByCbsIds = getMusicSheetApplicationMapByCbsIds(query.getProviderType(), musicSheetIds);
        if (musicSheetApplicationMapByCbsIds == null) {
            return musicSheetCloudIPage;
        }
        records = records.stream().map(o->{
            CbsMusicSheetWrapper.MusicSheetApplication musicSheetApplication = musicSheetApplicationMapByCbsIds.get(Long.parseLong(o.getCbsMusicSheetId()));
            if (musicSheetApplication != null) {
                o.setTitleImg(musicSheetApplication.getMusicCover());
            }
            return o;
        }).collect(Collectors.toList());
        musicSheetCloudIPage.setRecords(records);
        return musicSheetCloudIPage;
    }

    private Map<Long,MusicSheet> getMapByCbsIds(List<Long> cbsMusicSheetIds) {
        if (CollectionUtils.isEmpty(cbsMusicSheetIds)) {
            return new HashMap<>();
        }
        List<MusicSheet> musicSheets = this.lambdaQuery().in(MusicSheet::getCbsMusicSheetId, cbsMusicSheetIds).list();
        return musicSheets.stream().collect(Collectors.toMap(MusicSheet::getCbsMusicSheetId,o->o, (o1,o2)->o2));
    }


    private void syncMusicSheet(MusicSheet record, Date date) {
        List<MusicSheetAccompaniment> list = musicSheetAccompanimentService.lambdaQuery().eq(MusicSheetAccompaniment::getMusicSheetId, record.getId()).list();

        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = this.musicToAddMusicSheet(record,list);

        R<CbsMusicSheetWrapper.MusicSheet> musicSheetR = musicFeignClientService.musicCbsSync(addMusicSheet);
        try {
            CbsMusicSheetWrapper.MusicSheet musicSheet = musicSheetR.feignData();
            if (musicSheet == null) {
                log.error("曲目同步失败，曲目ID：{}", record.getId());
                return;
            }
            MusicSheet musicSheet1 = new MusicSheet();
            musicSheet1.setId(record.getId());
            musicSheet1.setCbsMusicSheetId(musicSheet.getId());
//            musicSheet1.setCbsSubjectId(musicSheet.getSubjectIds());
            musicSheet1.setMusicSheetName(musicSheet.getName());
            this.updateById(musicSheet1);
        } catch (Exception e){
            log.error("曲目同步失败，曲目ID：{}", record.getId(),e);
        }

    }

    private CbsMusicSheetWrapper.AddMusicSheet musicToAddMusicSheet(MusicSheet from, List<MusicSheetAccompaniment> accList) {
        if (from == null) {
            throw com.microsvc.toolkit.common.webportal.exception.BizException.from("参数错误");
        }
        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = new CbsMusicSheetWrapper.AddMusicSheet();
        addMusicSheet.setId(from.getId());
        if (from.getCbsMusicSheetId() != null && DateUtil.format(from.getCreateTime(),"yyyy-MM-dd HH:mm:ss").equals("2024-06-25 00:00:00")) {
            addMusicSheet.setId(from.getCbsMusicSheetId());
        }
        addMusicSheet.setMusicCover(from.getTitleImg());
        addMusicSheet.setName(from.getMusicSheetName());
        if (StringUtils.isNotBlank(from.getMusicSubject())) {
            List<Long> subjectIds = Arrays.stream(from.getMusicSubject().split(","))
                .map(Long::parseLong).collect(Collectors.toList());
            List<Subject> list = subjectService.findBySubjectByIdList(subjectIds);
            if (CollectionUtils.isNotEmpty(list)) {
                addMusicSheet.setSubjectIds(list.stream().map(o->o.getCbsSubjectId().toString()).collect(Collectors.joining(",")));
            }
        }
        addMusicSheet.setSendAppFlag(false);
        addMusicSheet.setAppAuditFlag(from.getAuditVersion() ==YesOrNoEnum.YES);
        addMusicSheet.setRemark(from.getRemark());

        addMusicSheet.setMusicCategoryId(110061L);
        addMusicSheet.setComposer(from.getComposer());
        if (from.getMusicSheetType() != null) {
            addMusicSheet.setMusicSheetType(from.getMusicSheetType() == MusicSheetTypeEnum.CONCERT?EMusicSheetType.CONCERT:EMusicSheetType.SINGLE);
        } else {
            addMusicSheet.setMusicSheetType(EMusicSheetType.SINGLE);

        }
        if (from.getMp3Type() !=null && from.getMp3Type() == AudioTypeEnum.MP3) {
            addMusicSheet.setIsPlayBeat(true);
            addMusicSheet.setIsUseSystemBeat(true);
        } else {
            addMusicSheet.setIsPlayBeat(true);
            addMusicSheet.setIsUseSystemBeat(false);
        }
        if (from.getCanEvaluate() !=null) {
            addMusicSheet.setIsEvaluated(from.getCanEvaluate() == YesOrNoEnum.YES);
        } else {
            addMusicSheet.setIsEvaluated(true);
        }
        addMusicSheet.setIsConvertibleScore(from.getNotation() == null ||from.getNotation() == YesOrNoEnum.YES);
        addMusicSheet.setIsShowFingering(from.getShowFingering()  ==null ||from.getShowFingering() ==YesOrNoEnum.YES);
        addMusicSheet.setPlaySpeed(Optional.ofNullable(from.getPlaySpeed()).map(String::valueOf).orElse(null));
        if (from.getAudioType() !=null) {
            addMusicSheet.setPlayMode( from.getAudioType() == AudioTypeEnum.MP3?EMusicPlayMode.MP3:EMusicPlayMode.MIDI);
        } else {
            addMusicSheet.setPlayMode(EMusicPlayMode.MP3);

        }
        addMusicSheet.setXmlFileUrl(from.getXmlFileUrl());
        addMusicSheet.setMidiFileUrl(from.getMidiUrl());
        addMusicSheet.setMusicJson(from.getMusicJSON());
        addMusicSheet.setMusicSvg(from.getMusicSvg());
        addMusicSheet.setMusicJianSvg(from.getMusicJianSvg());
        addMusicSheet.setMusicFirstSvg(from.getMusicFirstSvg());

        addMusicSheet.setMusicFirstImg(Optional.ofNullable(from.getFirstTone()).orElse(from.getFirstTone()));
        addMusicSheet.setMusicJianImg(Optional.ofNullable(from.getFixedTone()).orElse(from.getFixedTone()));
        addMusicSheet.setMusicImg(from.getMusicImg());
        addMusicSheet.setExtConfigJson(from.getExtConfigJson());
        addMusicSheet.setCreateTime(from.getCreateTime());
        addMusicSheet.setAudioType(from.getAccompanimentType() !=null && from.getAccompanimentType() == AccompanimentTypeEnum.COMMON? EAudioType.COMMON:EAudioType.HOMEMODE);
        if (from.getSourceType() !=null) {
            addMusicSheet.setAvailableType(from.getSourceType() == SourceTypeEnum.PLATFORM?EMusicAvailableType.PLATFORM:EMusicAvailableType.PERSON);
            addMusicSheet.setSourceType(from.getSourceType() == SourceTypeEnum.PLATFORM?EMusicSourceType.PLATFORM:EMusicSourceType.PERSON);
        } else {
            addMusicSheet.setAvailableType(EMusicAvailableType.PLATFORM);
            addMusicSheet.setSourceType(EMusicSourceType.PLATFORM);
        }
        addMusicSheet.setStatus(from.getState() == YesOrNoEnum.YES);
        addMusicSheet.setReason(from.getReason());

        String tracks = "";
        // 伴奏，原音 扩展信息
        if (addMusicSheet.getPlayMode() == EMusicPlayMode.MP3) {
            CbsMusicSheetWrapper.MusicSheetAccompaniment musicSheetAccompaniment = new CbsMusicSheetWrapper.MusicSheetAccompaniment();
            if (StringUtils.isNotBlank(from.getMetronomeUrl())) {
                musicSheetAccompaniment.setAudioFileUrl(from.getMetronomeUrl());
            }else if (StringUtils.isNotBlank(from.getUrl())) {
                musicSheetAccompaniment.setAudioFileUrl(from.getUrl());
            } else if (StringUtils.isNotBlank(from.getAudioFileUrl())) {
                musicSheetAccompaniment.setAudioFileUrl(from.getAudioFileUrl());
            }
            if (StringUtils.isNotBlank(musicSheetAccompaniment.getAudioFileUrl())) {
                addMusicSheet.setMusicSheetAccompanimentList(Lists.newArrayList(musicSheetAccompaniment));
            }
            if (CollectionUtils.isNotEmpty(accList)) {
                List<CbsMusicSheetWrapper.MusicSheetSound> musicSheetSounds = new ArrayList<>();
                for (MusicSheetAccompaniment sheetAccompaniment : accList) {
                    CbsMusicSheetWrapper.MusicSheetSound musicSheetSound = new CbsMusicSheetWrapper.MusicSheetSound();
                    if (StringUtils.isNotBlank(sheetAccompaniment.getAudioFileUrl())){
                        musicSheetSound.setAudioFileUrl(sheetAccompaniment.getAudioFileUrl());
                    } else if (StringUtils.isNotBlank(sheetAccompaniment.getMetronomeUrl())) {
                        musicSheetSound.setAudioFileUrl(sheetAccompaniment.getMetronomeUrl());
                    }
                    musicSheetSound.setTrack(sheetAccompaniment.getTrack());
                    musicSheetSound.setSortNumber(sheetAccompaniment.getSortNumber());
                    if (StringUtils.isNotBlank(musicSheetSound.getAudioFileUrl())) {
                        musicSheetSounds.add(musicSheetSound);
                    }
                }
                tracks = musicSheetSounds.stream().map(CbsMusicSheetWrapper.MusicSheetSound::getTrack).collect(Collectors.joining(","));
                addMusicSheet.setMusicSheetSoundList(musicSheetSounds);
            }
        }
        addMusicSheet.setMultiTracksSelection(tracks);

        CbsMusicSheetWrapper.MusicSheetExtend musicSheetExtend = new CbsMusicSheetWrapper.MusicSheetExtend();
        musicSheetExtend.setApplicationId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
        if (from.getSourceType() !=null) {
            if (from.getSourceType() == SourceTypeEnum.TEACHER) {
                musicSheetExtend.setUserId(from.getUserId());
                musicSheetExtend.setClientType(EClientType.TEACHER.name());
            } else {
                musicSheetExtend.setClientType(EClientType.BACKEND.name());
            }
        }
        addMusicSheet.setMusicSheetExtend(musicSheetExtend);

        // 应用扩展信息
        CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend addMusicSheetApplicationExtend = new CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend();
        addMusicSheetApplicationExtend.setApplicationId(Long.parseLong(openFeignClientConfigProperties.getAppId()));
        addMusicSheetApplicationExtend.setStatus(addMusicSheet.getStatus());
        addMusicSheetApplicationExtend.setSortNo(from.getSortNumber());
        addMusicSheetApplicationExtend.setPaymentType(from.getPaymentType());
        addMusicSheetApplicationExtend.setTopFlag(from.getTopFlag() !=null && from.getTopFlag() == YesOrNoEnum.YES);
        addMusicSheetApplicationExtend.setExquisiteFlag(from.getExquisiteFlag() !=null && from.getExquisiteFlag() == YesOrNoEnum.YES);
        addMusicSheetApplicationExtend.setAvailableType(StringUtils.isNotBlank(from.getProviderType())&& from.getProviderType().equals(SourceTypeEnum.TENANT.getCode())?EMusicAvailableType.ORG:EMusicAvailableType.PLATFORM);
        addMusicSheetApplicationExtend.setMusicTagIds(from.getMusicTag());
        addMusicSheetApplicationExtend.setMusicPrice(from.getMusicPrice());
        addMusicSheet.setAddMusicSheetApplicationExtend(Lists.newArrayList(addMusicSheetApplicationExtend));
        addMusicSheet.setIsConvertibleScore(true);
        return addMusicSheet;
    }


    private SysUser getSysUser(Long userId) {
        return Optional.ofNullable(userId)
                .map(sysUserFeignService::queryUserById)
                .orElseThrow(() -> new BizException("用户不存在"));
    }
}