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

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.ym.mec.biz.dal.dao.CourseScheduleStudentPaymentDao;
import com.ym.mec.biz.dal.dao.StudentDao;
import com.ym.mec.biz.dal.dto.StudentCourseTimesDto;
import com.ym.mec.biz.dal.dto.StudentTeacherCourseDto;
import com.ym.mec.biz.dal.entity.CourseSchedule;
import com.ym.mec.biz.dal.entity.Student;
import com.ym.mec.biz.dal.page.StudentQueryInfo;
import com.ym.mec.biz.service.StudentService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;

@Service
public class StudentServiceImpl extends BaseServiceImpl<Integer, Student> implements StudentService {

	@Autowired
	private StudentDao studentDao;
	
	@Autowired
	private CourseScheduleStudentPaymentDao courseScheduleStudentPaymentDao;

	@Override
	public BaseDAO<Integer, Student> getDAO() {
		return studentDao;
	}

	@Override
	public PageInfo findStudentVipGroupList(StudentQueryInfo queryInfo) {
		PageInfo pageInfo = new PageInfo<>(queryInfo.getPage(), queryInfo.getRows());
		Map<String, Object> params = new HashMap<String, Object>();
		MapUtil.populateMap(params, queryInfo);

		List dataList = null;
		int count = studentDao.countStudents(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = studentDao.findStudents(params);
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Long upSet(Student student) {
		if(studentDao.get(student.getUserId()) == null){
			return studentDao.insert(student);
		}else {
			student.setUpdateTime(new Date());
			studentDao.update(student);
			return student.getUserId().longValue();
		}
	}

	@Override
	public boolean updateOperatingTempTag() {
		List<StudentCourseTimesDto> studentCourseTimesDtoList = courseScheduleStudentPaymentDao.queryStudentNotStartCourseTimesOfOnline();
		Map<Integer,StudentCourseTimesDto> map = studentCourseTimesDtoList.stream().collect(Collectors.toMap(StudentCourseTimesDto::getUserId, s -> s));
		//查询服务指标为0的用户
		List<Student> unlabeledStudentList = studentDao.queryByOperatingTempTag(0);
		
		List<Student> updateStudentList = new ArrayList<Student>();
		StudentCourseTimesDto dto = null;
		for(Student s : unlabeledStudentList){
			if(s.getOperatingTag() == 1){
				continue;
			}
			dto = map.get(s.getUserId());
			if(dto != null){
				if(dto.getTotalCourseTimes() > 0 && dto.getTotalCourseTimes() != dto.getFreePracticeCourseTimes()){
					s.setOperatingTempTag(1);
					s.setOperatingTag(1);
					updateStudentList.add(s);
				}
			}
		}

		List<Student> labeledStudentList = studentDao.queryByOperatingTempTag(1);
		for(Student s : labeledStudentList){
			dto = map.get(s.getUserId());
			if (dto == null || dto.getTotalCourseTimes() == dto.getFreePracticeCourseTimes()) {
				s.setOperatingTempTag(0);
				s.setOperatingTag(0);
				updateStudentList.add(s);
			}
		}
		
		if(updateStudentList.size() > 0){
			studentDao.batchUpdate(updateStudentList);
		}
		
		return true;
	}

	@Override
	public void initTeacherId() {
		List<StudentTeacherCourseDto> allStudentCourseInfo = courseScheduleStudentPaymentDao.findAllStudentCourseInfo();
		Map<Integer, List<StudentTeacherCourseDto>> studentCoursesMap = allStudentCourseInfo.stream().collect(Collectors.groupingBy(StudentTeacherCourseDto::getStudentId));
		List<Student> students=new ArrayList<>();
		for (Map.Entry<Integer, List<StudentTeacherCourseDto>> studentCoursesEntry : studentCoursesMap.entrySet()) {
			Map<CourseSchedule.CourseScheduleType, List<StudentTeacherCourseDto>> courseTypeCourseMap = studentCoursesEntry.getValue().stream().collect(Collectors.groupingBy(StudentTeacherCourseDto::getCourseScheduleType));
			List<StudentTeacherCourseDto> practiceCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.PRACTICE);
			if (!CollectionUtils.isEmpty(practiceCourses)) {
				practiceCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
				Student student=new Student(studentCoursesEntry.getKey());
				student.setTeacherId(practiceCourses.get(0).getTeacherId());
				students.add(student);
				continue;
			}

			List<StudentTeacherCourseDto> vipCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.VIP);
			if (!CollectionUtils.isEmpty(vipCourses)) {
				Student student=new Student(studentCoursesEntry.getKey());
				vipCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
				student.setTeacherId(vipCourses.get(0).getTeacherId());
				students.add(student);
				continue;
			}

			List<StudentTeacherCourseDto> singleCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.SINGLE);
			if (!CollectionUtils.isEmpty(singleCourses)) {
				Student student=new Student(studentCoursesEntry.getKey());
				singleCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
				student.setTeacherId(singleCourses.get(0).getTeacherId());
				students.add(student);
				continue;
			}

			List<StudentTeacherCourseDto> mixCourses = courseTypeCourseMap.get(CourseSchedule.CourseScheduleType.MIX);
			if (!CollectionUtils.isEmpty(mixCourses)) {
				Student student=new Student(studentCoursesEntry.getKey());
				mixCourses.sort(Comparator.comparing(StudentTeacherCourseDto::getClassesStartTime).reversed());
				student.setTeacherId(mixCourses.get(0).getTeacherId());
				students.add(student);
				continue;
			}
		}
		if(!CollectionUtils.isEmpty(students)){
			studentDao.batchUpdate(students);
		}
		students=null;
		studentCoursesMap=null;
		allStudentCourseInfo=null;
	}

	@Override
	public void batchUpdateAdviser(Integer teacherId,String studentIds) {
		studentDao.batchUpdateAdviser(teacherId,studentIds);
	}
}
