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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.StudentDao;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicSheetSearch;
import com.yonge.cooleshow.biz.dal.entity.*;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.PeriodEnum;
import com.yonge.cooleshow.biz.dal.enums.SubjectTypeEnum;
import com.yonge.cooleshow.biz.dal.mapper.*;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.biz.dal.vo.StudentVo;
import com.yonge.cooleshow.biz.dal.wrapper.TenantAlbumWrapper;
import com.yonge.cooleshow.biz.dal.wrapper.TenantGroupAlbumWrapper;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.mybatis.support.PageUtil;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import com.yonge.toolset.utils.obj.ObjectUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import com.yonge.cooleshow.biz.dal.wrapper.UserTenantAlbumRecordWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 购买训练工具记录
 * 2023-07-24 13:32:24
 */
@Slf4j
@Service
public class UserTenantAlbumRecordServiceImpl extends ServiceImpl<UserTenantAlbumRecordMapper, UserTenantAlbumRecord> implements UserTenantAlbumRecordService {

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private TenantAlbumRefService tenantAlbumRefService;

    @Autowired
    private TenantInfoService tenantInfoService;

    @Autowired
    private TenantAlbumMusicService tenantAlbumMusicService;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TenantAlbumService tenantAlbumService;

    @Autowired
    private UserTenantAlbumRecordMapper userTenantAlbumRecordMapper;

    @Autowired
    private StudentDao studentDao;

    @Autowired
    private TenantAlbumPurchaseMapper tenantAlbumPurchaseMapper;

    @Autowired
    private UserTenantAlbumRecordService userTenantAlbumRecordService;


    @Autowired
    private TenantAlbumRefMapper tenantAlbumRefMapper;

    @Autowired
    private TenantAlbumMapper tenantAlbumMapper;

    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TenantInfoMapper tenantInfoMapper;

    @Autowired
    private TenantGroupAlbumService tenantGroupAlbumService;


    @Autowired
    private TenantGroupAlbumMapper tenantGroupAlbumMapper;

    @Autowired
    private TenantAlbumMusicMapper tenantAlbumMusicMapper;
    /**
     * 查询详情
     *
     * @param id 详情ID
     * @return UserTenantAlbumRecord
     */
    @Override
    public UserTenantAlbumRecord detail(Long id) {

        return baseMapper.selectById(id);
    }

    public StudentVo detailStudent(Long userId) {
        return studentDao.detail(userId);
    }

    /**
     * 分页查询
     *
     * @param page  IPage<UserTenantAlbumRecord>
     * @param query UserTenantAlbumRecordWrapper.UserTenantAlbumRecordQuery
     * @return IPage<UserTenantAlbumRecord>
     */
    @Override
    public IPage<TenantAlbumWrapper.TenantAlbum> selectPage(IPage<TenantAlbumWrapper.TenantAlbum> page, UserTenantAlbumRecordWrapper.UserTenantAlbumRecordQuery query) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        Long id = sysUser.getId();
        query.setUserId(sysUser.getId());

        List<TenantAlbumWrapper.TenantAlbum> list = new ArrayList<>();

        //查询生效的机构专辑id
        if (id != null) {
            List<Long> tenantAlbumIds = baseMapper.selectTenantIds(id);
            if (CollectionUtils.isEmpty(tenantAlbumIds)) {
                return null;
            }
            List<TenantAlbum> tenantAlbums = baseMapper.selectTenantAlbumInfo(tenantAlbumIds);

            tenantAlbums.stream().forEach(i -> {
                TenantAlbumWrapper.TenantAlbum vo = JSON.parseObject(JSON.toJSONString(i),
                        TenantAlbumWrapper.TenantAlbum.class);

                //查关联表
                TenantAlbumRef one = tenantAlbumRefService.lambdaQuery().eq(TenantAlbumRef::getTenantAlbumId, i.getId())
                        .last("limit 1").one();
                vo.setTenantId(one.getTenantId().toString());


                TenantInfo tenantInfo = tenantInfoService.getById(one.getTenantId());
                if (tenantInfo != null) {
                    vo.setTenantName(tenantInfo.getName());
                    vo.setTenantImg(tenantInfo.getLogo());
                }
                //查询机构专辑曲目表
                List<TenantAlbumMusic> tenantAlbumMusics = tenantAlbumMusicService.lambdaQuery()
                        .eq(TenantAlbumMusic::getTenantAlbumId, i.getId())
                        .eq(TenantAlbumMusic::getDelFlag, false)
                        .list();

                Map<SubjectTypeEnum, List<TenantAlbumMusic>> groupByType =
                        tenantAlbumMusics.stream().collect(Collectors.groupingBy(TenantAlbumMusic::getSubjectType));

                List<Long> musicSheetIdlist = tenantAlbumMusics.stream().map(next -> next.getMusicSheetId()).distinct().collect(Collectors.toList());

                StudentMusicSheetSearch search = new StudentMusicSheetSearch();
                search.setMusicSheetIdlist(musicSheetIdlist);
                search.setPage(1);
                search.setRows(9999);

                IPage<MusicSheetVo> records = musicSheetService.selectStudentPage(PageUtil.getPage(search), search, ClientEnum.TENANT_STUDENT);

                Map<Long, MusicSheetVo> idMsMap = records.getRecords().stream()
                        .collect(Collectors.toMap(MusicSheet::getId, Function.identity()));

                List<TenantAlbumWrapper.MusicSheetData> musicSheetData = vo.getMusicSheetData();

                groupByType.forEach((key, value) -> {
                    value.sort(Comparator.comparing(TenantAlbumMusic::getSortNumber));
                    TenantAlbumWrapper.MusicSheetData sheetData = new TenantAlbumWrapper.MusicSheetData();
                    sheetData.setSubjectType(key);
                    List<TenantAlbumWrapper.TenantAlbumSheet> tenantAlbumSheets = value.stream().map(next -> {

                        TenantAlbumWrapper.TenantAlbumSheet tenantAlbumSheet = new TenantAlbumWrapper.TenantAlbumSheet();
                        BeanUtils.copyProperties(next, tenantAlbumSheet);
                        Long musicSheetId = tenantAlbumSheet.getMusicSheetId();
                        MusicSheetVo musicSheet = idMsMap.getOrDefault(musicSheetId, new MusicSheetVo());
                        tenantAlbumSheet.setMusicSheetName(musicSheet.getMusicSheetName());
                        tenantAlbumSheet.setMusicTag(musicSheet.getMusicTag());
                        tenantAlbumSheet.setComposer(musicSheet.getComposer());
                        return tenantAlbumSheet;
                    }).collect(Collectors.toList());


                    sheetData.setTenantAlbumSheetList(tenantAlbumSheets);
                    musicSheetData.add(sheetData);
                    vo.setMusicSheetData(musicSheetData);
                });
                list.add(vo);
            });
        }
        return page.setRecords(list);
    }


    /**
     * 分页查询
     *
     * @param page  IPage<UserTenantAlbumRecord>
     * @param query UserTenantAlbumRecordWrapper.UserTenantAlbumRecordQuery
     * @return IPage<UserTenantAlbumRecord>
     */
    @Override
    public IPage<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> selectUserTenantAlbumRecordPage(IPage<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> page,
                                                                                                     UserTenantAlbumRecordWrapper.UserTenantAlbumRecordQuery query) {

        IPage<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> records = page.setRecords(baseMapper.selectUserTenantAlbumRecordPage(page, query));
        List<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> rows = records.getRecords();
        if (CollectionUtils.isNotEmpty(rows)) {
            List<Long> collect = rows.stream().map(UserTenantAlbumRecordWrapper.UserTenantAlbumRecord::getTenantAlbumId).distinct().collect(Collectors.toList());
            Map<Long, String> idNameMap = tenantAlbumService.lambdaQuery()
                    .in(TenantAlbum::getId, collect)
                    .list().stream().collect(Collectors.toMap(TenantAlbum::getId, TenantAlbum::getName));
            rows.forEach(next -> next.setTenantAlbumName(idNameMap.getOrDefault(next.getTenantAlbumId(), "")));
        }
        return records;
    }

    /**
     * 添加
     *
     * @param userTenantAlbumRecord UserTenantAlbumRecordWrapper.UserTenantAlbumRecord
     * @return Boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(UserTenantAlbumRecord userTenantAlbumRecord) {
        Long tenantAlbumId = userTenantAlbumRecord.getTenantAlbumId();
        TenantAlbum tenantAlbum = tenantAlbumMapper.selectById(tenantAlbumId);
        if (tenantAlbum == null || Boolean.TRUE.equals(tenantAlbum.getDelFlag())) {
            throw new BizException("专辑不存在");
        }
        if (Boolean.FALSE.equals(tenantAlbum.getStatus())) {
            throw new BizException("专辑已经停用");
        }

        List<UserTenantAlbumRecord> userTenantAlbumRecords = this.getBaseMapper()
                .selectList(Wrappers.<UserTenantAlbumRecord>lambdaQuery()
                        .eq(UserTenantAlbumRecord::getTenantId, userTenantAlbumRecord.getTenantId())
                        .eq(UserTenantAlbumRecord::getUserId, userTenantAlbumRecord.getUserId())
                        .eq(UserTenantAlbumRecord::getTenantAlbumId, userTenantAlbumRecord.getTenantAlbumId())
                        .eq(UserTenantAlbumRecord::getClientType, ClientEnum.STUDENT)
                        .orderByDesc(UserTenantAlbumRecord::getEndTime));

        Calendar instance = Calendar.getInstance();
        instance.setTime(DateTime.now().withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0).toDate());
        if (!userTenantAlbumRecords.isEmpty()) {
            // 如果最后一次的时间的小于当前时间，则以当前时间为会员的开始时间
            // 如果最后一次的时间的大于当前时间，则以最后一次的结束时间为记录的开始时间，相当会员续期
            UserTenantAlbumRecord lastRecord = userTenantAlbumRecords.get(0);
            Date lastEndTime = lastRecord.getEndTime();
            if (lastEndTime.after(new Date())) {
                instance.setTime(lastEndTime);
            }
        }
        userTenantAlbumRecord.setStartTime(instance.getTime());

        String type = userTenantAlbumRecord.getType();
        if ("DAY".equals(type)) {
            instance.add(Calendar.DAY_OF_MONTH, userTenantAlbumRecord.getTimes());
        } else if ("MONTH".equals(type)) {
            instance.add(Calendar.MONTH, userTenantAlbumRecord.getTimes());
        } else if ("YEAR".equals(type)) {
            instance.add(Calendar.YEAR, userTenantAlbumRecord.getTimes());
        } else {
            throw new BizException("不支持的周期类型");
        }

        instance.set(Calendar.HOUR_OF_DAY, 23);
        instance.set(Calendar.MINUTE, 59);
        instance.set(Calendar.SECOND, 59);
        instance.set(Calendar.MILLISECOND, 0);
        userTenantAlbumRecord.setEndTime(instance.getTime());
        userTenantAlbumRecord.setCreateTime(new Date());
        userTenantAlbumRecord.setUpdateTime(new Date());
        this.save(userTenantAlbumRecord);

        SysUser sysUser = sysUserMapper.getByUserId(userTenantAlbumRecord.getUserId());
        sendMessage(userTenantAlbumRecord.getUserId(), sysUser.getPhone(), ClientEnum.STUDENT, userTenantAlbumRecord.getTimes(), PeriodEnum.valueOf(userTenantAlbumRecord.getType()),
                tenantAlbum.getName(), userTenantAlbumRecord.getReason());
        return true;
    }

    private void sendMessage(Long userId, String phone, ClientEnum client, Integer times, PeriodEnum type, String tenantAlbumName, String reason) {
        try {
            Map<Long, String> receivers = new HashMap<>();
            receivers.put(userId, phone);
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.USER_TENANT_ALBUM_VIP,
                    receivers, null, 0, null, client.getCode(), times, type.getMsg(), tenantAlbumName, reason);
        } catch (Exception e) {
            log.error("机构专辑会员赠送消息发送失败 ： {}", e.getMessage());
        }
    }

    /**
     * 更新
     *
     * @param userTenantAlbumRecord UserTenantAlbumRecordWrapper.UserTenantAlbumRecord
     * @return Boolean
     */
    @Override
    public Boolean update(UserTenantAlbumRecordWrapper.UserTenantAlbumRecord userTenantAlbumRecord) {

        return this.updateById(JSON.parseObject(userTenantAlbumRecord.jsonString(), UserTenantAlbumRecord.class));
    }


    /**
     * 获取最新的购买记录
     *
     * @param tenantId   机构ID
     * @param userId     用户ID
     * @param clientType 客户端类型
     */
    @Override
    public UserTenantAlbumRecord getNewestByTenantIdAndUserId(Long tenantId, Long userId, ClientEnum clientType) {
        List<UserTenantAlbumRecord> recordList = getNewestByTenantIdAndUserId(tenantId, userId, clientType, null);
        if (CollectionUtils.isEmpty(recordList)) {
            return null;
        }
        return recordList.get(0);
    }

    /**
     * 获取最新的购买记录
     *
     * @param tenantId   机构ID
     * @param userId     用户ID
     * @param clientType 客户端类型
     */
    @Override
    public List<UserTenantAlbumRecord> getNewestByTenantIdAndUserId(Long tenantId, Long userId, ClientEnum clientType, List<Long> tenantAlbumIds) {
        if (tenantId == null || userId == null || clientType == null) {
            return new ArrayList<>();
        }
        return this.lambdaQuery()
                .eq(UserTenantAlbumRecord::getTenantId, tenantId)
                .eq(UserTenantAlbumRecord::getUserId, userId)
                .eq(UserTenantAlbumRecord::getClientType, clientType)
                .in(CollectionUtils.isNotEmpty(tenantAlbumIds), UserTenantAlbumRecord::getTenantAlbumId, tenantAlbumIds)
                .ge(UserTenantAlbumRecord::getEndTime, new Date())
                .orderByDesc(UserTenantAlbumRecord::getEndTime)
                .list();
    }

    @Override
    public List<Long> getUseAlbumIdsByUserId(Long userId, ClientEnum clientType) {
        if (userId == null) {
            return new ArrayList<>();
        }
        List<UserTenantAlbumRecord> list = this.lambdaQuery()
                .eq(UserTenantAlbumRecord::getUserId, userId)
                .eq(UserTenantAlbumRecord::getClientType, clientType)
                .ge(UserTenantAlbumRecord::getEndTime, new Date())
                .list();
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(UserTenantAlbumRecord::getTenantAlbumId).distinct().collect(Collectors.toList());

    }

    @Override
    public TenantAlbumWrapper.TenantAlbum detailAlbum(String albumId) {

        Integer size = 0;
        TenantAlbumWrapper.TenantAlbum album = new TenantAlbumWrapper.TenantAlbum();

        //如果没传专辑id  则查询对应机构的专辑详情
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            throw new BizException("用户不存在");
        }
        List<Long>  tenantAlbumIds = new ArrayList<>();
        Long tenantAlbumId;

        if (StringUtils.isEmpty(albumId)) {
            Long id = sysUser.getId();
            Student student = studentService.getById(id);
            //获取机构Id
            Long tenantId = student.getTenantId();

            // 如果没有小组， 就没有专辑
            if (student.getTenantGroupId() == null || tenantId ==null || tenantId <=0) {

                album.setTenantAlbumStatus(0);
                album.setTenantAlbumFlag(YesOrNoEnum.NO);
                return album;
            } else {
                //查询对应小组专辑id
                List<TenantGroupAlbum> list = tenantGroupAlbumService.lambdaQuery()
                    .eq(TenantGroupAlbum::getTenantGroupId, student.getTenantGroupId())
                    .eq(TenantGroupAlbum::getDelFlag, false)
                    .eq(TenantGroupAlbum::getStatus, true)
                    .list();
                if (CollectionUtils.isEmpty(list)) {
                    album.setTenantAlbumStatus(0);
                    album.setTenantAlbumFlag(YesOrNoEnum.NO);
                    return album;
                }
                // 专辑ID集合
                tenantAlbumIds = list.stream().map(TenantGroupAlbum::getTenantAlbumId).distinct().collect(Collectors.toList());

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

        StudentVo detail = detailStudent(sysUser.getId());
        // 判断是否是机构学生 机构学生 检测机构专辑购买记录
        TenantInfo tenantInfo = tenantInfoService.detail(detail.getTenantId());
        if (tenantInfo != null) {
            album.setTenantAlbumStatus(0);
            album.setTenantName(tenantInfo.getName());
            QueryWrapper<TenantAlbumRef> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TenantAlbumRef::getTenantId, detail.getTenantId());
            List<TenantAlbumRef> albumRefs = tenantAlbumRefMapper.selectList(queryWrapper);
            if (!albumRefs.isEmpty()) {
                List<Long> albIds = albumRefs.stream().map(TenantAlbumRef::getTenantAlbumId).distinct().collect(Collectors.toList());
                QueryWrapper<TenantAlbum> query = new QueryWrapper<>();
                query.lambda().in(TenantAlbum::getId, albIds)
                    .eq(TenantAlbum::getStatus, true);
                Integer count = tenantAlbumMapper.selectCount(query);
                if (count > 0) {
                    album.setTenantAlbumStatus(1);
                }
            }
            UserTenantAlbumRecord record =
                userTenantAlbumRecordService.getNewestByTenantIdAndUserId(tenantInfo.getId(), detail.getUserId(),
                    ClientEnum.STUDENT);
            if (record == null || record.getEndTime().getTime() < System.currentTimeMillis()) {
                album.setTenantAlbumFlag(YesOrNoEnum.NO);
            } else {
                album.setTenantAlbumStatus(2);
                album.setTenantAlbumFlag(YesOrNoEnum.YES);
                album.setTenantAlbumStartTime(record.getStartTime());
                album.setTenantAlbumEndTime(record.getEndTime());
            }
        }


        //查询是否已经购买专辑
        List<Long> buyTenantAlbumId = userTenantAlbumRecordMapper.ifBuy(Lists.newArrayList(tenantAlbumId), sysUser.getId());

        album.setIfBuy(CollectionUtils.isNotEmpty(buyTenantAlbumId));


        //查询对应专辑的详情
        List<TenantAlbum> list = tenantAlbumService.lambdaQuery().eq(TenantAlbum::getId, tenantAlbumId).list();
        if (CollectionUtils.isEmpty(list)) {
            throw new BizException("机构专辑不存在");
        }
        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();

        //获取合奏曲目数量
        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).distinct().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).distinct().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).distinct().collect(Collectors.toList());

        album.setSubjectCounts(subjectSheetIds.size());


        //机构专辑简介
        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);
        return album;
    }

    @Nullable
    private TenantAlbumWrapper.TenantAlbum getTenantAlbum(SysUser sysUser, TenantAlbumWrapper.TenantAlbum album, List<Long> tenantAlbumIds) {
        StudentVo detail = detailStudent(sysUser.getId());

        // 判断是否是机构学生 机构学生 检测机构专辑购买记录
        TenantInfo tenantInfo = tenantInfoService.detail(detail.getTenantId());
        if (tenantInfo == null) {
            return album;
        }

        // 判断小组有没有曲目 ，小组有曲目有专辑
        TenantGroupAlbumWrapper.BuyTenantAlbumQuery query = new TenantGroupAlbumWrapper.BuyTenantAlbumQuery();
        query.setTenantAlbumIds(tenantAlbumIds);
        List<TenantGroupAlbumWrapper.BuyTenantAlbum> buyAlbumInfo = tenantGroupAlbumMapper.getBuyAlbumInfo(query);
        if (CollectionUtils.isNotEmpty(buyAlbumInfo)) {
            album.setTenantAlbumStatus(1);
        }  else {
            album.setTenantAlbumStatus(0);
            return album;
        }

        tenantAlbumIds = buyAlbumInfo.stream().map(TenantGroupAlbumWrapper.BuyTenantAlbum::getId).collect(Collectors.toList());

        //获取对应机构专辑状态
        List<TenantAlbum> albumList = tenantAlbumService.lambdaQuery()
            .in(TenantAlbum::getId, tenantAlbumIds)
            .list();
        if (CollectionUtils.isEmpty(albumList)) {
            throw new BizException("专辑不存在");
        }
        //查询是否已经购买专辑
        List<Long> ifedBuy = userTenantAlbumRecordMapper.ifBuy(tenantAlbumIds, sysUser.getId());

        if (CollectionUtils.isNotEmpty(ifedBuy)) {
            album.setIfBuy(true);
            album.setTenantAlbumStatus(2);
            tenantAlbumIds = ifedBuy;
        } else {
            album.setIfBuy(false);
        }


        //查询对应专辑的详情
//        TenantAlbum tenantAlbum = albumList.get(0);
        //机构专辑曲目数

        List<TenantAlbumMusic> list = tenantAlbumMusicMapper.getByAlbumAndEnable(tenantAlbumIds);
        // 根据专辑ID分组 在根据声部分类 分组
        Map<Long, Map<SubjectTypeEnum, Long>> map = list.stream()
            .collect(Collectors.groupingBy(TenantAlbumMusic::getTenantAlbumId, Collectors.groupingBy(TenantAlbumMusic::getSubjectType,Collectors.counting())));

        Set<String> subjectTypes = new HashSet<>();

        int size = 0;
        int musicSize = 0;
        int ensembleSize = 0;
        int subjectSize = 0;
        for (TenantGroupAlbumWrapper.BuyTenantAlbum buyTenantAlbum : buyAlbumInfo) {
            Map<SubjectTypeEnum, Long> subjectTypeEnumLongMap = map.get(buyTenantAlbum.getId());
            if (subjectTypeEnumLongMap != null) {
                buyTenantAlbum.setMusicCounts(subjectTypeEnumLongMap.getOrDefault(SubjectTypeEnum.MUSIC,0L).intValue());
                buyTenantAlbum.setEnsembleCounts(subjectTypeEnumLongMap.getOrDefault(SubjectTypeEnum.ENSEMBLE,0L).intValue());
                buyTenantAlbum.setSubjectCounts(subjectTypeEnumLongMap.getOrDefault(SubjectTypeEnum.SUBJECT,0L).intValue());
            } else {
                buyTenantAlbum.setMusicCounts(0);
                buyTenantAlbum.setEnsembleCounts(0);
                buyTenantAlbum.setSubjectCounts(0);
            }
            buyTenantAlbum.setMusicNum(buyTenantAlbum.getMusicCounts() + buyTenantAlbum.getEnsembleCounts()+buyTenantAlbum.getSubjectCounts());
            if (buyTenantAlbum.getMusicNum() > 0) {
                subjectTypes.add(SubjectTypeEnum.MUSIC.name());
            }
            if (buyTenantAlbum.getEnsembleCounts() > 0) {
                subjectTypes.add(SubjectTypeEnum.ENSEMBLE.name());
            }
            if (buyTenantAlbum.getSubjectCounts() > 0) {
                subjectTypes.add(SubjectTypeEnum.SUBJECT.name());
            }
            size += buyTenantAlbum.getMusicNum();
            musicSize += buyTenantAlbum.getMusicCounts();
            ensembleSize += buyTenantAlbum.getEnsembleCounts();
            subjectSize += buyTenantAlbum.getSubjectCounts();

        }

        //机构专辑简介
        album.setEnsembleCounts(ensembleSize);
        album.setMusicCounts(musicSize);
        album.setSubjectCounts(subjectSize);
//        album.setId(String.valueOf(tenantAlbum.getId()));
//        album.setName(tenantAlbum.getName());
//        album.setCoverImg(tenantAlbum.getCoverImg());
        album.setMusicNum(size);
//        album.setDescribe(tenantAlbum.getDescribe());
        album.setSubjectTypes(subjectTypes.stream().collect(Collectors.joining(",")));
//        album.setCostPrice(tenantAlbum.getCostPrice());
//        album.setPurchaseCycle(tenantAlbum.getPurchaseCycle());
//        album.setSalePrice(tenantAlbum.getSalePrice());
        return album;
    }

    @Override
    public void sendTenantAlbumMessage() {
        List<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> userTenantAlbumRecords = baseMapper.selectTemporaryRecord();
        if (CollectionUtils.isEmpty(userTenantAlbumRecords)) {
            return;
        }
        //标识
        Map<Long, Long> temporaryFlagMap = new HashMap<>();
        for (UserTenantAlbumRecordWrapper.UserTenantAlbumRecord record : userTenantAlbumRecords) {
            if (null != temporaryFlagMap.get(record.getUserId())) {
                continue;
            }
            temporaryFlagMap.put(record.getUserId(), record.getUserId());
            //发送消息
            CompletableFuture.runAsync(() -> temporarySend(record.getUserId(), record.getTenantAlbumId()));
            UserTenantAlbumRecord userTenantAlbumRecord = new UserTenantAlbumRecord();
            userTenantAlbumRecord.setMsgStatus(true);
            userTenantAlbumRecord.setUpdateTime(new Date());
            userTenantAlbumRecord.setId(record.getId());

            baseMapper.updateById(userTenantAlbumRecord);
        }
    }

    @Override
    public UserTenantAlbumRecord getNewestByTenantAlbumId(Long tenantAlbumId, Long userId, ClientEnum client) {

        return this.lambdaQuery()
                .eq(UserTenantAlbumRecord::getTenantAlbumId, tenantAlbumId)
                .eq(UserTenantAlbumRecord::getUserId, userId)
                .eq(UserTenantAlbumRecord::getClientType, client)
                .ge(UserTenantAlbumRecord::getEndTime, new Date())
                .orderByDesc(UserTenantAlbumRecord::getEndTime)
                .last("limit 1")
                .one();
    }

    @Override
    public List<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> list(UserTenantAlbumRecordWrapper.UserTenantAlbumRecordQuery query) {

        List<Long> tenantAlbumIdList = new ArrayList<>();
        Long tenantGroupId = query.getTenantGroupId();
        if (tenantGroupId != null) { // 学生只看当前就够的专辑列表
            QueryWrapper<TenantGroupAlbum> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(TenantGroupAlbum::getTenantGroupId, tenantGroupId)
                    .eq(TenantGroupAlbum::getDelFlag, false)
                    .eq(TenantGroupAlbum::getStatus, true);
            List<TenantGroupAlbum> tenantGroupAlbums = tenantGroupAlbumMapper.selectList(queryWrapper);
            if (CollectionUtils.isEmpty(tenantGroupAlbums)) {
                return new ArrayList<>();
            }
            tenantAlbumIdList = tenantGroupAlbums.stream().map(TenantGroupAlbum::getTenantAlbumId).distinct().collect(Collectors.toList());
        }

        List<UserTenantAlbumRecord> list = this.lambdaQuery()
                .eq(UserTenantAlbumRecord::getUserId, query.getUserId())
                .ge(query.getEndTime() != null, UserTenantAlbumRecord::getEndTime, query.getEndTime())
                .in(CollectionUtils.isNotEmpty(tenantAlbumIdList), UserTenantAlbumRecord::getTenantAlbumId, tenantAlbumIdList)
                .list();
        if (list.size() == 0) {
            return new ArrayList<>();
        }

        // 去重
        list.sort(Comparator.comparing(UserTenantAlbumRecord::getEndTime));
        List<UserTenantAlbumRecord> reverse = Lists.reverse(list);
        List<UserTenantAlbumRecord> collect = reverse.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(UserTenantAlbumRecord::getTenantAlbumId))), ArrayList::new));

        List<UserTenantAlbumRecordWrapper.UserTenantAlbumRecord> userTenantAlbumRecords = JSON.parseArray(JSON.toJSONString(collect), UserTenantAlbumRecordWrapper.UserTenantAlbumRecord.class);
        List<Long> tenantAlbumIds = userTenantAlbumRecords.stream().map(UserTenantAlbumRecordWrapper.UserTenantAlbumRecord::getTenantAlbumId).collect(Collectors.toList());
        Map<Long, TenantAlbum> albumIdMap = tenantAlbumService.lambdaQuery()
                .in(TenantAlbum::getId, tenantAlbumIds)
                .list().stream().collect(Collectors.toMap(TenantAlbum::getId, Function.identity()));

        userTenantAlbumRecords.forEach(next -> {
            TenantAlbum orDefault = albumIdMap.getOrDefault(next.getTenantAlbumId(), new TenantAlbum());
            next.setTenantAlbumName(orDefault.getName());
            next.setTenantAlbumCoverImg(orDefault.getCoverImg());
        });
        return userTenantAlbumRecords;
    }


    private void temporarySend(Long userId, Long tenantAlbumId) {
        SysUser sysUser = sysUserFeignService.queryUserById(userId);
        if (null == sysUser) {
            return;
        }
        TenantAlbum tenantAlbum = tenantAlbumService.getById(tenantAlbumId);
        if (tenantAlbum == null) {
            return;
        }
        Map<Long, String> receivers = new HashMap<>();
        receivers.put(userId, sysUser.getPhone());

        try {
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.TENANT_ALBUM_EXPIRE,
                    receivers, null, 0, null, ClientEnum.TENANT_STUDENT.getCode(), tenantAlbum.getName());
        } catch (Exception e) {
            log.error("机构学生训练教材过期", e);
        }
    }
}