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

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

import com.alibaba.fastjson.JSON;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicSheetOrderSearch;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.cooleshow.biz.dal.enums.album.PurchaseRecordTypeEnum;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumWrapper;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.enums.ActivityShareEnum;
import com.yonge.toolset.utils.obj.ObjectUtil;
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.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dao.MusicAlbumDao;
import com.yonge.cooleshow.biz.dal.dto.MusicAlbumSheetDto;
import com.yonge.cooleshow.biz.dal.dto.MusicAlbumSheetSortDto;
import com.yonge.cooleshow.biz.dal.dto.search.MusicAlbumDetailSearch;
import com.yonge.cooleshow.biz.dal.dto.search.MusicAlbumSearch;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicAlbumSearch;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.util.StringUtil;
import com.yonge.toolset.mybatis.support.PageUtil;

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

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

    @Autowired
    private ActivityPlanService activityPlanService;
    @Autowired
    private MusicAlbumDao musicAlbumDao;

    @Autowired
    private AlbumMusicRelateService albumMusicRelateService;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private MusicTagService musicTagService;

    @Autowired
    private AlbumFavoriteService albumFavoriteService;

    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MusicSheetPurchaseRecordService musicSheetPurchaseRecordService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TenantAlbumMusicService tenantAlbumMusicService;

    @Autowired
    private TenantAlbumService tenantAlbumService;

    @Autowired
    private TenantStaffService tenantStaffService;


    @Autowired
    private SysUserFeignService sysUserFeignService;

    public MusicAlbumDao getDao() {
        return musicAlbumDao;
    }

    @Override
    public IPage<MusicAlbumVo> selectPage(IPage<MusicAlbumVo> page, MusicAlbumSearch query) {
        return page.setRecords(baseMapper.selectPage(page,query));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean state(Long id) {
        MusicAlbum musicAlbum = this.getById(id);
        if (musicAlbum == null) {
            throw  new BizException("未找到专辑信息");
        }
        if (YesOrNoEnum.NO.getCode().equals(musicAlbum.getAlbumStatus().getCode())) {
            musicAlbum.setAlbumStatus(YesOrNoEnum.YES);
        } else {
            musicAlbum.setAlbumStatus(YesOrNoEnum.NO);
        }
        return this.updateById(musicAlbum);
    }

    @Override
    public AlbumDetailVo detail(IPage<MusicSheetVo> page, MusicAlbumDetailSearch query, SysUser sysUser, ClientEnum client) {
        MusicAlbumVo musicAlbum = baseMapper.selectMusicAlbumById(query.getId());
        if (musicAlbum == null) {
            throw  new BizException("未找到专辑信息");
        }
        AlbumDetailVo albumDetailVo = new AlbumDetailVo();
        albumDetailVo.setId(musicAlbum.getId());
        albumDetailVo.setAlbumName(musicAlbum.getAlbumName());
        albumDetailVo.setAlbumDesc(musicAlbum.getAlbumDesc());
        albumDetailVo.setAlbumTag(musicAlbum.getAlbumTag());
        albumDetailVo.setAlbumCoverUrl(musicAlbum.getAlbumCoverUrl());
        albumDetailVo.setAlbumStatue(musicAlbum.getAlbumStatus());
        albumDetailVo.setAlbumFavoriteCount(musicAlbum.getAlbumFavoriteCount() + musicAlbum.getVirtualNumber());
        albumDetailVo.setAlbumPrice(musicAlbum.getAlbumPrice());
        albumDetailVo.setPaymentType(musicAlbum.getPaymentType());
        albumDetailVo.setMusicTagNames(musicTagService.getMusicTagNames(StringUtil.toLongList(musicAlbum.getAlbumTag())));
        albumDetailVo.setAuditVersion(musicAlbum.getAuditVersion());
        albumDetailVo.setAlbumType(musicAlbum.getAlbumType());
//        query.setMusicSheetType(musicAlbum.getAlbumType());

        // 新增专辑曲目查询条件
        if (query.getType() != null && query.getType() == 1) {
            query.setSubjectIds(musicAlbum.getSubjectId());
        }

        if (sysUser != null) {
            query.setStudentId(sysUser.getId());
        }
        query.setClientType(client);
        IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.selectAlbumDetailPage(page,query);

        List<MusicSheetVo> records = musicSheetVoIPage.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            // 专辑曲目付费方式
            List<String> paymentTypes = musicSheetVoIPage.getRecords().stream()
                    .flatMap(x -> Arrays.stream(x.getPaymentType().split(","))).distinct().collect(Collectors.toList());
            albumDetailVo.setMusicPaymentTypes(paymentTypes);

            // 更新曲目专辑数量
            musicSheetService.updateMusicAlbumNumInfo(records);
        }
        //处理Long精度丢失问题
        List<MusicSheetVoResult> musicSheetVoResults = new ArrayList<>();
        for (MusicSheetVo row : records) {
            MusicSheetVoResult musicSheetVoResult = JSON.parseObject(JSON.toJSONString(row), MusicSheetVoResult.class);
            musicSheetVoResult.setCbsMusicSheetId(row.getCbsMusicSheetId().toString());
            musicSheetVoResults.add(musicSheetVoResult);
        }
        albumDetailVo.setMusicSheetList(PageUtil.pageInfo(com.yonge.cooleshow.biz.dal.dto.PageUtil.transPageInfo(musicSheetVoIPage, musicSheetVoResults)));


        albumDetailVo.setMusicSheetCount((int) musicSheetVoIPage.getTotal());

        if (sysUser == null) {
            return albumDetailVo;
        }

        // 查询购买信息
        MusicSheetPurchaseRecord purchaseRecord = musicSheetPurchaseRecordService.checkPurchase(
                sysUser.getId(), query.getId(), client, PurchaseRecordTypeEnum.ALBUM);
        if (purchaseRecord != null) {
            albumDetailVo.setOrderStatus(purchaseRecord.getOrderStatus());
            albumDetailVo.setOrderNo(purchaseRecord.getOrderNo());
        }

        return albumDetailVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delMusicSheet(Long albumId, String musicSheetIds) {
        MusicAlbum musicAlbum = this.getById(albumId);
        if (musicAlbum == null) {
            throw  new BizException("未找到专辑信息");
        }

        // 付费专辑，需要校验是否已存在购买记录
        /*if (!ChargeTypeEnum.VIP.match(musicAlbum.getPaymentType())) {

            // 统计付费专辑的购买数量
            Integer count = musicSheetPurchaseRecordMapper.selectCount(Wrappers.<MusicSheetPurchaseRecord>lambdaQuery()
                    .eq(MusicSheetPurchaseRecord::getMusicSheetId, albumId)
                    .eq(MusicSheetPurchaseRecord::getPurchaseType, PurchaseRecordTypeEnum.ALBUM)
            );
            if (Optional.ofNullable(count).orElse(0) > 0) {
                throw new BizException("当前专辑已有购买记录");
            }
        }*/

        List<Long> musicSheetIdList = StringUtil.toLongList(musicSheetIds);
        return albumMusicRelateService.delMusicSheet(albumId,musicSheetIdList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addMusicSheet(Long albumId, List<MusicAlbumSheetDto.AlbumMusic> albumMusicList, Long userId) {
        MusicAlbum musicAlbum = this.getById(albumId);
        if (musicAlbum == null) {
            throw  new BizException("未找到专辑信息");
        }

        // 付费专辑最多只能添加两首免费曲目
        /*if (!ChargeTypeEnum.FREE.match(musicAlbum.getPaymentType())) {

            // 新添加曲目统计
            long freeNum = 0;
            List<Long> musicIds = albumMusicList.stream()
                    .map(MusicAlbumSheetDto.AlbumMusic::getMusicSheetId).distinct().collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(musicIds)) {

                freeNum = musicSheetMapper.selectBatchIds(musicIds).stream()
                        .filter(x -> ChargeTypeEnum.FREE.match(x.getPaymentType()))
                        .count();
            }

            // 已添加曲目统计
            Map<Long, Integer> collect = getBaseMapper().selectAlbumMusicSheetStatInfo(albumId, ChargeTypeEnum.FREE).stream()
                    .collect(Collectors.toMap(StatGroupWrapper::getId, StatGroupWrapper::getTotal, (o, n) -> n));

            if ((collect.getOrDefault(albumId, 0) + freeNum) > 2) {
                throw new BizException("专辑免费曲目最多2首");
            }
        }*/

        return albumMusicRelateService.addMusicSheet(albumId,albumMusicList,userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createMusicAlbum(MusicAlbum musicAlbum) {
        if (checkNameRepeat(musicAlbum.getAlbumName(),musicAlbum.getId())) {
            throw new BizException("专辑名称重复");
        }
        if (musicAlbum.getAuditVersion() == null) {
            musicAlbum.setAuditVersion(YesOrNoEnum.NO);
        }
        musicAlbum.setDelFlag(false);
        return this.save(musicAlbum);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMusicAlbum(MusicAlbum musicAlbum) {
        if (checkNameRepeat(musicAlbum.getAlbumName(),musicAlbum.getId())) {
            throw new BizException("专辑名称重复");
        }
        if (musicAlbum.getAuditVersion() == null) {
            musicAlbum.setAuditVersion(YesOrNoEnum.NO);
        }

        // 非付费类型，已添加曲目或者已购买，不允许修改付费方式
        /*MusicAlbum album = getById(musicAlbum.getId());
        if (Objects.isNull(album)) {
            throw new BizException("无效的专辑ID");
        }*/

        // 专辑从免费修改为付费方式，需要判断当前免费单曲数量
        /*if (Objects.nonNull(musicAlbum.getPaymentType())
                && ChargeTypeEnum.FREE.match(album.getPaymentType())
                && !album.getPaymentType().equals(musicAlbum.getPaymentType())) {

            Map<Long, Integer> collect = getBaseMapper().selectAlbumMusicSheetStatInfo(album.getId(), ChargeTypeEnum.FREE).stream()
                    .collect(Collectors.toMap(StatGroupWrapper::getId, StatGroupWrapper::getTotal, (o, n) -> n));

            if (collect.getOrDefault(album.getId(), 0) > 2) {
                throw new BizException(MessageFormat.format("当前专辑免费单曲数为 {0}, 已超过免费数量", collect.get(album.getId())));
            }
        }*/

        return this.updateById(musicAlbum);
    }

    @Override
    public YesOrNoEnum checkFavorite(Long studentId, Long albumId, ClientEnum clientType) {
        List<AlbumFavorite> albumFavorites = albumFavoriteService.getFavorite(studentId,albumId, clientType);

        return CollectionUtils.isEmpty(albumFavorites)?YesOrNoEnum.NO:YesOrNoEnum.YES;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setFavorite(Long studentId, Long albumId, ClientEnum clientType) {
        List<AlbumFavorite> albumFavorites = albumFavoriteService.getFavorite(studentId,albumId, clientType);
        if (CollectionUtils.isEmpty(albumFavorites)) {
            AlbumFavorite albumFavorite = new AlbumFavorite();
            albumFavorite.setAlbumId(albumId);
            albumFavorite.setClientType(clientType);
            albumFavorite.setUserId(studentId);
            albumFavorite.setFavoriteTime(new Date());
            return albumFavoriteService.save(albumFavorite);
        } else {
            List<Long> ids = albumFavorites.stream().map(AlbumFavorite::getId).collect(Collectors.toList());
            return albumFavoriteService.removeByIds(ids);
        }
    }

    @Override
    public IPage<MusicAlbumVo> favoriteAlbum(IPage<MusicAlbumVo> page, StudentMusicAlbumSearch search, ClientEnum clientType) {

        IPage<MusicAlbumVo> iPage = page.setRecords(baseMapper.selectFavoritePage(page, search, clientType));
        List<MusicAlbumVo> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return iPage;
        }
        List<MusicAlbumVo> favoriteNumAndMusicNumList =baseMapper.selectFavoriteNumAndMusicNum(records);
        Map<Long, List<MusicAlbumVo>> collect = new HashMap<>();
        if (CollectionUtils.isNotEmpty(favoriteNumAndMusicNumList)) {
            collect = favoriteNumAndMusicNumList.stream().collect(Collectors.groupingBy(
                                                                                      MusicAlbumVo::getId));
        }

        for (MusicAlbumVo record : records) {
            List<MusicAlbumVo> musicAlbumVos = collect.get(record.getId());
            if (CollectionUtils.isNotEmpty(musicAlbumVos)) {
                record.setAlbumFavoriteCount(musicAlbumVos.get(0).getAlbumFavoriteCount() + record.getVirtualNumber());
                record.setMusicSheetCount(musicAlbumVos.get(0).getMusicSheetCount());
            } else {
                record.setAlbumFavoriteCount(0);
                record.setMusicSheetCount(0);
            }
        }
        return iPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean del(Long id) {
        MusicAlbum musicAlbum = new MusicAlbum();
        musicAlbum.setDelFlag(true);
        musicAlbum.setId(id);
        return this.updateById(musicAlbum);
    }

    @Override
    public IPage<MusicAlbumVo> selectStudentPage(IPage<MusicAlbumVo> page, MusicAlbumSearch query, ClientEnum clientType) {
    	List<MusicAlbumVo> records = baseMapper.selectStudentPage(page, query, clientType);
    	/*if(records == null || records.size() == 0){
    		query.setSubjectIdList(null);
    		records = baseMapper.selectStudentPage(page, query);
    	}*/

        // 设置收藏数
        for (MusicAlbumVo record : records) {
            record.setAlbumFavoriteCount(record.getAlbumFavoriteCount() + record.getVirtualNumber());
        }

        IPage<MusicAlbumVo> iPage = page.setRecords(records);

        List<Long> albumIds = records.stream().map(MusicAlbumVo::getId).collect(Collectors.toList());
        if (query.getUserId() == null || CollectionUtils.isEmpty(albumIds)) {
            return iPage;
        }
        albumIds = albumFavoriteService.selectFavorite(query.getUserId(), albumIds, clientType);
        for (MusicAlbumVo record : records) {
            if(albumIds.contains(record.getId())) {
                record.setFavorite(YesOrNoEnum.YES);
            } else {
                record.setFavorite(YesOrNoEnum.NO);
            }
        }
        return iPage;
    }

    @Override
    public Boolean updateMusicSheet(MusicAlbumSheetSortDto query) {

         return albumMusicRelateService.lambdaUpdate()
                .eq(AlbumMusicRelate::getAlbumId,query.getAlbumId())
                .eq(AlbumMusicRelate::getMusicSheetId,query.getMusicSheetId())
                .set(AlbumMusicRelate::getSortNumber,query.getSortNumber())
                .update();


    }

    @Override
    public ShareProfitVo albumShareProfit(SysUser sysUser, Long albumId) {
        MusicAlbumDetailSearch query = new MusicAlbumDetailSearch();

        query.setId(albumId);
        query.setType(2);
        query.setRows(200);
        query.setState(YesOrNoEnum.YES);
        AlbumDetailVo detail = detail(PageUtil.getPage(query), query, null, null);
        if (detail == null) {
            throw new BizException("未找到专辑信息");
        }
        ShareProfitVo shareProfitVo = new ShareProfitVo();
        ActivityPlanVo activityPlanVo = activityPlanService.activityShare(ActivityShareEnum.VIP, sysUser.getId());
        if (activityPlanVo != null) {
            shareProfitVo.setActivityId(activityPlanVo.getId());
            shareProfitVo.setDiscount(YesOrNoEnum.YES);
        }
        shareProfitVo.setTeacherId(sysUser.getId());
        shareProfitVo.setName(sysUser.getUsername());
        shareProfitVo.setAvatar(sysUser.getAvatar());
        shareProfitVo.setType("ALBUM");
        shareProfitVo.setMusicAlbum(detail);
        return shareProfitVo;
    }

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

    @Override
    public void setVirtualNumber() {

        List<MusicAlbum> musicAlbums = this.lambdaQuery()
                                                .select(MusicAlbum::getId,MusicAlbum::getVirtualNumber)
                                               .eq(MusicAlbum::getAlbumStatus, 1)
                                               .eq(MusicAlbum::getDelFlag, false)
                                                .eq(MusicAlbum::getAuditVersion,0)
                                               .list();
        if (CollectionUtils.isEmpty(musicAlbums)) {
            return;
        }
        //给每个曲目设置增长值
        String value = sysConfigService.findConfigValue(SysConfigConstant.MUSIC_ALBUM_VIRTUAL_NUMBER);
        for (MusicAlbum musicAlbum : musicAlbums) {
            int i = (int) (Math.random() * Integer.parseInt(value));
            musicAlbum.setVirtualNumber(i + musicAlbum.getVirtualNumber());
        }

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

    }

    @Override
    public TenantAlbumWrapper.TenantAlbum detailAlbum(String albumId) {
        Long tenantAlbumId;
        Integer size = 0;
        TenantAlbumWrapper.TenantAlbum album = new TenantAlbumWrapper.TenantAlbum();
        if (StringUtils.isEmpty(albumId)){
            //如果没传专辑id  则查询对应机构的专辑详情
            SysUser sysUser = sysUserFeignService.queryUserInfo();
            Long id = sysUser.getId();
            List<Teacher> list = teacherService.lambdaQuery().eq(Teacher::getUserId, id).list();
            if (CollectionUtils.isEmpty(list)) {
                throw new BizException("老师账号未找到");
            }
            Teacher teacher = list.get(0);
            //获取机构Id
            Long tenantId = teacher.getTenantId();
            //查询对应专辑id
            List<TenantAlbumMusic> tenantAlbumMusicList = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getTenantId, tenantId)
                    .eq(TenantAlbumMusic::getDelFlag,false).list();
            if (CollectionUtils.isEmpty(tenantAlbumMusicList)) {
                album.setTenantAlbumStatus(0);
                return album;
            }

            //TODO
            TenantAlbumMusic tenantAlbumMusic = tenantAlbumMusicList.get(0);
            tenantAlbumId = tenantAlbumMusic.getTenantAlbumId();
        } else {
            //如果传专辑id   则查询这个专辑的详情
            tenantAlbumId = Long.parseLong(albumId);
        }

        //获取对应机构专辑状态
        TenantAlbum one = tenantAlbumService.lambdaQuery().eq(TenantAlbum::getId, tenantAlbumId).last("limit 1").one();
        if (!ObjectUtil.isEmpty(one)){
            album.setStatus(one.getStatus());
        }


        //查询对应专辑的详情
        List<TenantAlbum> list = tenantAlbumService.lambdaQuery().eq(TenantAlbum::getStatus, true).eq(TenantAlbum::getId, tenantAlbumId).list();
        if (CollectionUtils.isEmpty(list)){
            album.setTenantAlbumStatus(0);
            return album;
        }
        album.setTenantAlbumStatus(2);
        //TODO
        TenantAlbum tenantAlbum = list.get(0);
        //机构专辑名称
        String name = tenantAlbum.getName();
        //机构专辑封面
        String coverImg = tenantAlbum.getCoverImg();
        //机构专辑曲目数
        List<TenantAlbumMusic> tenantAlbumMusiclist = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getTenantAlbumId, tenantAlbumId)
                .eq(TenantAlbumMusic::getDelFlag,false).list();
        List<Long> MusicSheetIds = tenantAlbumMusiclist.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(MusicSheetIds)){
            size = musicSheetService.lambdaQuery().in(MusicSheet::getId, MusicSheetIds).eq(MusicSheet::getState, true)
                    .eq(MusicSheet::getDelFlag, false).count();
        }

        //获取合奏曲目数量
        List<TenantAlbumMusic> ensembleLits = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getSubjectType, "ENSEMBLE")
                .eq(TenantAlbumMusic::getTenantAlbumId, tenantAlbumId)
                .eq(TenantAlbumMusic::getDelFlag,false).list();
        List<Long> ensembleMusicSheetIds = ensembleLits.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());

        album.setEnsembleCounts(ensembleMusicSheetIds.size());

        //获取小曲目的曲目数量
        List<TenantAlbumMusic> musicLists = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getSubjectType, "MUSIC")
                .eq(TenantAlbumMusic::getTenantAlbumId, tenantAlbumId)
                .eq(TenantAlbumMusic::getDelFlag,false).list();
        List<Long> musicSheetIds = musicLists.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());

        album.setMusicCounts(musicSheetIds.size());

        //获取声部的曲目数量
        List<TenantAlbumMusic> subjectLists = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getSubjectType, "SUBJECT")
                .eq(TenantAlbumMusic::getTenantAlbumId, tenantAlbumId)
                .eq(TenantAlbumMusic::getDelFlag,false).list();
        List<Long> subjectSheetIds = subjectLists.stream().map(TenantAlbumMusic::getMusicSheetId).collect(Collectors.toList());

        album.setSubjectCounts(subjectSheetIds.size());



        //Integer musicNum = tenantAlbum.getMusicNum();
        //机构专辑简介
        String describe = tenantAlbum.getDescribe();
        //声部
        String subjectTypes = tenantAlbum.getSubjectTypes();

        album.setName(name);
        album.setCoverImg(coverImg);
        album.setMusicNum(size);
        album.setDescribe(describe);
        album.setSubjectTypes(subjectTypes);
        return album;
    }


    @Override
    public TenantAlbumWrapper.TenantAlbum tenantDetailAlbum(String albumId) {
        Integer size = 0;
        Long tenantAlbumId;
        if (StringUtils.isEmpty(albumId)){
            //如果没传专辑id  则查询对应机构的专辑详情
            SysUser sysUser = sysUserFeignService.queryUserInfo();
            Long id = sysUser.getId();
            //List<Teacher> list = teacherService.lambdaQuery().eq(Teacher::getUserId, id).list();
            //查询对应机构Id
            List<TenantStaff> list = tenantStaffService.lambdaQuery().eq(TenantStaff::getUserId,id).list();
            if (CollectionUtils.isEmpty(list)) {
                throw new BizException("未绑定机构");
            }
            TenantStaff tenantStaff = list.get(0);
            //获取机构Id
            Long tenantId = tenantStaff.getTenantId();
            //查询对应专辑id
            List<TenantAlbumMusic> tenantAlbumMusicList = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getTenantId, tenantId)
                    .eq(TenantAlbumMusic::getDelFlag,false).list();
            if (CollectionUtils.isEmpty(tenantAlbumMusicList)) {
                return null;
            }
            TenantAlbumMusic tenantAlbumMusic = tenantAlbumMusicList.get(0);
            tenantAlbumId = tenantAlbumMusic.getTenantAlbumId();
        } else {
            //如果传专辑id   则查询这个专辑的详情
            tenantAlbumId = Long.parseLong(albumId);
        }


        TenantAlbumWrapper.TenantAlbum album = new TenantAlbumWrapper.TenantAlbum();

        //获取对应机构专辑状态
        TenantAlbum one = tenantAlbumService.lambdaQuery().eq(TenantAlbum::getId, tenantAlbumId).last("limit 1").one();
        if (!ObjectUtil.isEmpty(one)){
            album.setStatus(one.getStatus());
        }


        //查询对应专辑的详情
        List<TenantAlbum> list = tenantAlbumService.lambdaQuery().eq(TenantAlbum::getStatus, true).eq(TenantAlbum::getId, tenantAlbumId).list();
        if (CollectionUtils.isEmpty(list)){
            throw new BizException("机构专辑不存在");
        }
        //TODO
        TenantAlbum tenantAlbum = list.get(0);
        //机构专辑名称
        String name = tenantAlbum.getName();
        //机构专辑封面
        String coverImg = tenantAlbum.getCoverImg();
        //机构专辑曲目数
        List<TenantAlbumMusic> tenantAlbumMusiclist = tenantAlbumMusicService.lambdaQuery().eq(TenantAlbumMusic::getTenantAlbumId, tenantAlbumId)
                .eq(TenantAlbumMusic::getDelFlag,false).list();
        List<Long> MusicSheetIds = tenantAlbumMusiclist.stream().map(TenantAlbumMusic::getMusicSheetId).distinct().collect(Collectors.toList());
        //计算符合条件的个数
        if (CollectionUtils.isNotEmpty(MusicSheetIds)){
            size = musicSheetService.lambdaQuery().in(MusicSheet::getId, MusicSheetIds).eq(MusicSheet::getState, true)
                    .eq(MusicSheet::getDelFlag, false).count();
        }

        //Integer musicNum = tenantAlbum.getMusicNum();
        //机构专辑简介
        String describe = tenantAlbum.getDescribe();
        //声部
        String subjectTypes = tenantAlbum.getSubjectTypes();
        //原价
        BigDecimal costPrice = tenantAlbum.getCostPrice();
        //售价
        BigDecimal salePrice = tenantAlbum.getSalePrice();
        //周期
        Integer purchaseCycle = tenantAlbum.getPurchaseCycle();

        album.setId(String.valueOf(tenantAlbum.getId()));
        album.setName(name);
        album.setCoverImg(coverImg);
        album.setMusicNum(size);
        album.setDescribe(describe);
        album.setSubjectTypes(subjectTypes);
        album.setCostPrice(costPrice);
        album.setPurchaseCycle(purchaseCycle);
        album.setSalePrice(salePrice);
        album.setOriginalPrice(tenantAlbum.getOriginalPrice());
        return album;
    }

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

    }

    @Override
    public Map<Long, Long> getMusicCountByIds(List<Long> bizIds) {
        if (CollectionUtils.isEmpty(bizIds)) {
            return new HashMap<>();
        }
        List<AlbumMusicRelate> list = albumMusicRelateService.lambdaQuery()
                .in(AlbumMusicRelate::getAlbumId, bizIds)
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        return list.stream().collect(Collectors.groupingBy(o->o.getAlbumId(),Collectors.counting()));

    }

    private boolean checkNameRepeat(String albumName, Long id) {
        LambdaQueryChainWrapper<MusicAlbum> eq = this.lambdaQuery()
                                                     .eq(MusicAlbum::getDelFlag,0)
                                                   .eq(MusicAlbum::getAlbumName, albumName);
        if (id != null) {
            eq.ne(MusicAlbum::getId,id);
        }
        return eq.count() != 0;
    }
}