package com.ssj.service.weixin.library.service.impl;


import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.primitives.Ints;
import com.ssj.bean.sys.homework.domain.HomeworkPicture;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.libmy.domain.TbLibManagerAudit;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.dao.kmt.kmt.dao.KmtQueryDao;
import com.ssj.dao.sys.teacher.dao.CorrectTeacherQueryDao;
import com.ssj.dao.weixin.library.dao.IBookManagerDao;
import com.ssj.dao.weixin.library.dao.ILibJoinQueryDao;
import com.ssj.dao.weixin.library.dao.IOneBookQueryDao;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.*;
import com.ssj.service.conch.curator.request.CreateTeacherRequest;
import com.ssj.service.conch.teacher.app.request.VcodeSubmitReq;
import com.ssj.service.mapper.LibManagerMapper;
import com.ssj.service.mapper.LibVipMapper;
import com.ssj.service.sys.homework.service.HomeworkPictureService;
import com.ssj.service.sys.teacher.OnlineTeacherWeightService;
import com.ssj.service.sys.teacher.dto.CorrectionCountDTO;
import com.ssj.service.sys.teacher.dto.OnlineCorrectTeacherDTO;
import com.ssj.service.weixin.library.dto.*;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.LibManagerAuditService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.transaction.annotation.Transactional;

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

@Service(version="1.0")
@Transactional
public class BookManagerServiceImpl extends BaseServiceImpl<TbLibManager, String> implements IBookManagerService {
    private   static Logger logger = LoggerFactory.getLogger(BookManagerServiceImpl.class);

	@Autowired
	private IBookManagerDao dao;
	
	@Autowired
	private ILibJoinQueryDao  libJoinQueryDao;
	
	@Autowired
	private KmtQueryDao queryDao;
	
	@Autowired
	private IOneBookQueryDao bookQueryDao;

    @Autowired
    private HomeworkPictureService homeworkPictureService;
    @Autowired
    private OnlineTeacherWeightService onlineTeacherWeightService;
    @Autowired
    private CorrectTeacherQueryDao correctTeacherQueryDao;

    @Autowired
    private PushTemplateService pushTemplateService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private LibManagerMapper libManagerMapper;
    @Autowired
    private LibVipMapper libVipMapper;
    @Autowired
    private LibManagerAuditService libManagerAuditService;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
	public PagingAndSortingRepository<TbLibManager, String> getDao() {
		
		return dao;
	}

    @Override
    public TbLibManager findByUserId(String userId) {

        return dao.findByUserId(userId);
    }

    @Override
    public TbLibManager findByUserId(String userId, Integer type) {

        return dao.findByUserId(userId, type);
    }

    @Override
    public List<TbLibManager> find121Teacher(int type) {
        return dao.findByTypeAndState(type, 1);
    }

    @Override
    public TbLibManager findByUserIdAndType(String userId, Integer type) {
        return dao.findByUserIdAndType(userId, type);
    }

    @Override
    public TbLibManager findExerciseTeacherByUserIdAndType(String userId, int type) {
        return dao.findExerciseTeacherByUserIdAndType(userId, type);
    }

    @Override
    public TbLibManager findByLibIdAndUserIdAndType(String libId,String userId, Integer type) {
        return dao.findByLibIdAndUserIdAndType(libId,userId, type);
    }

    @Override
    public List<Map<String, Object>> findManageList(String libId) {

        return libJoinQueryDao.findManageList(libId);
    }
    @Override
    public List<Map<String, Object>> findManageUserList(String userId) {
    	
    	return libJoinQueryDao.findManageUserList(userId);
    }

    @Override
    public List<Map<String, Object>> findSaleList(String libId) {

        return libJoinQueryDao.findSaleList(libId);
    }

    @Override
    public Map<String, Object> getLibUserInfo(String userId, String libId) {

        return libJoinQueryDao.getLibUserInfo(userId, libId);
    }

    @Override
    public Page<Map<String, Object>> vipUserList(Map<String, Object> params, Pageable pageable) {

        return libJoinQueryDao.vipUserList(params, pageable);
    }

    @Override
    public Map<String, Object> getSaleUserInfo(String userId, String libId) {

        return libJoinQueryDao.getSaleUserInfo(userId, libId);
    }

    @Override
    public Page<Map<String, Object>> vipList(Map<String, Object> params, Pageable pageable) {

        return libJoinQueryDao.vipList(params, pageable);
    }

    @Override
    public List<Map<String, Object>> findLibUserList(Map<String, Object> params) {

        return libJoinQueryDao.findLibUserList(params);
    }

    @Override
    public List<Map<String, Object>> findVipUserList(Map<String, Object> params) {

        return libJoinQueryDao.findVipUserList(params);
    }

    @Override
    public List<Map<String, Object>> searchAddUser(Map<String, Object> params) {

        return libJoinQueryDao.searchAddUser(params);
    }

    @Override
    public List<Map<String, Object>> searchAddUserList(
            Map<String, Object> params) {
        return libJoinQueryDao.searchAddUserList(params);
    }

    @Override
    public TbLibManager findByUserIdAndLibId(String id, String libId) {

        return dao.findByUserIdAndLibId(id, libId);
    }

    @Override
    public List<String> findManageOpenidList(String libId, int type) {

        return dao.findManageOpenidList(libId, type);
    }

    @Override
    public List<Map<String, Object>> findAnything(String libId, int type) {

        return libJoinQueryDao.findAnything(libId, type);
    }


    @Override
    public List<Map<String, Object>> findKmtTeacherByPage() {
        return queryDao.findKmtTeacherByPage();
    }

    @Override
    public Map<String, Object> findKmtTeacherByUserId(String userId) {
        return queryDao.findKmtTeacherByUserId(userId);
//        return null;
    }

    @Override
    public Map<String, Object> findRandomByCourseName(String courseName) {
      //  return queryDao.findOnLineTeacherByRand(courseName);
    	 return null;
    }

    @Override
    public Map<String, Object> findRandomByCourseNameAndGrade(String courseName, String grade) {
      //  return queryDao.findOnLineTeacherByCourseNameAndGradeRand(courseName, grade);
    	 return null;
    }

    @Override
    public Map<String, Object> findKmtTeacherByUserIdAndCourse(String userId) {
     //   return queryDao.findKmtTeacherByUserIdAndCourse(userId);
    	 return null;
    }
    
    
    @Override
    public Map<String, Object> findKmtTeacherByUserIdAndOne(String userId) {
      //  return queryDao.findKmtTeacherByUserIdAndOne(userId);
    	 return null;
    }
   

    @Override
    public List<TbLibManager> findManagerList(String userId, int type) {
        return dao.findManagerList(userId, type);
    }
    
    
    @Override
    public List<TbLibManager> findManagerList(String libId,String userId, int type) {
        return dao.findManagerList(libId,userId, type);
    }

    @Override
    public int bindByMasterAndTeacher(String teacherId, String masterId) {
    	int count=0;
        List<TbLibManager> ms=dao.finBindByMasterAndTeacher(masterId,teacherId,7);
        if(CollectionUtils.isEmpty(ms)){
            TbLibManager manager=new TbLibManager();
            TbLibManager  managerTearcher= dao.findByOnoTwoOnoTearcher(teacherId);
            manager.setCreateTime(new Date());
            manager.setMasterId(masterId);
            manager.setName(managerTearcher.getName());
            manager.settPhoto(managerTearcher.gettPhoto());
            manager.setSex(managerTearcher.getSex());
            manager.setUserId(teacherId);
            manager.setType(7);
            manager.setTelephone(managerTearcher.getTelephone());
            manager.setState(1);
            
            manager.setBirthday(managerTearcher.getBirthday());
            manager.setCourseName(managerTearcher.getCourseName());
            manager.setGrade(managerTearcher.getGrade());
            manager.setSchoolAge(managerTearcher.getSchoolAge());
            manager.setTeacherLever(managerTearcher.getTeacherLever());
            manager.setPersonalLabel(managerTearcher.getPersonalLabel());
            manager.setPersonalInfo(managerTearcher.getPersonalInfo());
            manager.setTeachPoint(managerTearcher.getTeachPoint());
            manager.setSuccessfulCase(managerTearcher.getSuccessfulCase());
            manager.setTeacherType(managerTearcher.getTeacherType());
            manager.setStudentCount(managerTearcher.getStudentCount());
            manager.setCourseCount(managerTearcher.getCourseCount());
            manager.setPraise(managerTearcher.getPraise());
            dao.save(manager);
        }else{
        	count=1;
        }
        return count;
    }

    @Override
    public List<TbLibManager> findManagerList(String[] libIds, int[] types, String masterId) {
	    if (libIds == null || libIds.length  ==0){
	        return null;
        }
        return dao.findManagerList(libIds, types, masterId);
    }

    @Override
    public List<TbLibManager> searchTeacherList(String[] libIds, String masterId, String key) {
        if (libIds == null || libIds.length  == 0 || StringUtil.isEmpty(key)){
            return dao.search121TeacherList(key);
        }
	    return dao.searchTeacherList(libIds, key);
    }

    @Override
	public List<TbLibManager> getByUserId(String userId) {
		return dao.getByUserId(userId);
	}


    @Override
    public List<TbLibManager> findByUserIdIn(String[] userIds) {
        return dao.findByUserIdInAndType(userIds, Constant.KMT_121_TEACHER_TYPE);
    }

	@Override
	public List<TbLibManager> getByDistinctUserId(String userId) {
		return dao.getByDistinctUserId(userId);
	}

	@Override
	public TbLibManager findByUserIdAndTypeAndGradeAndTeacherLever(String userId, int type, String grade, String teacherLever) {
		return dao.findByUserIdAndTypeAndGradeAndTeacherLever(userId, type, grade, teacherLever);
	}

	@Override
	public List<TbLibManager> findMasterListByUserIdAndType(String userId, int type) {
		return dao.findMasterListByUserIdAndType(userId, type);
	}

	@Override
	public List<TbLibManager> findTeacherByUserId(String userId) {
		return dao.findTeacherByUserId(userId);
	}

	@Override
	public TbLibManager findByOnoTwoOnoTearcher(String userId) {
		return dao.findByOnoTwoOnoTearcher(userId);
	}

	@Override
	public TbLibManager findByUserIdAndLibIsNotNull(String userId) {
		return dao.findByUserIdAndLibIsNotNull(userId);
	}

	@Override
	public List<Map<String,Object>> findMasterIdByLibId(List<String[]> masterIdByLibId) {
		return bookQueryDao.findMasterIdByLibId(masterIdByLibId);
	}

	@Override
	public List<Map<String,Object>> findTeacherIdByMasterId(List<String[]> teacherIdByMasterId) {
		return bookQueryDao.findTeacherIdByMasterId(teacherIdByMasterId);
	}

    @Override
    public List<Map<String, Object>> findByLibIdAndType(String libId, int type) {
        return bookQueryDao.findLibManagerByLibIdAndType(libId, type);
    }

    @Override
    public Page<Map<String, Object>> findKmtTeacherByPage(Map<String, Object> params, Pageable pageable) {
        return queryDao.findKmtTeacherByPage(params, pageable);
    }

    @Override
    public List<TbLibManager> findByUserIdAndTypeIn(String userId, int[] type) {
        //return dao.findByUserIdAndTypeInAndState(userId, type, 1);
        //不包含已注销的数据
        return dao.findByUserIdAndTypeInAndStateAndIsCancelled(userId, type, 1, 0);
    }

    @Override
    public TbLibManager findAllByUserIdAndTypeAndCancelled(String userId, int type) {
        return dao.findByTypeAndUserIdAndCancelled(userId, type);
    }

    @Override
    public void updateByUserIdAndTypeAndCancelled(String userId, int type,int cancelled) {
         dao.updateByUserIdAndTypeAndCancelled(userId, type,cancelled);
    }
    @Override
    public List<TbLibManager> findAllByUserIdAndTypeIn(String userId, int[] type) {
        return dao.findByUserIdAndTypeInOrderByCreateTimeDesc(userId, Ints.asList(type));
    }


    @Override
    public List<TbLibManager> findAllByUserIdAndTypeInAndIsCancelled(String userId, int[] type, int isCancelled){
        return dao.findByUserIdAndTypeInAndIsCancelled(userId, Ints.asList(type),isCancelled);
    }

    @Override
    public List<TbLibManager> findByType(int type) {
        return dao.findByTypeAndState(type, 1);
    }

    @Override
    public List<TbLibManager> findByTypeIn(int[] type) {
        return dao.findByTypeInAndState(type, 1);
    }

    @Override
    public Page<Map<String,Object>>findTbLibTeacherByPage(Map<String,Object>params,Pageable pageable){
	    return queryDao.findTbLibTeacherByPage(params,pageable);

    }

    @Override
    public List<TbLibManager> findByParentId(String parentId) {
        return dao.findByParentIdAndState(parentId, 1);
    }


    @Override
    public List<TbLibManager> findByParentIdAndType(String parentId,int type) {
        return dao.findByParentIdAndStateAndType(parentId, 1,type);
    }
    @Override
    public void setCorretSysRoleInfo(String userId, int type) {
        List<TbLibManager> list = this.findByUserIdAndTypeIn(userId, new int[]{8, 11, 12});
        if (list.size() > 0) {
            Date now = new Date();
            for (TbLibManager user : list) {
                if (type == 1) {
                    user.setIsOnline(1);
                    user.setLoginTime(now);
                } else if (type == 2) {
                    user.setIsOnline(0);
                    user.setLogoutTime(now);
                }
            }
        }
    }

    @Override
    public TbLibManager findAllByUserIdAndType(String userId, int type) {
        return dao.findTopByTypeAndUserIdOrderByCreateTimeDesc(type, userId);
    }



    @Override
    public void allotHomework(String homeworkId, String teacherId) {
        logger.info("作业{}分配到老师{}", homeworkId, teacherId);
        List<HomeworkPicture> homeworkPictures = homeworkPictureService.findAllByHomeworkId(homeworkId);
        for (HomeworkPicture homeworkPicture : homeworkPictures) {
            if (StringUtils.isNotBlank(homeworkPicture.getTeacherId())) {
                //作业已有批改老师
                if (homeworkPicture.getIsFeedback() == 0 &&
                        homeworkPicture.getIsMark() != 1 &&
                        homeworkPicture.getIsMark() != 3) {

                    //未批改的图片需要更新原分配老师和新老师的实时权重
                    this.updateCorrectHomeworkNum(homeworkPicture.getVipId(), homeworkPicture.getTeacherId(), -1);
                    homeworkPicture.setTeacherId(teacherId);
                    this.updateCorrectHomeworkNum(homeworkPicture.getVipId(), teacherId, 1);
                }
            } else {
                //作业还未分配批改老师
                homeworkPicture.setTeacherId(teacherId);
                this.updateCorrectHomeworkNum(homeworkPicture.getVipId(), teacherId, 1);
            }
        }
        homeworkPictureService.save(homeworkPictures);
    }

    @Override
    public void updateCorrectHomeworkNum(String vipId, String teacherId, int num) {
        List<TbLibManager> libManagerList = this.findByUserIdAndTypeIn(teacherId, new int[]{8, 11, 13});
        if(CollectionUtils.isNotEmpty(libManagerList)) {
            onlineTeacherWeightService.updateRealTimeWeightAndHomeworkSum(vipId, libManagerList.get(0), num);
        }
    }

    @Override
    public Page<OnlineCorrectTeacherDTO> findCorrectTeacherPage(String teacherName, Pageable pageable) {
        return correctTeacherQueryDao.findCorrectTeacherPage(teacherName, pageable);
    }

    @Override
    public Page<CorrectionCountDTO> correctionCount(String teacherName, Date beginTime, Date endTime, Pageable pageable) {
        return correctTeacherQueryDao.correctionCount(teacherName, beginTime, endTime, pageable);
    }

    @Override
    public void resetCorrectHomeworkNum() {
        dao.resetCorrectHomeworkNum();
    }

    @Override
    public TbLibManager findByCourseNameAndGrade(String courseName, String grade) {
        return dao.findByCourseNameAndGrade(courseName, grade);
    }
    @Override
    public TbLibManager findByCourseNameAndGrade(String courseName, String grade,int teacherType) {
        return dao.findByCourseNameAndGrade(courseName, grade,teacherType);
    }
    @Override
    public TbLibManager findByCourseNameAndGrade(String courseName, String grade,String teacherId) {
        return dao.findByCourseNameAndGrade(courseName, grade,teacherId);
    }
    @Override
    public TbLibManager findByCourseName(String courseName) {
        return dao.findByCourseName(courseName);
    }
    @Override
    public TbLibManager findByCourseName(String courseName,String teacherId) {
        return dao.findByCourseName(courseName, teacherId);
    }

    @Override
    public List<TbLibManager> findCorrectTeacherByPeriod(String period){
        return dao.findByPeriodLikeAndTypeInAndStateAndIsBanned("%"+period+"%", new int[]{Constant.KMT_122_TEACHER_TYPE, Constant.CORRECT_MANAGER}, 1, 0);
    }

    @Override
    public Page<SchoolManagerDTO> findPageByTypeIn(String subject, List<Integer> typeList, Pageable pageable) {
	    return bookQueryDao.findPageByType(subject, typeList, pageable);
    }

    @Override
    public TeacherInfoDTO findMyInfo(String teacherId) {
        return bookQueryDao.findMyInfo(teacherId);
    }

    @Override
    public TbLibManager findByCourseNameAndGrade(String courseName, String grade, int teacherType, int correctType) {
        return dao.findByCourseNameAndGrade(courseName, grade,teacherType,correctType);
    }

    @Override
    public TbLibManager findCorrectTeacherByUserId(String userId, boolean isAll) {
        int[] type = {Constant.KMT_122_TEACHER_TYPE, Constant.CORRECT_MANAGER, Constant.KNOW_MATCH_TYPE};
        List<TbLibManager> list;
        if (isAll) {
            list = this.findAllByUserIdAndTypeIn(userId, type);
        } else {
            list = dao.findByUserIdAndTypeInAndState(userId, type, 1);
        }
        if (list != null & list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public TbLibManager findCorrectTeacherByUserIdAndIsCancelled(String userId, boolean isAll,int cancel) {
        int[] type = {Constant.KMT_122_TEACHER_TYPE, Constant.CORRECT_MANAGER, Constant.KNOW_MATCH_TYPE};
        List<TbLibManager> list;
        if (isAll) {
            list = this.findAllByUserIdAndTypeInAndIsCancelled(userId, type,0);
        } else {
            list = dao.findByUserIdAndTypeInAndStateAndIsCancelled(userId, type, 1,0);
        }
        if (list != null & list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<Integer> findTeacherTypeByUserId(String userId) {
        return dao.findTeacherTypeByUserId(userId);
    }

    @Override
    public int findCorrectOrKnowRoleByUserId(String userId) {
        //三个角色只会是其中一个
        List<TbLibManager> list = dao.findByUserIdAndTypeInAndState(userId, new int[]{8, 11, 13}, 1);
        if (list.size() > 0) {
            TbLibManager tbLibManager = list.get(0);
            if (tbLibManager.getType() == 8 || tbLibManager.getType() == 11) {
                return 8;
            } else {
                return 13;
            }
        }
        return 0;
    }

    @Override
    public TbLibManager findTopByUserIdAndTypeIn(String userId, int[] type) {
        return dao.findTopByUserIdAndTypeInAndState(userId, type, 1);
    }

	@Override
	public List<String> findByParentIdAndTypeAndCourseName(String parentId,Integer type, String courseName,String teacherName) {
		if(StringUtils.isEmpty(parentId)){
			return dao.findByParentIdAndTypeAndCourseName(type,courseName,teacherName);
		}else{
			return dao.findByParentIdAndTypeAndCourseName(parentId,type,courseName,teacherName);
		}
	}

    @Override
    public boolean checkSchoolManagerSubject(String managerUserId, String subject) {
        List<TbLibManager> managerList = this.findByUserIdAndTypeIn(managerUserId, new int[]{11, 12});

        if (CollectionUtils.isNotEmpty(managerList)) {
            return Objects.equals(subject, managerList.get(0).getCourseName());
        }

        return false;
    }

    @Override
    public TbLibManager findUserInfoByPhone(String phone) {
        return dao.findUserInfoByPhone(phone);
    }

    @Override
    public void getVerificationCode(String userId, String phone) {
        this.sendCodeToUser(userId,phone);
    }

    @Override
    public ResponseEntity bindTelPhone(String userId, VcodeSubmitReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        String phone = req.getPhone();
        String vcode = req.getVcode();
        String redisVcode = redisUtil.get("vcode_"+phone);
        if(redisVcode == null){
            responseEntity.failure(ResponseConstant.CODE_000, "验证码不正确，请重新获取验证码");
        }else{
            if(redisVcode.equals(vcode)){ //修改用户信息
                //根据手机号码去查询用户
                TbLibManager manager = dao.findUserInfoByPhone(phone);
                if(manager == null){

                    dao.updateManagerPhone(userId,phone);
                    User user = userService.getById(userId);
                    user.setMobile(phone);
                    userService.save(user);
                    responseEntity.success("提交成功");
                }else{
                    if(!manager.getUserId().equals(userId)){
                        responseEntity.failure(ResponseConstant.CODE_000, "此手机号码已被用户绑定！");
                    }else{
                        responseEntity.success("提交成功");
                    }
                }

            }else{
                responseEntity.failure(ResponseConstant.CODE_000, "验证码不正确，请重新输入");
            }
        }
        return responseEntity;
    }

    @Override
    public void updateManagerPhone(String userId, String phone) {
        dao.updateManagerPhone(userId,phone);
    }
    
    @Override
    public void updateManagerPhoto(String userId, String photo) {
        dao.updateManagerPhoto(userId,photo);
    }

    @Override
    public TbLibManager findByCourseNameAndGradeNotThis(String subject, String grade, int type, String teacherId) {
        return dao.findByCourseNameAndGradeNotThis(subject,grade,type,teacherId);
    }

    public void sendCodeToUser(String userId,String phone){
        Map<String, String> data = new HashMap<String, String>();
        String redisVcode = redisUtil.get("vcode_"+phone);
        if(redisVcode == null ){
            User user = userService.getById(userId);
            String vercode =(int)((Math.random()*9+1)*100000)+"";
            //存入redis
            redisUtil.set("vcode_"+phone,vercode,5*60);

            String template_id_short="OPENTM411737351";

            data.put("first","您收到一条私塾家登录验证码，五分钟内有效，请勿泄露！");
            data.put("keyword1",vercode);
            data.put("keyword2", DateHelper.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
            data.put("remark", "");
            SendTemplateShort templateShort = new SendTemplateShort(user.getAccount(), template_id_short,null, data);
            pushTemplateService.savePushWxTemplate(templateShort);
        }
     }
     @Override
     public int findActiveTeacherByLoginTime(String loginTime){
        return dao.findActiveTeacherByLoginTime(loginTime);
     }
     @Override
    public  int findRegisterUser(){
        return dao.findRegisterUser();
     }

    @Override
    public int findActiveUserByCreateTime(String createTime) {
        return dao.findActiveUserByCreateTime(createTime);
    }

    @Override
    public List<TbLibManager> findLibTeacherByLibId(String libId) {
        return dao.findByLibIdAndTypeAndStateAndIsCorrectOrderByIsOnlineDescAllotTimeAsc(libId, 15, 1, 1);
    }

    @Override
    public List<TbLibManager> findLibTeacherByLibId(String libId, String subject) {
        return dao.findByLibIdAndTypeAndStateAndCourseNameLikeOrderByIsOnlineDescAllotTimeAsc(libId, 15, 1, "%"+subject+"%");
    }

    @Override
    public int findCorrectTeacherType(String teacherId) {
        int[] types = {Constant.KMT_122_TEACHER_TYPE, Constant.LIB_TEACHER_TYPE, Constant.KNOW_MATCH_TYPE, 11};
        int teacherType = Constant.KMT_122_TEACHER_TYPE;
        TbLibManager teacher = this.findTopByUserIdAndTypeIn(teacherId, types);
        if (teacher != null && teacher.getType() != 11){
            teacherType = teacher.getType();
        }
        return teacherType;
    }

    @Override
    public ResponseEntity findOrgMyInfo(String teacherId) {
        ResponseEntity responseEntity = new ResponseEntity();

        //查询老师的资料
        SelfCorrectTeacherInfoDTO selfCorrectTeacherInfoDTO = libManagerMapper.findOrgMyInfo(teacherId, Constant.LIB_TEACHER_TYPE);
        if (selfCorrectTeacherInfoDTO == null) {
            return responseEntity.failure("请先联系管理员添加自批改老师身份");
        }

        //查询老师负责的学生
        List<StudentDTO> studentDtoList = libVipMapper.findManageStudentList(teacherId, selfCorrectTeacherInfoDTO.getLibId());
        studentDtoList = studentDtoList.stream()
                .sorted(Comparator.comparingInt(StudentDTO::getServiceSort))
                .distinct()
                .filter(it -> Objects.equals(2, it.getCorrectType()) || Objects.equals(it.getType(), "C025"))
                .collect(Collectors.toList());
        selfCorrectTeacherInfoDTO.setChildList(studentDtoList);

        return responseEntity.success(selfCorrectTeacherInfoDTO, "查询成功");
    }

    @Override
    public ResponseEntity findOrgMyInfoV1(String teacherId) {
        ResponseEntity responseEntity = new ResponseEntity();
        //查询老师所在校区列表
        //查询老师的资料
        List<SelfCorrectTeacherInfoDTO> list = libManagerMapper.findOrgMyInfoV1(teacherId, Constant.LIB_TEACHER_TYPE);
        if (CollectionUtils.isEmpty(list)) {
            return responseEntity.failure("请先联系管理员添加自批改老师身份");
        }
        SelfCorrectTeacherInfoDTO selfCorrectTeacherInfoDTO = list.get(0);
        OrgMyInfoDto orgMyInfoDto = new OrgMyInfoDto();
        orgMyInfoDto.setName(selfCorrectTeacherInfoDTO.getName());
        orgMyInfoDto.setPhoto(selfCorrectTeacherInfoDTO.getPhoto());
        orgMyInfoDto.setTelephone(selfCorrectTeacherInfoDTO.getTelephone());

        //查询老师所在校区学生列表
        List<OrgStudentDto> orgStudentDtoList = new ArrayList<>();
        StringBuffer orgNames = new StringBuffer();
        for (SelfCorrectTeacherInfoDTO dto : list) {
            //查询老师负责的学生
            List<StudentDTO> studentDtoList = libVipMapper.findManageStudentList(teacherId, dto.getLibId());
            if(CollectionUtils.isNotEmpty(studentDtoList)) {
                studentDtoList = studentDtoList.stream()
                        .sorted(Comparator.comparingInt(StudentDTO::getServiceSort))
                        .distinct()
                        .filter(it -> Objects.equals(2, it.getCorrectType()) || Objects.equals(it.getType(), "C025"))
                        .collect(Collectors.toList());

                //将学生信息放入实体
                for (StudentDTO studentDTO : studentDtoList) {
                    OrgStudentDto orgStudentDto = new OrgStudentDto();
                    orgStudentDto.setImgUrl(studentDTO.getImgUrl());
                    orgStudentDto.setStudentName(studentDTO.getStudentName());
                    orgStudentDto.setLeagueName(dto.getOrgName());
                    orgStudentDto.setVipId(studentDTO.getVipId());
                    orgStudentDto.setEndTime(studentDTO.getEndTime());
                    orgStudentDto.setServiceTime(studentDTO.getServiceTime());
                    orgStudentDto.setCorrectType(studentDTO.getCorrectType());
                    orgStudentDto.setType(studentDTO.getType());
                    orgStudentDto.setServiceSort(studentDTO.getServiceSort());
                    orgStudentDto.setCreateTime(studentDTO.getCreateTime());
                    orgStudentDtoList.add(orgStudentDto);
                }
            }
            orgNames.append(dto.getOrgName()).append(",");
        }
        orgMyInfoDto.setOrgName(orgNames.substring(0,orgNames.length()-1));
        orgMyInfoDto.setChildList(orgStudentDtoList);
        return responseEntity.success(orgMyInfoDto, "查询成功");
    }

    @Override
	public TbLibManager findAllByUserIdAndTypeAndState(String userId, int type, int state) {
		return dao.findAllByUserIdAndTypeAndState(userId, type, state);
	}

	@Override
	public TbLibManager findAllByUserIdAndTypeAndState(String libId,String userId, int type, int state) {
		return dao.findTopByLibIdAndUserIdAndTypeAndState(libId,userId, type, state);
	}
	
	
	@Override
	public List<TbLibManager> findByUserIdAndTypeInAndState(String userId, int[] type, int state) {
		return dao.findByUserIdAndTypeInAndState(userId, type, state);
	}

    /*@Override
    public List<TbLibManager> findByUserIdAndTypeInAndState(String libId, String userId, int[] type, int state) {
        return dao.findByLibIdAndUserIdAndTypeInAndState(libId, userId, type, state);
    }*/

    @Override
    public List<TbLibManager> findList(String libId, String userId, int[] type, Integer state) {
        if (state != null) {
            return dao.findByLibIdAndUserIdAndTypeInAndStateOrderByType(libId, userId, type, state);
        }
        return dao.findByLibIdAndUserIdAndTypeInOrderByType(libId, userId, type);
    }

    @Override
    public TbLibManager saveTypeTbLibManager(User user, CreateTeacherRequest dto, String libId, int type) {
        TbLibManager tbLibManager = this.findByLibIdAndUserIdAndType(libId,user.getId(), type);
        if(tbLibManager==null){
            tbLibManager=new TbLibManager();
            tbLibManager.settPhoto(user.getPhoto());
            tbLibManager.setUserId(user.getId());
            tbLibManager.setType(type);
            tbLibManager.setCreateTime(new Date());
            tbLibManager.setName(user.getUserName());
            tbLibManager.setTelephone(user.getMobile());
            tbLibManager.setCourseName(StringUtil.join(dto.getSubjectList(), ","));
            if(CollectionUtils.isEmpty(dto.getSubjectList())) {
                tbLibManager.setCourseName("语文,数学,英语");
            }
            tbLibManager.setLibId(libId);
            tbLibManager.setState(1);
        } else {
            tbLibManager.settPhoto(user.getPhoto());
            tbLibManager.setTelephone(user.getMobile());
            tbLibManager.setName(user.getUserName());
            tbLibManager.setCourseName(StringUtil.join(dto.getSubjectList(), ","));
            if(CollectionUtils.isEmpty(dto.getSubjectList())) {
                tbLibManager.setCourseName("语文,数学,英语");
            }
            tbLibManager.setState(1);
            tbLibManager.setLibId(libId);
        }
        this.save(tbLibManager);
        return tbLibManager;
    }

    @Override
    public void saveTbLibManagerStatus(String userId, int type, int status) {
        TbLibManager libManager = this.findByUserId(userId, type);
        if (libManager != null){
            libManager.setState(status);
            this.save(libManager);
        }
    }

    @Override
    public void saveTbLibManagerListStatus(String userId, int[] types, int status) {
        String date = DateHelper.format(new Date(),"yyyy-MM-dd HH:mm:ss");
        List<TbLibManager> platformTbLibManagers = this.findByUserIdAndTypeInAndState(userId, types,1);
        if(platformTbLibManagers!=null && platformTbLibManagers.size()>0) {
            for (TbLibManager platformTbLibManager : platformTbLibManagers) {
                platformTbLibManager.setState(status);
                if (status == 2) {
                    //删除审批记录
                    List<TbLibManagerAudit> auditList = libManagerAuditService.findByLibManagerId(platformTbLibManager.getId());
                    auditList.forEach(e -> {
                        e.setMongodbComment(date + "：备份删除审批记录");
                        mongoTemplate.save(e);
                        libManagerAuditService.delete(e);
                    });
                }
            }
            this.save(platformTbLibManagers);
        }
    }
    
    @Override
    public void saveTbLibManagerListStatus(String libId,String userId, int[] types, int status) {
        String date = DateHelper.format(new Date(),"yyyy-MM-dd HH:mm:ss");
        List<TbLibManager> platformTbLibManagers = this.findList(libId,userId, types,1);
        if(platformTbLibManagers!=null && platformTbLibManagers.size()>0) {
            for (TbLibManager platformTbLibManager : platformTbLibManagers) {
                platformTbLibManager.setState(status);
                if (status == 2) {
                    //删除审批记录
                    List<TbLibManagerAudit> auditList = libManagerAuditService.findByLibManagerId(platformTbLibManager.getId());
                    auditList.forEach(e -> {
                        e.setMongodbComment(date + "：备份删除审批记录");
                        mongoTemplate.save(e);
                        libManagerAuditService.delete(e);
                    });
                }
            }
            this.save(platformTbLibManagers);
        }
    }


	@Override
	public List<TbLibManager> findTbLibManagerByLibId(String libId, int type, int status) {
		return dao.findTbLibManagerByLibId(libId, type, status);
	}

    @Override
    public List<TbLibManager> findClassTeacherList(String vipId, String subject, int type) {
        if (StringUtil.isNotBlank(subject)) {
            return dao.findClassTeacherList(vipId, subject, type);
        }
        return dao.findClassTeacherList(vipId, type);
    }

    @Override
    public TbLibManager findTopClassTeacherList(String vipId, String subject, int type) {
        if (StringUtil.isNotBlank(subject)) {
            return dao.findTopClassTeacherList(vipId, subject, type);
        }
        return dao.findTopClassTeacherList(vipId, type);
    }


    @Override
    public int findCountByUserIdAndTypesAndStatus1(String userId, int[] types) {
        return dao.findCountByUserIdAndTypesAndStatus1(userId, types);
    }
    
    @Override
    public int findCountByUserIdAndTypesAndStatus1(String libId,String userId, int[] types) {
        return dao.findCountByUserIdAndTypesAndStatus1(libId,userId, types);
    }

    @Override
    public int findCountIsNotLibByUserIdAndTypesAndStatus(String libId, String userId, int[] type) {
        return dao.findCountIsNotLibByUserIdAndTypesAndStatus(libId,userId,type);
    }

    @Override
    public TbLibManager findByTelephoneAndTypesIn(String telephone, int[] types) {
        return dao.findByTelephoneAndTypesIn(telephone, types);
    }


    @Override
    public List<TbLibManager> findAllManagerByTeacherId(String teacherId){
        return dao.findAllManagerByTeacherId(teacherId);
    }

    @Override
    public List<TbLibManager> findLibTeacherByLibIdAndType(String libId,int type){
        return dao.findLibTeacherByLibIdAndType(libId,type);
    }

    @Override
    public void updateCancelStatusByUserId(String userId){
        dao.updateCancelStatusByUserId(userId);
    }


    @Override
    public void updateStatusByUserId(String userId){
        dao.updateStatusByUserId(userId);
    }

    @Override
    public List<TbLibManager> findAllValidTeacherList(String userId,int[]types){
      return dao.findAllValidTeacherList(userId,types);
    }

    @Override
    public TbLibManager findByLibIdAndUserIdAndType(String libId, String userId, int type) {
        return dao.findTopByLibIdAndUserIdAndTypeAndState(libId, userId, type, 1);
    }

    @Override
    public List<TbLibManager> findAllByUserIdAndTypeAndStatus(String teacherId,int type) {
        return dao.findAllByUserIdAndTypeAndStatus(teacherId,type);
    }

    @Override
    public TbLibManager findByTypeAndState(int type,int state){
        return dao.findExerciseByTypeAndState(type,state);
    }

    @Override
    public List<TbLibManager> findByNameAndType(String name, int type) {
        return libManagerMapper.findManagerByNameAndType(name, type);
    }

    @Override
    public TbLibManager findOneManagerBySubject (String subject){
        return libManagerMapper.findRandManagerByTypeAndSubject(subject);
    }
}


