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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dayaedu.cbs.common.enums.music.EAudioType;
import com.dayaedu.cbs.common.enums.music.EDefaultScoreType;
import com.dayaedu.cbs.common.enums.music.EMusicAvailableType;
import com.dayaedu.cbs.common.enums.school.EMusicSheetType;
import com.dayaedu.cbs.openfeign.client.MusicFeignClientService;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetApplicationExtendClientWrapper;
import com.dayaedu.cbs.openfeign.wrapper.music.CbsMusicSheetWrapper;
import com.microsvc.toolkit.common.response.template.R;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetAuthRecordDao;
import com.yonge.cooleshow.biz.dal.dto.PageUtil;
import com.yonge.cooleshow.biz.dal.dto.req.TeacherMusicSheetAuditReq;
import com.yonge.cooleshow.biz.dal.dto.search.TeacherMusicSheetAuditSearch;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.TeacherTagEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetDetailVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherMusicSheetVo;
import com.yonge.cooleshow.biz.dal.wrapper.AddMusicSheetWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.InstrumentWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.MusicSheetWrapper;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.cooleshow.common.service.IdGeneratorService;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class MusicSheetAuthRecordServiceImpl extends ServiceImpl<MusicSheetAuthRecordDao, MusicSheetAuthRecord> implements MusicSheetAuthRecordService {
    private static final Logger log = LoggerFactory.getLogger(MusicSheetAuthRecordServiceImpl.class);
    @Resource
    private IdGeneratorService idGeneratorService;
    @Resource
    private MusicSheetService musicSheetService;
    @Resource
    private MusicFeignClientService musicFeignClientService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private SubjectService subjectService;
    @Resource
    private MusicTagService musicTagService;
    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private InstrumentService instrumentService;
    @Resource
    private MusicSheetAccompanimentService musicSheetAccompanimentService;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void audit(TeacherMusicSheetAuditReq param, Long userId) {
        // 查询到审核记录
        MusicSheetAuthRecord musicSheetAuthRecord = this.lambdaQuery()
                                              .eq(MusicSheetAuthRecord::getId, param.getMusicSheetId())
                                              .eq(MusicSheetAuthRecord::getAuditState, AuthStatusEnum.DOING.getCode()).one();
        if (musicSheetAuthRecord == null) {
            throw new BizException("没有找到待审核记录");
        }
        musicSheetAuthRecord.setAuditState(param.getAuthStatus());
        musicSheetAuthRecord.setReason(param.getRemark());
        musicSheetAuthRecord.setVerifyUserId(userId);
        musicSheetAuthRecord.setAuditState(param.getAuthStatus());
        musicSheetAuthRecord.setLastAuditState(param.getAuthStatus());
        String musicSheetJson = musicSheetAuthRecord.getMusicSheetJson();
        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetJson, CbsMusicSheetWrapper.AddMusicSheet.class);
        addMusicSheet.setIsEvaluated(param.getCanEvaluate()==YesOrNoEnum.YES);
        addMusicSheet.setIsPlayBeat(true);
        addMusicSheet.setIsUseSystemBeat(param.getHasBeat()!=YesOrNoEnum.YES);
        addMusicSheet.setIsShowFingering(param.getShowFingering()==YesOrNoEnum.YES);
        addMusicSheet.setIsConvertibleScore(param.getNotation()==YesOrNoEnum.YES);
        addMusicSheet.setExtConfigJson(param.getExtConfigJson());
        addMusicSheet.setAudioType(EAudioType.valueOf(param.getAccompanimentType().getCode()));
        addMusicSheet.setMusicSheetType(EMusicSheetType.valueOf(param.getMusicSheetType()));
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> addMusicSheetApplicationExtend = addMusicSheet.getAddMusicSheetApplicationExtend();
        for (CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend musicSheetApplicationExtend : addMusicSheetApplicationExtend) {
            musicSheetApplicationExtend.setScoreType(EDefaultScoreType.valueOf(param.getScoreType()));
        }
        musicSheetAuthRecord.setMusicSheetJson(JSON.toJSONString(addMusicSheet));
        MusicSheet musicSheet = musicSheetService.getById(musicSheetAuthRecord.getMusicSheetId());
        if (musicSheet == null) {
            throw new BizException("曲目信息不存在");
        }
        if (param.getAuthStatus().equals(AuthStatusEnum.PASS)) {
//            MusicSheet update = new MusicSheet();
//            update.setId(musicSheet.getId());
//            update.setFirstPassAuditTime(new Date());
//            musicSheetService.updateById(musicSheet);
            // 修改老师标签
            teacherService.setTeacherTag(musicSheet.getUserId(), TeacherTagEnum.MUSIC);
            //同步到内容平台
            CbsMusicSheetWrapper.MusicSheetExtend musicSheetExtend = new CbsMusicSheetWrapper.MusicSheetExtend();
            musicSheetExtend.setApplicationId(applicationId);
            R<CbsMusicSheetWrapper.MusicSheet> detail = musicFeignClientService.musicSheetDetail(musicSheet.getCbsMusicSheetId(), applicationId);
            String useApplicationIds = null;
            if (detail.getCode().equals(200) && detail.getData() != null){
                useApplicationIds = detail.feignData().getMusicSheetExtend().getUseApplicationIds();
            }
            if(StringUtils.isEmpty(useApplicationIds)){
                useApplicationIds = applicationId.toString();
            }else {
                if(!useApplicationIds.contains(applicationId.toString())){
                    useApplicationIds = useApplicationIds + "," + applicationId;
                }
            }
            musicSheetExtend.setUseApplicationIds(useApplicationIds);
            musicSheetExtend.setUserId(addMusicSheet.getCreateBy());
            addMusicSheet.setSendAppFlag(true);
            addMusicSheet.setMusicSheetExtend(musicSheetExtend);
            addMusicSheet.setMusicImg(param.getMusicImg());
            addMusicSheet.setMusicFirstImg(param.getMusicFirstImg());
            addMusicSheet.setMusicJianImg(param.getMusicJianImg());
            addMusicSheet.setExtConfigJson(param.getExtConfigJson());
            addMusicSheet.setIsEvaluated(param.getCanEvaluate()==YesOrNoEnum.YES);
            addMusicSheet.setIsPlayBeat(true);
            addMusicSheet.setIsUseSystemBeat(param.getHasBeat()!=YesOrNoEnum.YES);
            addMusicSheet.setId(musicSheet.getCbsMusicSheetId());
            addMusicSheet.setAvailableType(EMusicAvailableType.PLATFORM);
            addMusicSheet.setUpdateBy(userId);
            //修改声部和乐器为内容平台id
            String musicalInstrumentIds = addMusicSheet.getMusicalInstrumentIds();
            List<Instrument> instruments = instrumentService.lambdaQuery().in(Instrument::getId, musicalInstrumentIds.split(",")).list();
            addMusicSheet.setMusicalInstrumentIds(musicalInstrumentIds);
            String subjectIds = instruments.stream().map(e -> e.getSubjectId().toString()).distinct().collect(Collectors.joining(","));
            List<Subject> subjectList = subjectService.findBySubjectByIdList(subjectIds);
            addMusicSheet.setSubjectIds(subjectList.stream().map(e -> e.getCbsSubjectId().toString()).distinct().collect(Collectors.joining(",")));
            R<Long> longR = musicFeignClientService.musicSheetAdd(addMusicSheet);
            if (!longR.getCode().equals(200)) {
                throw new BizException("同步到内容平台失败");
            }
        }else {
            musicSheet.setAuditStatus(param.getAuthStatus());
            musicSheet.setUpdateBy(userId);
            musicSheetService.updateById(musicSheet);
        }
        //批量更新同一个批次的审核状态
        this.lambdaUpdate().eq(MusicSheetAuthRecord::getBatchNo, musicSheetAuthRecord.getBatchNo())
                .set(MusicSheetAuthRecord::getLastAuditState, param.getAuthStatus())
                .update();
        this.updateById(musicSheetAuthRecord);
        // 发送审核通知
        Map<Long, String> receivers = new HashMap<>();
        SysUser teacher = sysUserService.getByUserId(musicSheet.getUserId());
        receivers.put(musicSheet.getUserId(), teacher.getPhone());
        try {
            sendMusicSheetAuditMessage(param, musicSheet, receivers);
        } catch (Exception e) {
            log.warn("曲目审核消息发送失败，{}", e.getMessage());
        }
    }

    // 发送曲目审核消息
    private void sendMusicSheetAuditMessage(TeacherMusicSheetAuditReq param, MusicSheet musicSheet, Map<Long, String> receivers) {
        if (AuthStatusEnum.PASS.getCode().equals(param.getAuthStatus().getCode())) {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSIC_SHEET_AUTH_PASS,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode(), musicSheet.getMusicSheetName());
        } else if (AuthStatusEnum.UNPASS.getCode().equals(param.getAuthStatus().getCode())) {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.MUSIC_SHEET_AUTH_UNPASS,
                    receivers, null, 0, null, ClientEnum.TEACHER.getCode(), musicSheet.getMusicSheetName(),
                    param.getRemark());
        }
    }


    @Override
    public String selectAuditReason(Long musicSheetId) {
        MusicSheetAuthRecord one = this.lambdaQuery()
                                       .eq(MusicSheetAuthRecord::getMusicSheetId, musicSheetId)
                                       .orderByDesc(MusicSheetAuthRecord::getId)
                                       .last("limit 1")
                                       .one();
        if (one == null) {
            return "";
        }
        return one.getReason();
    }

    private CbsMusicSheetWrapper.AddMusicSheet checkRecord(MusicSheetAuthRecord musicSheetAuthRecord){
        if(StringUtils.isEmpty(musicSheetAuthRecord.getMusicSheetJson())){
            throw new BizException("曲目信息不能为空");
        }
        AddMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetAuthRecord.getMusicSheetJson(), AddMusicSheetWrapper.AddMusicSheet.class);
        //反查乐器关联的声部
        String musicalInstrumentIds = addMusicSheet.getMusicalInstrumentIds();
        List<Instrument> list = instrumentService.lambdaQuery().in(Instrument::getId, musicalInstrumentIds.split(",")).list();
        if(CollectionUtils.isEmpty(list)){
            throw new BizException("乐器信息不存在");
        }
        String subjectIds = list.stream().map(e -> e.getSubjectId().toString()).distinct().collect(Collectors.joining(","));
        List<Subject> subjectList = subjectService.findBySubjectByIdList(subjectIds);
        addMusicSheet.setSubjectIds(subjectList.stream().map(e -> e.getId().toString()).distinct().collect(Collectors.joining(",")));
        List<CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend> extendList = new ArrayList<>();
        CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend extend = new CbsMusicSheetApplicationExtendClientWrapper.AddMusicSheetApplicationExtend();
        extend.setApplicationId(applicationId);
        extend.setMusicSheetCategoryId(addMusicSheet.getMusicSheetCategoryId());
        extend.setStatus(addMusicSheet.getStatus());
        extend.setSortNo(addMusicSheet.getSortNo());
        extend.setPaymentType(addMusicSheet.getPaymentType());
        extend.setTopFlag(addMusicSheet.getTopFlag());
        extend.setExquisiteFlag(addMusicSheet.getExquisiteFlag());
        extend.setAvailableType(EMusicAvailableType.PLATFORM);
        extend.setMusicTagIds(addMusicSheet.getMusicTagIds());
        extend.setMusicPrice(addMusicSheet.getMusicPrice());
        extend.setScoreType(EDefaultScoreType.STAVE);
        if(addMusicSheet.getIsConvertibleScore() == null){
            addMusicSheet.setIsConvertibleScore(true);
        }
        if(addMusicSheet.getIsEvaluated() == null){
            addMusicSheet.setIsEvaluated(true);
        }
        if(addMusicSheet.getIsPlayBeat() == null){
            addMusicSheet.setIsPlayBeat(true);
        }
        extendList.add(extend);
        addMusicSheet.setAddMusicSheetApplicationExtend(extendList);
        return addMusicSheet;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addRecord(MusicSheetAuthRecord musicSheetAuthRecord) {
        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = this.checkRecord(musicSheetAuthRecord);
        //保存曲目信息
        MusicSheet musicSheet = musicSheetService.initMusicSheet(addMusicSheet);
        Long userId = sysUserService.getUserId();
        musicSheet.setUserId(userId);
        musicSheet.setCreateBy(userId);
        musicSheet.setUpdateBy(userId);
        musicSheet.setScoreType(EDefaultScoreType.STAVE.name());
        musicSheet.setCbsMusicSheetId(IdWorker.getId());
        musicSheetService.save(musicSheet);
        List<MusicSheetAccompaniment> musicSheetAccompaniments = musicSheetAccompanimentService.initMusicSheetAccompaniment(musicSheetAuthRecord.getMusicSheetJson(),musicSheet.getId());
        musicSheetAccompanimentService.saveBatch(musicSheetAccompaniments);
        String batchNo = idGeneratorService.generatorId("payment") + "";
        musicSheetAuthRecord.setBatchNo(batchNo);
        musicSheetAuthRecord.setAuditState(AuthStatusEnum.DOING);
        musicSheetAuthRecord.setMusicSheetId(musicSheet.getId());
        musicSheetAuthRecord.setMusicSheetJson(JSON.toJSONString(addMusicSheet));
        musicSheetAuthRecord.setLastAuditState(AuthStatusEnum.DOING);
        //批量更新同一个批次的审核状态
        this.lambdaUpdate().eq(MusicSheetAuthRecord::getBatchNo, musicSheetAuthRecord.getBatchNo())
                .set(MusicSheetAuthRecord::getLastAuditState,AuthStatusEnum.DOING)
                .update();
        return baseMapper.insert(musicSheetAuthRecord);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRecord(MusicSheetAuthRecord musicSheetAuthRecord) {
        if(musicSheetAuthRecord.getId() == null){
            throw new BizException("先选择要修改的曲目");
        }
        MusicSheetAuthRecord record = this.lambdaQuery().eq(MusicSheetAuthRecord::getId, musicSheetAuthRecord.getId()).one();
        if (record == null){
            throw new BizException("审核记录不存在");
        }
        MusicSheet musicSheet1 = musicSheetService.getById(record.getMusicSheetId());
        if (musicSheet1 == null){
            throw new BizException("曲目信息不存在");
        }
        if (musicSheet1.getState() == YesOrNoEnum.YES){
            throw new BizException("请先下架曲目再修改");
        }
        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = this.checkRecord(musicSheetAuthRecord);
        musicSheetService.initMusicSheet(addMusicSheet);
        musicSheet1.setDelFlag(true);
        musicSheetService.updateById(musicSheet1);
        musicSheetAuthRecord.setMusicSheetId(musicSheet1.getId());
        musicSheetAuthRecord.setBatchNo(record.getBatchNo());
        musicSheetAuthRecord.setAuditState(AuthStatusEnum.DOING);
        musicSheetAuthRecord.setLastAuditState(AuthStatusEnum.DOING);
        musicSheetAuthRecord.setMusicSheetJson(JSON.toJSONString(addMusicSheet));
        //批量更新同一个批次的审核状态
        this.lambdaUpdate().eq(MusicSheetAuthRecord::getBatchNo, musicSheetAuthRecord.getBatchNo())
                .set(MusicSheetAuthRecord::getLastAuditState,AuthStatusEnum.DOING)
                .update();
        baseMapper.insert(musicSheetAuthRecord);
    }

    @Override
    public IPage<TeacherMusicSheetVo> selectAuditPage(IPage<TeacherMusicSheetVo> page, TeacherMusicSheetAuditSearch query) {
        List<TeacherMusicSheetVo> teacherMusicSheetVos = baseMapper.selectAuditPage(page, query);
        this.convertMusicDetail(teacherMusicSheetVos);
        return page.setRecords(teacherMusicSheetVos);
    }

    @Override
    public MusicSheetDetailVo auditDetail(Long musicSheetAuthRecordId) {
        MusicSheetDetailVo detail = musicSheetService.detail(musicSheetAuthRecordId, null, null);
        MusicSheetAuthRecord musicSheetAuthRecord = this.getById(musicSheetAuthRecordId);
        MusicSheetAuthRecord last = this.lambdaQuery().eq(MusicSheetAuthRecord::getMusicSheetId, musicSheetAuthRecord.getMusicSheetId())
                                    .ne(MusicSheetAuthRecord::getId, musicSheetAuthRecordId)
                                    .orderByDesc(MusicSheetAuthRecord::getId)
                                    .last("LIMIT 1").one();
        if(last != null){
            detail.setLastMusicSheet(musicSheetService.detail(last.getId(), null, null));
        }
//        List<MusicSheetDetailVo> sheetDetailVos = musicSheetService.getDao().auditDetailList(musicSheetAuthRecord.getMusicSheetId(),null);
//        if (CollectionUtils.isNotEmpty(sheetDetailVos)) {
//            detail.setLastMusicSheet(sheetDetailVos.get(0));
//        }
        return detail;
    }

    @Override
    public List<MusicSheetWrapper.MusicSheetDetailVo> auditDetailList(String batchNo) {
        List<MusicSheetWrapper.MusicSheetDetailVo> sheetDetailVos = musicSheetService.getDao().auditDetailList(batchNo);
        if (CollectionUtils.isNotEmpty(sheetDetailVos)) {
            String userName = sheetDetailVos.get(0).getUserName();
            String realName = sheetDetailVos.get(0).getRealName();
            for (MusicSheetWrapper.MusicSheetDetailVo sheetDetailVo : sheetDetailVos) {
                sheetDetailVo.setUserName(userName);
                sheetDetailVo.setRealName(realName);
                String musicSheetJson = sheetDetailVo.getMusicSheetJson();
                if(StringUtils.isNotEmpty(musicSheetJson)){
                    CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetJson, CbsMusicSheetWrapper.AddMusicSheet.class);
                    musicSheetService.initMusicSheetDetailVo(addMusicSheet,sheetDetailVo);
                    sheetDetailVo.setMusicSheetJson(null);
                    sheetDetailVo.setSubmitAuditTime(sheetDetailVo.getCreateTime());
                    //获取声部
                    String musicSubject = sheetDetailVo.getMusicSubject();
                    if(StringUtils.isNotEmpty(musicSheetJson)){
                        List<Subject> list = subjectService.findBySubjectByIdList(musicSubject);
                        sheetDetailVo.setSubjectNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                    }
                    //获取标签
                    String musicTagIds = sheetDetailVo.getMusicTag();
                    if(StringUtils.isNotEmpty(musicTagIds)){
                        List<MusicTag> list = musicTagService.lambdaQuery().in(MusicTag::getId, musicTagIds.split(",")).list();
                        sheetDetailVo.setMusicTagNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                    }
                }
            }
        }
        return sheetDetailVos;
    }
    @Override
    public MusicSheetDetailVo auditDetail(String id) {
        //获取待审核曲目信息
        MusicSheetAuthRecord record = this.lambdaQuery().eq(MusicSheetAuthRecord::getId, id).one();
        if(Objects.isNull(record)){
            record = this.lambdaQuery().eq(MusicSheetAuthRecord::getMusicSheetId, id)
                    .orderByDesc(MusicSheetAuthRecord::getId).last("LIMIT 1").one();
        }
        if(Objects.nonNull(record)){
            MusicSheetDetailVo sheetDetailVo = musicSheetService.getDao().auditDetail(record.getId());
            String musicSheetJson = sheetDetailVo.getMusicSheetJson();
            if(StringUtils.isNotEmpty(musicSheetJson)){
                CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetJson, CbsMusicSheetWrapper.AddMusicSheet.class);
                musicSheetService.initMusicSheetDetailVo(addMusicSheet,sheetDetailVo);
                //获取乐器名称
                List<MusicSheetAccompaniment> background = sheetDetailVo.getBackground();
                if (CollectionUtils.isNotEmpty(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());
                            }
                        }
                    }
                }
                sheetDetailVo.setSubmitAuditTime(sheetDetailVo.getCreateTime());
                //获取声部
                String musicSubject = sheetDetailVo.getMusicSubject();
                if(StringUtils.isNotEmpty(musicSheetJson)){
                    List<Subject> list = subjectService.findBySubjectByIdList(musicSubject);
                    sheetDetailVo.setSubjectNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                }
                //获取标签
                String musicTagIds = sheetDetailVo.getMusicTag();
                if(StringUtils.isNotEmpty(musicTagIds)){
                    List<MusicTag> list = musicTagService.lambdaQuery().in(MusicTag::getId, musicTagIds.split(",")).list();
                    sheetDetailVo.setMusicTagNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                }
            }
            sheetDetailVo.setMusicSheetAuthRecordId(record.getId().toString());
            return sheetDetailVo;
        }
        return null;
    }

    public void convertMusicDetail(List<TeacherMusicSheetVo> lists) {
        if (CollectionUtils.isNotEmpty(lists)){
            //剔除pass状态的曲子
            List<TeacherMusicSheetVo> collect = lists.stream().filter(e -> e.getAuditStatus() != AuthStatusEnum.PASS).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                Map<AuthStatusEnum,List<TeacherMusicSheetVo>> statusEnumListMap =
                        collect.stream().collect(Collectors.groupingBy(TeacherMusicSheetVo::getAuditStatus));
                for (AuthStatusEnum authStatusEnum : statusEnumListMap.keySet()) {
                    List<TeacherMusicSheetVo> records = statusEnumListMap.get(authStatusEnum);
                    List<String> musicSheetIds = records.stream().map(e -> e.getMusicSheetId()).collect(Collectors.toList());
                    List<MusicSheetAuthRecord> recordList = this.baseMapper.findByMusicSheetIds(musicSheetIds, authStatusEnum.getCode());
                    if (CollectionUtils.isNotEmpty(recordList)){
                        Map<Long,MusicSheetAuthRecord> authRecordMap = recordList.stream()
                                .collect(Collectors.toMap(MusicSheetAuthRecord::getMusicSheetId, Function.identity(), (o, n) -> n));
                        for (TeacherMusicSheetVo musicSheetVo : records) {
                            MusicSheetAuthRecord sheetDetailVo = authRecordMap.get(Long.parseLong(musicSheetVo.getMusicSheetId()));
                            if(sheetDetailVo == null){
                                continue;
                            }
                            musicSheetVo.setId(sheetDetailVo.getId().toString());
                            musicSheetVo.setMusicSheetId(sheetDetailVo.getId().toString());
                            String musicSheetJson = sheetDetailVo.getMusicSheetJson();
                            if(StringUtils.isNotEmpty(musicSheetJson)){
                                CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetJson, CbsMusicSheetWrapper.AddMusicSheet.class);
                                musicSheetService.initMusicSheetDetailVo(addMusicSheet,musicSheetVo);
                                //获取标签
                                String musicTagIds = musicSheetVo.getMusicTag();
                                if(StringUtils.isNotEmpty(musicTagIds)){
                                    List<MusicTag> list = musicTagService.lambdaQuery().in(MusicTag::getId, musicTagIds.split(",")).list();
                                    musicSheetVo.setMusicTagNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public IPage convertMusicDetail(IPage<MusicSheetVo> musicSheetVoIPage, AuthStatusEnum auditStatus) {
        List<MusicSheetVo> records = musicSheetVoIPage.getRecords();
        if (CollectionUtils.isNotEmpty(records)){
            List<Long> musicSheetIds = records.stream().map(e -> e.getId()).collect(Collectors.toList());
            List<MusicSheetAuthRecord> recordList = this.baseMapper.findByMusicSheetIds(musicSheetIds, auditStatus.getCode());
            if (CollectionUtils.isNotEmpty(recordList)){
                Map<Long,MusicSheetAuthRecord> authRecordMap = recordList.stream()
                        .collect(Collectors.toMap(MusicSheetAuthRecord::getMusicSheetId, Function.identity(), (o, n) -> n));
                List<MusicSheetWrapper.MusicSheetVo> results = new ArrayList<>();
                for (MusicSheetVo musicSheetVo : records) {
                    MusicSheetWrapper.MusicSheetVo vo = JSON.parseObject(JSON.toJSONString(musicSheetVo), MusicSheetWrapper.MusicSheetVo.class);
                    vo.setId(musicSheetVo.getId().toString());
                    if(musicSheetVo.getCbsMusicSheetId() != null){
                        vo.setCbsMusicSheetId(musicSheetVo.getCbsMusicSheetId().toString());
                    }
                    MusicSheetAuthRecord sheetDetailVo = authRecordMap.get(musicSheetVo.getId());
                    if(sheetDetailVo == null){
                        continue;
                    }
                    vo.setId(sheetDetailVo.getId().toString());
                    String musicSheetJson = sheetDetailVo.getMusicSheetJson();
                    if(StringUtils.isNotEmpty(musicSheetJson)){
                        CbsMusicSheetWrapper.AddMusicSheet addMusicSheet = JSON.parseObject(musicSheetJson, CbsMusicSheetWrapper.AddMusicSheet.class);
                        musicSheetService.initMusicSheetDetailVo(addMusicSheet,vo);
                        //获取声部
                        String musicSubject = vo.getMusicSubject();
                        if(StringUtils.isNotEmpty(musicSheetJson)){
                            List<Subject> list = subjectService.findBySubjectByIdList(musicSubject);
                            vo.setSubjectNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                        }
                        //获取标签
                        String musicTagIds = vo.getMusicTag();
                        if(StringUtils.isNotEmpty(musicTagIds)){
                            List<MusicTag> list = musicTagService.lambdaQuery().in(MusicTag::getId, musicTagIds.split(",")).list();
                            vo.setMusicTagNames(list.stream().map(e->e.getName()).collect(Collectors.joining(",")));
                        }
                    }
                    results.add(vo);
                }
                return PageUtil.transPageInfo(musicSheetVoIPage,results);
            }
        }
        return musicSheetVoIPage;
    }
}