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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.biz.dal.dao.CourseCoursewareDao;
import com.yonge.cooleshow.biz.dal.dao.MusicSheetAccompanimentDao;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dto.MusicSheetAccompanimentResult;
import com.yonge.cooleshow.biz.dal.dto.search.CourseCoursewareSearch;
import com.yonge.cooleshow.biz.dal.entity.CourseCourseware;
import com.yonge.cooleshow.biz.dal.entity.MusicSheetAccompaniment;
import com.yonge.cooleshow.biz.dal.entity.SysUser;
import com.yonge.cooleshow.biz.dal.entity.Teacher;
import com.yonge.cooleshow.biz.dal.enums.AudioTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.mapper.SysUserMapper;
import com.yonge.cooleshow.biz.dal.service.CourseCoursewareService;
import com.yonge.cooleshow.biz.dal.service.MusicSheetService;
import com.yonge.cooleshow.biz.dal.service.TenantAlbumMusicService;
import com.yonge.cooleshow.biz.dal.vo.CourseCoursewareVo;
import com.yonge.cooleshow.biz.dal.vo.MusicSheetDetailVo;
import com.yonge.cooleshow.biz.dal.vo.TeacherVo;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service
public class CourseCoursewareServiceImpl extends ServiceImpl<CourseCoursewareDao, CourseCourseware> implements CourseCoursewareService {
    private final static Logger log = LoggerFactory.getLogger(CourseCoursewareServiceImpl.class);


    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private MusicSheetService musicSheetService;

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private MusicSheetAccompanimentDao musicSheetAccompanimentDao;

    @Autowired
    private TeacherDao teacherDao;

    @Autowired
    private TenantAlbumMusicService tenantAlbumMusicService;

	@Override
    public CourseCoursewareVo detail(Long id) {
        return baseMapper.detail(id);
    }
    
    @Override
    public IPage<CourseCoursewareVo> selectPage(IPage<CourseCoursewareVo> page, CourseCoursewareSearch query){
        IPage<CourseCoursewareVo> courseCoursewareVoIPage = page.setRecords(baseMapper.selectPage(page, query));
        List<CourseCoursewareVo> records = courseCoursewareVoIPage.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            return courseCoursewareVoIPage;
        }
        // 设置用户名
        Set<Long> userIdList = records.stream().map(CourseCoursewareVo::getUserId).collect(Collectors.toSet());
        List<SysUser> sysUsers = userMapper.selectBatchIds(userIdList);
        if (CollectionUtils.isEmpty(sysUsers)) {
            return courseCoursewareVoIPage;
        }
        Map<Long, String> userIdUsernameMap = sysUsers.stream().collect(Collectors.toMap(SysUser::getId, SysUser::getUsername));
        //获取曲目关联的伴奏
        List<Long> musicSheetIds = records.stream().map(e -> e.getMusicSheetId()).distinct().collect(Collectors.toList());
        Map<Long, MusicSheetAccompaniment> accoompanimentMap = musicSheetAccompanimentDao.selectList(
                        Wrappers.<MusicSheetAccompaniment>lambdaQuery()
                                .in(MusicSheetAccompaniment::getMusicSheetId, musicSheetIds)).stream()
                .collect(Collectors.groupingBy(MusicSheetAccompaniment::getMusicSheetId, Collectors.collectingAndThen(Collectors.toList(), e -> e.get(0))));
        for (CourseCoursewareVo record : records) {
            record.setUsername(userIdUsernameMap.get(record.getUserId()));
            MusicSheetAccompaniment musicSheetAccompaniment = accoompanimentMap.get(record.getMusicSheetId());
            if (musicSheetAccompaniment != null) {
                record.setMusicSheetAccompanimentId(musicSheetAccompaniment.getId());
            }
        }

        // 设置原音
        List<Long> musicSheetIdList = records.stream().map(CourseCoursewareVo::getMusicSheetId).collect(Collectors.toList());
        List<MusicSheetAccompaniment> musicSheetAccompanimentList = musicSheetAccompanimentDao.selectList(
                Wrappers.<MusicSheetAccompaniment>lambdaQuery()
                        .in(MusicSheetAccompaniment::getMusicSheetId, musicSheetIdList));
        if (CollectionUtils.isNotEmpty(musicSheetAccompanimentList)) {
            Map<Long, List<MusicSheetAccompaniment>> map = musicSheetAccompanimentList.stream()
                                                          .collect( Collectors.groupingBy(MusicSheetAccompaniment::getMusicSheetId));
            for (CourseCoursewareVo record : records) {
                List<MusicSheetAccompaniment> musicSheetAccompaniments = map.get(record.getMusicSheetId());
                if (CollectionUtils.isEmpty(musicSheetAccompaniments)) {
                    continue;
                }
                String url = musicSheetAccompaniments.stream()
                                                         .map(MusicSheetAccompaniment::getAudioFileUrl)
                                                         .collect(Collectors.joining(","));
                record.setMp3url(url);
            }
        }



        // 查询有效直接返回
        if (query.getStatus() != null && query.getStatus().equals(YesOrNoEnum.YES)) {
            records = records.stream()
                   .peek(record -> record.setStatus(YesOrNoEnum.YES)).collect(Collectors.toList());
            courseCoursewareVoIPage.setRecords(records);
            return courseCoursewareVoIPage;
        }
        // 设置课件失效

        // 1.判断曲目启用
        for (CourseCoursewareVo record : records) {
            if (record.getMusicStatus().equals(YesOrNoEnum.NO)) {
                record.setStatus(YesOrNoEnum.NO);
            }
        }

        // 1. 判断免费

        for (CourseCoursewareVo record : records) {
            if (record.getPaymentType().contains("FREE") && record.getStatus() == null) {
                record.setStatus(YesOrNoEnum.YES);
            }
        }

        // 2. 判断是否购买曲目或专辑
        List<Long> coursewareIdList = records.stream()
                                    .filter(record -> record.getStatus() == null)
                                    .map(CourseCoursewareVo::getId)
                                    .collect(Collectors.toList());

        coursewareIdList = baseMapper.selectPayMusic(coursewareIdList);

        for (CourseCoursewareVo record : records) {
            if (coursewareIdList.contains(record.getId())) {
                record.setStatus(YesOrNoEnum.YES);
            }
        }
        // 4. 判断会员

        List<Teacher> teachers = teacherDao.selectBatchIds(userIdList);
        userIdList = new HashSet<>();
        for (Teacher teacher : teachers) {
            if (teacher.getMembershipEndTime() != null && teacher.getMembershipEndTime().compareTo(new Date()) > 0) {
                userIdList.add(teacher.getUserId());
            }
        }

        for (CourseCoursewareVo record : records) {
            if (record.getPaymentType().contains("VIP") && record.getStatus() == null && userIdList.contains(record.getUserId())) {
                record.setStatus(YesOrNoEnum.YES);
            }
        }
        for (CourseCoursewareVo record : records) {
            if (record.getStatus() == null) {
                record.setStatus(YesOrNoEnum.NO);
            }
        }

        // 查询老师所在机构存在机构曲目
        if (query.getClientType().equals(ClientEnum.TEACHER)) {
            TeacherVo detail = teacherDao.detail(query.getUserId());
            if (detail != null) {
                List<Long> list = tenantAlbumMusicService.getMusicIdsByTenantIds(detail.getTenantId());

                for (CourseCoursewareVo record : records) {
                    if (list.contains(record.getMusicSheetId())) {
                        record.setStatus(YesOrNoEnum.YES);
                    }
                }
            }
        }

        courseCoursewareVoIPage.setRecords(records);
        return courseCoursewareVoIPage;
    }

    @Override
    public boolean removeById(Serializable id) {
        return super.removeById(id);
        // CourseCourseware courseCourseware = new CourseCourseware();
        // courseCourseware.setId((Long) id);
        // courseCourseware.setDelFlag(true);
        // return updateById(courseCourseware);
    }

    @Override
    public CourseCourseware submit(CourseCourseware courseCourseware) {

        // 判断用户
        com.yonge.cooleshow.auth.api.entity.SysUser user = sysUserFeignService.queryUserById(
                courseCourseware.getUserId());
        if (user == null) {
            throw new BizException("用户信息未找到");
        }

        // 判断是否已经添加到附件
        Integer count = this.lambdaQuery()
                            .eq(CourseCourseware::getDelFlag, false)
                            .eq(CourseCourseware::getUserId, courseCourseware.getUserId())
                            .eq(CourseCourseware::getMusicSheetId, courseCourseware.getMusicSheetId())
                            .eq(CourseCourseware::getClientType, courseCourseware.getClientType())
                            .count();
        if (count >0 ) {
            throw new BizException("当前曲目已经添加到附件");
        }

        // 判断是否有权限添加
        MusicSheetDetailVo detail = musicSheetService.detail(courseCourseware.getMusicSheetId(), user,
                                                             courseCourseware.getClientType());

        if (detail == null) {
            throw new BizException("曲目不存在");
        }
        // 判断是否为MP3
        if (detail.getAudioType().equals(AudioTypeEnum.MIDI)) {
            throw new BizException("该曲目不支持添加到课件");
        }

        if (detail.getPlay().equals(YesOrNoEnum.NO)) {
            if (detail.getPaymentType().contains("VIP") && detail.getPaymentType().contains("CHARGE")) {
                throw new BizException("请先开通会员或购买曲目");
            } else if (detail.getPaymentType().contains("VIP")) {
                throw new BizException("请先开通会员");
            } else if (detail.getPaymentType().contains("CHARGE")) {
                throw new BizException("请先购买曲目");
            } else {
                throw new BizException("该曲目不支持添加到课件");
            }
        }
        this.saveOrUpdate(courseCourseware);
        return courseCourseware;
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        return super.removeByIds(idList);
        // List<CourseCourseware> list = new ArrayList<>();
        // for (Serializable id : idList) {
        //     CourseCourseware courseCourseware = new CourseCourseware();
        //     courseCourseware.setId((Long) id);
        //     courseCourseware.setDelFlag(true);
        //     list.add(courseCourseware);
        // }
        // return updateBatchById(list);
    }
}