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

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

import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.ClassGroupStudentInfoDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.service.TeacherService;
import com.ym.mec.util.collection.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.ym.mec.biz.dal.dto.ImUserFriendDto;
import com.ym.mec.biz.service.ImUserFriendService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import static com.ym.mec.biz.dal.enums.GroupType.*;

@Service
public class ImUserFriendServiceImpl extends BaseServiceImpl<Long, ImUserFriend> implements ImUserFriendService {

	@Autowired
	private ImUserFriendDao imUserFriendDao;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private ClassGroupTeacherMapperDao classGroupTeacherMapperDao;
	@Autowired
	private ClassGroupStudentMapperDao classGroupStudentMapperDao;
	@Autowired
	private MusicGroupDao musicGroupDao;
	@Autowired
	private VipGroupDao vipGroupDao;
	@Autowired
	private PracticeGroupDao practiceGroupDao;
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private CourseScheduleDao courseScheduleDao;
	@Autowired
	private StudentRegistrationDao studentRegistrationDao;
	@Autowired
	private ClassGroupDao classGroupDao;
	@Autowired
	private RedisTemplate<String,String> redisTemplate;

	@Override
	public BaseDAO<Long, ImUserFriend> getDAO() {
		return imUserFriendDao;
	}

	@Override
	public boolean addFriend(Integer userId, Integer friendUserId, String nickname, String memo) {
		// 检查是否已经是好友
		ImUserFriend userFriend = imUserFriendDao.query(userId, friendUserId);
		if (userFriend != null) {
			throw new BizException("好友已存在");
		}

		Date date = new Date();

		userFriend = new ImUserFriend();
		userFriend.setFriendId(friendUserId);
		userFriend.setUserId(friendUserId);
		userFriend.setFriendNickname(nickname);
		userFriend.setMemo(memo);
		userFriend.setCreateTime(date);
		userFriend.setUpdateTime(date);
		imUserFriendDao.insert(userFriend);

		return true;
	}

	@Override
	public boolean deleteFriend(Integer userId, Integer friendUserId) {
		ImUserFriend userFriend = imUserFriendDao.query(userId, friendUserId);
		if (userFriend == null) {
			throw new BizException("好友不存在");
		}
		imUserFriendDao.delete(userFriend.getId());
		return true;
	}

	@Override
	public boolean updateFriendNickname(Integer userId, Integer friendUserId, String nickname) {
		ImUserFriend userFriend = imUserFriendDao.query(userId, friendUserId);
		if (userFriend == null) {
			throw new BizException("好友不存在");
		}
		Date date = new Date();
		userFriend.setFriendNickname(nickname);
		userFriend.setUpdateTime(date);
		imUserFriendDao.update(userFriend);

		return true;
	}

	@Override
	public List<ImUserFriendDto> queryFriendListByUserId(Integer userId, String search) {
		String syncImUserFriendKey = "syncImUserFriend:" + userId;
		if(redisTemplate.hasKey(syncImUserFriendKey)){
			return imUserFriendDao.queryFriendListByUserId(userId, search);
		}else {
			return teacherService.queryGroupStudents1(userId,null);
		}
	}

	@Override
	public ImUserFriendDto queryFriendDetail(Integer userId, Integer friendUserId) {
		return imUserFriendDao.queryFriendDetail(userId, friendUserId);
	}

	@Override
	public void batchInsert(List<ImUserFriend> imUserFriends) {
		for (ImUserFriend imUserFriend : imUserFriends) {
			if(imUserFriend.getUserId() == imUserFriend.getFriendId()){
				continue;
			}
			// 检查是否已经是好友
			ImUserFriend userFriend = imUserFriendDao.query(imUserFriend.getUserId(), imUserFriend.getFriendId());
			if (userFriend != null) {
				continue;
			}
			imUserFriendDao.insert(imUserFriend);
		}
	}


	@Override
	@Transactional(rollbackFor = Exception.class)
	public void refreshCourseImUserFriend(Long courseId) {
		CourseSchedule courseSchedule = courseScheduleDao.get(courseId);
		//获取班级关联的老师列表
		Set<Integer> teacherIds = classGroupTeacherMapperDao.queryTeacherIdsByClassGroupId(courseSchedule.getClassGroupId(),null,null);
		//获取班级关联的学员列表
		Set<Integer> studentIds = classGroupStudentMapperDao.queryStudentIdsByClassGroupId(courseSchedule.getClassGroupId(),null,null);
		ClassGroup classGroup = classGroupDao.get(courseSchedule.getClassGroupId());
		GroupType groupType = classGroup.getGroupType();
		List<ImUserFriend> imUserFriends = saveImUserFriends(studentIds, teacherIds, groupType, classGroup.getMusicGroupId());
		if(imUserFriends.size() > 0){
			batchInsert(imUserFriends);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void refreshClassImUserFriend(Integer classGroupId) {
		//获取班级关联的老师列表
		Set<Integer> teacherIds = classGroupTeacherMapperDao.queryTeacherIdsByClassGroupId(classGroupId,null,null);
		//获取班级关联的学员列表
		Set<Integer> studentIds = classGroupStudentMapperDao.queryStudentIdsByClassGroupId(classGroupId,null,null);
		ClassGroup classGroup = classGroupDao.get(classGroupId);
		GroupType groupType = classGroup.getGroupType();
		List<ImUserFriend> imUserFriends = saveImUserFriends(studentIds, teacherIds, groupType, classGroup.getMusicGroupId());
		if(imUserFriends.size() > 0){
			batchInsert(imUserFriends);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void refreshGroupImUserFriend(String musicGroupId,GroupType groupType) {
		List<ClassGroup> classGroups = classGroupDao.queryClassGroups(musicGroupId, groupType.getCode());
		List<ImUserFriend> imUserFriends = new ArrayList<>();
		classGroups.forEach(e->{
			//获取班级关联的老师列表
			Set<Integer> teacherIds = classGroupTeacherMapperDao.queryTeacherIdsByClassGroupId(e.getId(),null,null);
			//获取班级关联的学员列表
			Set<Integer> studentIds = classGroupStudentMapperDao.queryStudentIdsByClassGroupId(e.getId(),null,null);
			imUserFriends.addAll(saveImUserFriends(studentIds,teacherIds,groupType,musicGroupId));
		});
		if(imUserFriends.size() > 0){
			batchInsert(imUserFriends);
		}
	}

	public List<ImUserFriend> saveImUserFriends(Set<Integer> studentIds,Set<Integer> teacherIds,GroupType groupType,String musicGroupId){
		List<ImUserFriend> imUserFriends = new ArrayList<>();
		Set<Integer> educationIds = new HashSet<>();
		MusicGroup musicGroup = new MusicGroup();
		//获取当前学员声部
		Map<Integer,String> studentSubjectName = new HashMap<>();
		Map<Integer, String> teacherSubjectNameMap = new HashMap<>();
		if(teacherIds.size() > 0){
			teacherSubjectNameMap = MapUtil.convertIntegerMap(teacherDao.querySubjectNameByIdList(new ArrayList<>(teacherIds)));
		}
		if(groupType == MUSIC){
			//学员关联乐团管理人员通讯录
			musicGroup = musicGroupDao.get(musicGroupId);
			educationIds.add(musicGroup.getDirectorUserId());
			educationIds.add(musicGroup.getEducationalTeacherId());
			educationIds.add(musicGroup.getTeamTeacherId());
			if(studentIds.size() > 0){
				studentSubjectName = MapUtil.convertMybatisMap(studentRegistrationDao.getStudentSubjectNameByStuIds(musicGroup.getId(),studentIds));
			}
		}else if(groupType == VIP){
			VipGroup vipGroup = vipGroupDao.get(Long.parseLong(musicGroupId));
			educationIds.add(vipGroup.getEducationalTeacherId());
		}else if(groupType == PRACTICE){
			PracticeGroup practiceGroup = practiceGroupDao.get(Long.parseLong(musicGroupId));
			educationIds.add(practiceGroup.getEducationalTeacherId());
		}
		studentIds.removeAll(Collections.singleton(null));
		teacherIds.removeAll(Collections.singleton(null));
		educationIds.removeAll(Collections.singleton(null));
		Map<Integer, String> usernameMap = new HashMap<>();
		if(studentIds.size() > 0){
			usernameMap = MapUtil.convertMybatisMap(teacherDao.queryUserNameByIdList(new ArrayList<>(studentIds)));
		}
		Map<Integer, String> teacherRealNameMap = new HashMap<>();
		if(teacherIds.size() > 0){
			teacherRealNameMap = MapUtil.convertMybatisMap(teacherDao.queryUserNameByIdList(new ArrayList<>(teacherIds)));
		}
		Map<Integer, String> educationRealNameMap = new HashMap<>();
		if(educationIds.size() > 0){
			educationRealNameMap = MapUtil.convertMybatisMap(teacherDao.queryUserNameByIdList(new ArrayList<>(educationIds)));
		}
		//老师关联教务、学员
		for (Integer teacherId : teacherIds) {
			//老师关联学员
			for (Integer studentId : studentIds) {
				if(teacherId == studentId){
					continue;
				}
				//学员、教务关联的老师
				ImUserFriend imUserFriend = new ImUserFriend();
				imUserFriend.setUserId(teacherId);
				imUserFriend.setFriendId(studentId);
				imUserFriend.setFriendNickname(usernameMap.get(studentId));
				imUserFriend.setMemo(musicGroup.getName());
				imUserFriend.setTags(studentSubjectName.get(studentId));
				imUserFriends.add(imUserFriend);
			}
			//老师关联教务
			for (Integer educationId : educationIds) {
				if(teacherId == educationId){
					continue;
				}
				ImUserFriend imUserFriend = new ImUserFriend();
				imUserFriend.setUserId(teacherId);
				imUserFriend.setFriendId(educationId);
				imUserFriend.setFriendNickname(educationRealNameMap.get(educationId));
				imUserFriends.add(imUserFriend);
			}
		}
		//教务关联的老师、学员
		for (Integer educationId : educationIds) {
			//教务关联学员
			for (Integer studentId : studentIds) {
				if(educationId == studentId){
					continue;
				}
				ImUserFriend imUserFriend = new ImUserFriend();
				imUserFriend.setUserId(educationId);
				imUserFriend.setFriendId(studentId);
				imUserFriend.setFriendNickname(usernameMap.get(studentId));
				imUserFriend.setMemo(musicGroup.getName());
				imUserFriend.setTags(studentSubjectName.get(studentId));
				imUserFriends.add(imUserFriend);
			}
			//教务关联老师
			for (Integer teacher : teacherIds) {
				if(educationId == teacher){
					continue;
				}
				ImUserFriend imUserFriend = new ImUserFriend();
				imUserFriend.setUserId(educationId);
				imUserFriend.setFriendId(teacher);
				imUserFriend.setFriendNickname(teacherRealNameMap.get(teacher));
				imUserFriend.setMemo(musicGroup.getName());
				imUserFriend.setTags(teacherSubjectNameMap.get(teacher));
				imUserFriends.add(imUserFriend);
			}
		}
		//学员关联的老师、教务
		for (Integer studentId : studentIds) {
			//学员关联的老师
			for (Integer teacher : teacherIds) {
				if(teacher == studentId){
					continue;
				}
				ImUserFriend imUserFriend = new ImUserFriend();
				imUserFriend.setUserId(studentId);
				imUserFriend.setFriendId(teacher);
				imUserFriend.setFriendNickname(teacherRealNameMap.get(teacher));
				imUserFriend.setMemo(musicGroup.getName());
				imUserFriend.setTags(teacherSubjectNameMap.get(teacher));
				imUserFriends.add(imUserFriend);
			}
			//学员关联的教务
			for (Integer education : educationIds) {
				if(education == studentId){
					continue;
				}
				ImUserFriend imUserFriend = new ImUserFriend();
				imUserFriend.setUserId(studentId);
				imUserFriend.setFriendId(education);
				imUserFriend.setFriendNickname(educationRealNameMap.get(education));
				imUserFriends.add(imUserFriend);
			}
		}
		return imUserFriends;
	}
}