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

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.search.MusicAlbumDetailSearch;
import com.yonge.cooleshow.biz.dal.dto.search.MusicAlbumSearch;
import com.yonge.cooleshow.biz.dal.dto.search.StudentMusicAlbumSearch;
import com.yonge.cooleshow.biz.dal.entity.AlbumFavorite;
import com.yonge.cooleshow.biz.dal.entity.MusicAlbum;
import com.yonge.cooleshow.biz.dal.entity.MusicSheet;
import com.yonge.cooleshow.biz.dal.enums.YesOrNoEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.support.PageUtil;
import com.yonge.cooleshow.biz.dal.vo.AlbumDetailVo;
import com.yonge.cooleshow.biz.dal.vo.MusicAlbumVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetVo;
import com.yonge.cooleshow.common.exception.BizException;
import com.yonge.toolset.utils.string.StringUtil;
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 org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

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

    @Autowired
    private MusicAlbumDao musicAlbumDao;

    @Autowired
    private AlbumMusicRelateService albumMusicRelateService;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private MusicTagService musicTagService;

    @Autowired
    private AlbumFavoriteService albumFavoriteService;

    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) {
        MusicAlbum musicAlbum = this.getById(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.setAlbumStatue(musicAlbum.getAlbumStatus());
        albumDetailVo.setMusicTagNames(musicTagService.getMusicTagNames(StringUtil.toLongList(musicAlbum.getAlbumTag())));

        IPage<MusicSheetVo> musicSheetVoIPage = musicSheetService.selectAlbumDetailPage(page,query);
        albumDetailVo.setMusicSheetList(PageUtil.pageInfo(musicSheetVoIPage));
        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("未找到专辑信息");
        }
        List<Long> musicSheetIdList = StringUtil.toLongList(musicSheetIds);
        return albumMusicRelateService.delMusicSheet(albumId,musicSheetIdList);
    }

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createMusicAlbum(MusicAlbum musicAlbum) {
        if (checkNameRepeat(musicAlbum.getAlbumName(),musicAlbum.getId())) {
            throw new BizException("专辑名称重复");
        }
        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("专辑名称重复");
        }
        return this.updateById(musicAlbum);
    }

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setFavorite(Long studentId, Long albumId) {
        List<AlbumFavorite> albumFavorites = albumFavoriteService.getFavorite(studentId,albumId);
        if (CollectionUtils.isEmpty(albumFavorites)) {
            AlbumFavorite albumFavorite = new AlbumFavorite();
            albumFavorite.setAlbumId(albumId);
            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) {

        IPage<MusicAlbumVo> iPage = page.setRecords(baseMapper.selectFavoritePage(page, search));
        List<MusicAlbumVo> records = iPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return iPage;
        }
        List<MusicAlbumVo> favoriteNumAndMusicNumList =baseMapper.selectFavoriteNumAndMusicNum(records);

        for (int i = 0; i < records.size(); i++) {
            records.get(i).setAlbumFavoriteCount(favoriteNumAndMusicNumList.get(i).getAlbumFavoriteCount());
            records.get(i).setMusicSheetCount(favoriteNumAndMusicNumList.get(i).getMusicSheetCount());
        }
        return iPage;
    }

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

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