package com.keao.edu.user.service.impl;


import com.keao.edu.auth.api.client.SysUserFeignService;
import com.keao.edu.auth.api.entity.SysUser;
import com.keao.edu.common.dal.BaseDAO;
import com.keao.edu.common.exception.BizException;
import com.keao.edu.common.page.PageInfo;
import com.keao.edu.common.service.impl.BaseServiceImpl;
import com.keao.edu.im.api.client.ImFeignService;
import com.keao.edu.im.api.entity.ImResult;
import com.keao.edu.im.api.entity.ImUserModel;
import com.keao.edu.user.dao.EmployeeDao;
import com.keao.edu.user.dao.SysUserDao;
import com.keao.edu.user.dao.TeacherDao;
import com.keao.edu.user.entity.Employee;
import com.keao.edu.user.entity.Teacher;
import com.keao.edu.user.page.TeacherQueryInfo;
import com.keao.edu.user.service.TeacherService;
import com.keao.edu.util.collection.MapUtil;
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.util.*;
import java.util.stream.Collectors;

@Service
public class TeacherServiceImpl extends BaseServiceImpl<Integer, Teacher> implements TeacherService {

	@Autowired
	private TeacherDao teacherDao;
	@Autowired
	private SysUserDao sysUserDao;
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private SysUserFeignService sysUserFeignService;

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

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int add(Teacher teacher) {
		SysUser sysUser = teacher.getSysUser();
		SysUser user = sysUserDao.queryByPhone(sysUser.getPhone());
		Date date = new Date();
		if(user != null && user.getId() != null){
			Employee employee = employeeDao.get(user.getId());
			if(employee != null && employee.getDelFlag() == false && employee.getEmployeeType().equals("ORGAN")){
				throw new BizException("手机号被占用");
			}
			Integer id = user.getId();
			sysUser.setId(id);
			Teacher teacher1 = teacherDao.get(id);
			if(teacher1 == null || teacher1.getUserId() == null){
				teacher.setUserId(id);
				teacherDao.insert(teacher);
				if(StringUtils.isEmpty(user.getUserType())){
					sysUser.setUserType("TEACHER");
				}else {
					sysUser.setUserType(user.getUserType() + ",TEACHER");
				}
				sysUser.setUpdateTime(date);
				sysUserDao.update(sysUser);
			}else if (teacher1.getDelFlag() == 1){
				teacher.setUserId(id);
				if(StringUtils.isEmpty(user.getUserType())){
					sysUser.setUserType("TEACHER");
				}else {
					sysUser.setUserType(user.getUserType() + ",TEACHER");
				}
				sysUserDao.update(sysUser);
				teacher.setDelFlag(0);
				teacherDao.update(teacher);
			}else {
				throw new BizException("用户已存在");
			}
			return id;
		}
		sysUser.setUserType("TEACHER");

		sysUserDao.insert(sysUser);
		Integer userId = sysUser.getId();
		teacher.setUserId(userId);
		teacherDao.insert(teacher);
		ImResult imResult = imFeignService.register(new ImUserModel(userId.toString(), sysUser.getRealName(), sysUser.getAvatar()));
		if(imResult != null){
			sysUser.setImToken(imResult.getToken());
			sysUserDao.update(sysUser);
		}
		return userId;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateTeacher(Teacher teacher) {
		SysUser sysUser = teacher.getSysUser();
		sysUser.setId(teacher.getUserId());
		if(null == teacherDao.get(sysUser.getId())){
			throw new BizException("教师信息不存在");
		}
		if(StringUtils.isNotEmpty(sysUser.getPhone())){
			SysUser queryUserByMobile = sysUserDao.queryByPhone(sysUser.getPhone());
			if(queryUserByMobile != null && !sysUser.getId().equals(queryUserByMobile.getId())){
				throw new BizException("手机号已存在");
			}
		}
		Date date = new Date();
		teacher.setUpdateTime(date);
		teacherDao.update(teacher);
		sysUserDao.update(sysUser);
		imFeignService.update(new ImUserModel(sysUser.getId().toString(),sysUser.getRealName(),sysUser.getAvatar()));
	}

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

		List<Teacher> dataList = null;
		int count = this.findCount(params);
		if (count > 0) {
			pageInfo.setTotal(count);
			params.put("offset", pageInfo.getOffset());
			dataList = this.getDAO().queryPage(params);
			Set<Integer> teacherIds = dataList.stream().map(e -> e.getUserId()).collect(Collectors.toSet());
			Map<Integer,String> subjectNames = MapUtil.convertMybatisMap(teacherDao.queryTeacherSubjectNames(teacherIds),Integer.class,String.class);
			dataList.forEach(e->{
				e.setSubjectName(subjectNames.get(e.getUserId()));
			});
		}
		if (count == 0) {
			dataList = new ArrayList<>();
		}
		pageInfo.setRows(dataList);
		return pageInfo;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void del(Integer id) {
		SysUser queryUserInfo = sysUserFeignService.queryUserInfo();
		Teacher teacher = teacherDao.get(id);
		if(queryUserInfo.getId().equals(teacher.getUserId())){
			throw new BizException("删除失败：不支持此操作");
		}
		String userType = teacher.getSysUser().getUserType();
		if(userType.contains(",TEACHER")){
			userType = userType.replace(",TEACHER","");
		}else if(userType.contains("TEACHER,")){
			userType = userType.replace("TEACHER,","");
		}else {
			userType = "";
		}
		sysUserDao.updateUserType(teacher.getUserId(),userType);
		teacherDao.delete(id);
	}
}