package com.ym.mec.biz.service.impl;

import com.ym.mec.biz.dal.dao.MusicGroupPaymentStudentCourseDetailDao;
import com.ym.mec.biz.dal.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ym.mec.biz.dal.dao.MusicGroupPaymentCalenderCourseSettingsDao;
import com.ym.mec.biz.service.MusicGroupPaymentCalenderCourseSettingsService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import org.springframework.util.CollectionUtils;

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

@Service
public class MusicGroupPaymentCalenderCourseSettingsServiceImpl extends BaseServiceImpl<Integer, MusicGroupPaymentCalenderCourseSettings>  implements MusicGroupPaymentCalenderCourseSettingsService {
	
	@Autowired
	private MusicGroupPaymentCalenderCourseSettingsDao musicGroupPaymentCalenderCourseSettingsDao;
	@Autowired
	private MusicGroupPaymentStudentCourseDetailDao musicGroupPaymentStudentCourseDetailDao;

	@Override
	public BaseDAO<Integer, MusicGroupPaymentCalenderCourseSettings> getDAO() {
		return musicGroupPaymentCalenderCourseSettingsDao;
	}

	@Override
	public Map<String, Integer> getMusicCourseSettingsWithStudents(String musicGroupId, List<Integer> studentIds) {
		List<MusicGroupPaymentStudentCourseDetail> mgpscds = musicGroupPaymentStudentCourseDetailDao.getUnUseWithStudents(musicGroupId, studentIds);
		if(CollectionUtils.isEmpty(mgpscds)){
			return Collections.emptyMap();
		}
		Map<String, Integer> result = new HashMap<>();
		Map<CourseSchedule.CourseScheduleType, List<MusicGroupPaymentStudentCourseDetail>> courseTypeDetailsMap = mgpscds.stream().collect(Collectors.groupingBy(MusicGroupPaymentStudentCourseDetail::getCourseType));
		for (Map.Entry<CourseSchedule.CourseScheduleType, List<MusicGroupPaymentStudentCourseDetail>> courseTypeDetailsEntry : courseTypeDetailsMap.entrySet()) {
			Map<Integer, List<MusicGroupPaymentStudentCourseDetail>> userDetailsMap = courseTypeDetailsEntry.getValue().stream().collect(Collectors.groupingBy(MusicGroupPaymentStudentCourseDetail::getUserId));
			if(CollectionUtils.isEmpty(userDetailsMap)||userDetailsMap.keySet().size()!=studentIds.size()){
				continue;
			}
			List<MusicGroupPaymentStudentCourseDetail> details = new ArrayList<>();
			for (Map.Entry<Integer, List<MusicGroupPaymentStudentCourseDetail>> userDetailsEntry : userDetailsMap.entrySet()) {
				details.add(userDetailsEntry.getValue().stream().min(Comparator.comparing(MusicGroupPaymentStudentCourseDetail::getId)).get());
			}
			result.put(courseTypeDetailsEntry.getKey().getCode(), details.stream().min(Comparator.comparing(MusicGroupPaymentStudentCourseDetail::getTotalCourseMinutes)).get().getTotalCourseMinutes());
		}
		return result;
	}
}
