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

import com.ym.mec.biz.dal.dao.OrganizationDao;
import com.ym.mec.biz.dal.dao.SchoolDao;
import com.ym.mec.biz.dal.entity.School;
import com.ym.mec.biz.dal.page.SchoolQueryInfo;
import com.ym.mec.biz.service.SchoolService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.util.collection.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SchoolServiceImpl extends BaseServiceImpl<Integer, School>  implements SchoolService {
	
	@Autowired
	private SchoolDao schoolDao;
	@Autowired
	private OrganizationDao organizationDao;

	@Override
	public BaseDAO<Integer, School> getDAO() {
		return schoolDao;
	}

	@Override
	public List<School> queryByOrganId(String organId) {
		return schoolDao.queryByOrganId(organId);
	}

	@Override
	public void deleteByTeacherAndId(Integer schoolId, Integer userId) {
		School school = schoolDao.get(schoolId);
		if(Objects.isNull(school)){
			throw new BizException("此教学点不存在");
		}
		if(Objects.nonNull(school.getUserId())&&school.getUserId().equals(userId)){
			schoolDao.delete(schoolId);
		}
	}

	@Override
	public List<School> findVipSchoolByTeacher(Integer teacherId,String organId,Integer isDefault) {
		return schoolDao.findVipSchoolByUserId(teacherId,organId,isDefault);
	}

	@Override
	public List<School> findVipSchoolByTeacher(Integer teacherId,String organId) {
		return schoolDao.findVipSchoolByUserId2(teacherId,organId);
	}

	@Override
	public PageInfo<School> queryPageDetail(SchoolQueryInfo queryInfo) {
		PageInfo<School> schoolPageInfo = queryPage(queryInfo);
		List<School> rows = schoolPageInfo.getRows();
		if(rows != null && rows.size() > 0){
			Set<Integer> organIds = rows.stream().map(e -> e.getOrganId()).collect(Collectors.toSet());
			Map<Integer,String> organNames = MapUtil.convertMybatisMap(organizationDao.findOrganNameMapList(organIds));
			rows.forEach(e->{
				e.setOrganName(organNames.get(e.getOrganId()));
			});
		}
		return schoolPageInfo;
	}
}
