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

import com.alibaba.fastjson.JSON;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.auth.api.enums.SysUserType;
import com.ym.mec.auth.api.enums.YesOrNoEnum;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.BasicUserDto;
import com.ym.mec.biz.dal.dto.NamesDto;
import com.ym.mec.biz.dal.dto.UserGoodsDto;
import com.ym.mec.biz.dal.entity.MusicGroup;
import com.ym.mec.biz.dal.entity.Teacher;
import com.ym.mec.biz.dal.entity.TeacherSchool;
import com.ym.mec.biz.dal.page.TeacherQueryInfo;
import com.ym.mec.biz.service.TeacherService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.entity.ImGroupModel;
import com.ym.mec.common.entity.ImResult;
import com.ym.mec.common.entity.ImUserModel;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.page.QueryInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.collection.MapUtil;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class TeacherServiceImpl extends BaseServiceImpl<Integer, Teacher>  implements TeacherService {
	
	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private SubjectDao subjectDao;
	@Autowired
	private MusicGroupDao musicGroupDao;
	@Autowired
	private ClassGroupDao classGroupDao;
	@Autowired
	private DemoGroupDao demoGroupDao;
	@Autowired
	private OrganizationDao organizationDao;
	@Autowired
	private TeacherSchoolDao teacherSchoolDao;
	@Autowired
	private SysUserFeignService sysUserFeignService;
	@Autowired
	private ImFeignService imFeignService;


	@Override
	public BaseDAO<Integer, Teacher> getDAO() {
		return teacherDao;
	}

	@Override
	public Teacher findByCertificateNum(String certificateNum){
		return teacherDao.findByCertificateNum(certificateNum);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void add(Teacher teacher){
		SysUser user = sysUserFeignService.queryUserByMobile(teacher.getPhone());
		if(user != null && user.getId() != null){
			teacherDao.updateUser(user);
			Teacher teacher1 = teacherDao.get(user.getId());
			if(teacher1 == null || teacher1.getId() == null){
				teacher.setId(user.getId());
				teacherDao.insert(teacher);
			}
			return;
		}
		teacher.setUserType(SysUserType.TEACHER);
		teacherDao.addSysUser(teacher);
		teacherDao.insert(teacher);
		ImResult imResult = imFeignService.register(new ImUserModel(teacher.getId().toString(), teacher.getUsername(), teacher.getAvatar()));
		if(imResult != null){
			teacher.setImToken(imResult.getToken());
			teacherDao.updateUser(teacher);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateTea(Teacher teacher) {
		teacher.setUpdateTime(new Date());
		teacherDao.update(teacher);
		teacherDao.updateUser(teacher);
	}

	@Override
	public void deleteTeacher(Long userId) {
		SysUser sysUser=new SysUser();
		sysUser.setId(userId.intValue());
		sysUser.setDelFlag(YesOrNoEnum.YES);
		teacherDao.updateUser(sysUser);
	}

	@Override
	public List<ImGroupModel> queryTeacherGroups(Integer userId,String search) {
		//获取教师所在乐团列表
		List<ImGroupModel> imGroupModels =  musicGroupDao.queryTeacherGroups(userId,search);

		if(imGroupModels != null && imGroupModels.size() > 0){
			//获取乐团id列表
			Set<String> musicGroupIds = imGroupModels.stream().map(e -> e.getId()).collect(Collectors.toSet());
			List<MusicGroup> musicGroups = musicGroupDao.queryListByIds(musicGroupIds);
			List<Map<String, BigDecimal>> musicGroupUserNums = musicGroupDao.countMusicGroupUserNum(musicGroupIds);
			Map<String, BigDecimal> musicGroupUserNumMap = MapUtil.convertMybatisMap(musicGroupUserNums);
			imGroupModels.forEach(e -> {
				MusicGroup musicGroup = musicGroups.stream().filter(mg -> mg.getId().equals(e.getId())).findFirst().get();
				//获取教学老师id列表
				Set<Integer> teachers = musicGroupDao.queryTeacherIds(e.getId());
				teachers.add(musicGroup.getTeamTeacherId());
				teachers.add(musicGroup.getEducationalTeacherId());
				teachers.add(musicGroup.getOperatorUserId());
				teachers.add(musicGroup.getDirectorUserId());
				teachers.removeAll(Collections.singleton(null));
				//获取乐团群用户总数
				BigDecimal count = musicGroupUserNumMap.get(e.getId());
				e.setCount(count == null?0:count.intValue() + teachers.size());
				e.setId("mg" + e.getId());
			});
		}else {
			imGroupModels = new ArrayList<>();
		}
		//获取教师所在班级列表
		List<ImGroupModel> imGroupModels1 =  classGroupDao.queryTeacherGroups(userId,search);
		if(imGroupModels1 != null && imGroupModels1.size() > 0){
			Set<String> classGroupIds = imGroupModels1.stream().map(e -> e.getId()).collect(Collectors.toSet());
			//获取班级老师总数map
			List<Map<Integer, Integer>> nums = classGroupDao.countTeacherNums(StringUtils.join(classGroupIds,","));
			Map<Integer, Integer> numsMap = MapUtil.convertMybatisMap(nums);
			imGroupModels1.forEach(e -> {
				//获取当前班级老师总数
				Integer num = numsMap.get(e.getId());
				e.setCount(num == null?0:num + e.getCount());
				e.setId("cg" + e.getId());
			});
			imGroupModels.addAll(imGroupModels1);
		}

		return imGroupModels;
	}

	@Override
	public List<BasicUserDto> queryGroupStudents(Integer teacherId, String search) {
		return teacherDao.queryGroupStudents(teacherId,search);
	}

    @Override
    public List<Teacher> findTeachers(Integer organId) {
		return teacherDao.findTeachers(organId);
    }

    @Override
	public PageInfo<Teacher> queryPageDetail(TeacherQueryInfo queryInfo) {
		PageInfo<Teacher> pageInfo = queryPage(queryInfo);
		List<Teacher> rows = pageInfo.getRows();
		if(rows != null && rows.size() > 0){
			Set<Integer> teachers = rows.stream().map(e -> e.getId()).collect(Collectors.toSet());
			String teacherIds = StringUtils.join(teachers, ",");
			//获取小课数量
			List<Map<Integer,Long>> numList =  classGroupDao.countTeacherVipNum(teacherIds);
			Map<Integer,Long> vipNumMap = MapUtil.convertMybatisMap(numList);
			//获取试听课数量
			List<Map<Integer,Long>> demoNumList =  demoGroupDao.countTeacherDemoGroupNum(teacherIds);
			Map<Integer,Long> demoNumMap = MapUtil.convertMybatisMap(demoNumList);
			rows.forEach(e->{
				e.setSubjectName(subjectDao.findBySubIds(e.getSubjectId()));
				Long num = vipNumMap.get(e.getId());
				e.setVipNum(num == null?0:num.intValue());
				Long demoNum = demoNumMap.get(e.getId());
				e.setDemoNum(demoNum == null?0:demoNum.intValue());
			});
		}
		return pageInfo;
	}

	@Override
	public Teacher getDetail(Integer id) {
		Teacher teacher = teacherDao.get(id);
		if(teacher != null){
			//获取老师教学点列表
			List<TeacherSchool> teacherSchools = teacherSchoolDao.findByTeacherId(id);
			teacher.setTeacherSchools(teacherSchools);
			//获取流动范围
			if(StringUtils.isNotEmpty(teacher.getFlowOrganRange())){
				List<String> organNames = organizationDao.findByOrganIds(teacher.getFlowOrganRange());
				teacher.setFlowOrganRange(StringUtils.join(organNames,","));
			}
			//专业技能
			if(StringUtils.isNotEmpty(teacher.getSubjectId())){
				teacher.setSubjectName(subjectDao.findBySubIds(teacher.getSubjectId()));
			}
		}
		return teacher;
	}

}