package yangtz.cs.liu.campus.service.impl.teacherFiles;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import org.apache.catalina.User;
import org.apache.regexp.RE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.controller.A;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClassMentor;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.teacherFiles.TeacherFiles;
import yangtz.cs.liu.campus.domain.teacherFiles.TeacherFilesNotice;
import yangtz.cs.liu.campus.domain.teacherFiles.TeacherFilesNoticeTotal;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMapper;
import yangtz.cs.liu.campus.mapper.schoolClass.SchoolClassMentorMapper;
import yangtz.cs.liu.campus.mapper.schoolgrade.SchoolGradeMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.mapper.teacherFiles.TeacherFilesMapper;
import yangtz.cs.liu.campus.mapper.teacherFiles.TeacherFilesNoticeMapper;
import yangtz.cs.liu.campus.service.teacherFiles.ITeacherFilesNoticeService;
import yangtz.cs.liu.campus.service.teacherFiles.ITeacherFilesService;
import yangtz.cs.liu.wechat.vo.schoolClass.SchoolClassVo;
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;



/**
 * 教师档案通知Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-09-06
 */
@Service
public class TeacherFilesNoticeServiceImpl  extends ServiceImpl<TeacherFilesNoticeMapper,TeacherFilesNotice> implements ITeacherFilesNoticeService
{
    @Autowired
    private TeacherFilesNoticeMapper teacherFilesNoticeMapper;

    @Autowired
    private TeacherFilesMapper teacherFilesMapper;

    @Autowired
    private SchoolGradeMapper schoolGradeMapper;

    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;


    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SchoolClassMapper schoolClassMapper;
    @Autowired
    private SchoolClassMentorMapper classMentorMapper;
    @Autowired
    private SchoolGradeMapper gradeMapper;
    /**
     * 教师教室档案通知
     * 
     * @param id 教师档案通知主键
     * @return 教师档案通知
     */
    @Override
    public TeacherFilesNotice selectTeacherFilesNoticeById(String id)
    {
        return teacherFilesNoticeMapper.selectTeacherFilesNoticeById(id);
    }

    /**
     * 查询教师档案通知列表
     * 
     * @param teacherFilesNotice 教师档案通知
     * @return 教师档案通知
     */
    @Override
    public List<TeacherFilesNoticeTotal> selectTeacherFilesNoticeList(TeacherFilesNotice teacherFilesNotice)
    {
        return teacherFilesNoticeMapper.selectTeacherFilesNoticeList(teacherFilesNotice);
    }

    @Autowired
    ITeacherFilesService iTeacherFilesService;

    /**
     * 新增教师档案通知
     * 
     * @param teacherFilesNotice 教师档案通知
     * @return 结果
     */
    @Override
    public int insertTeacherFilesNotice(TeacherFilesNotice teacherFilesNotice)
    {
        // TODO 修改最新学年
        int schoolYear = gradeMapper.isNewSchoolYear();
        String noticeId = UUID.randomUUID().toString().replaceAll("-","");
        //补充通知字段
        teacherFilesNotice.setNoticeRange("全体教师");
        teacherFilesNotice.setId(noticeId);
        teacherFilesNotice.setNoticeName(teacherFilesNotice.getNoticeYear()+"学年"+teacherFilesNotice.getNoticeSemester()+"教师档案填写");
        teacherFilesNotice.setNoticeState("1");
        teacherFilesNotice.setCreateTime(DateUtils.getNowDate());
        int i = teacherFilesNoticeMapper.insertTeacherFilesNotice(teacherFilesNotice);
        //获取所有带级部的部门
        List<SysDept> sysDepts = sysDeptMapper.selectDepartmentDept("级部");
        List<SysUser>  userList = new ArrayList<>();
        List<SchoolGrade> schoolGrades = new ArrayList<>();
        //级部信息查询
        for (SysDept dept :sysDepts){
            String[] split = dept.getAncestors().split(",");
            if (split.length != 2){
                continue;
            }
            //找到每一个级部下所有的人员
            List<SysUser> sysUsers = sysUserMapper.selectDeptAncetorsByPernId(dept.getDeptId().toString());
            SchoolGrade schoolGrade = schoolGradeMapper.selectGradeByName(dept.getDeptName());
            Map<String,Object> map = new HashMap<>();
            map.put("grade",schoolGrade);
            sysUsers.forEach(date->{
                date.setParams(map);
            });
            userList.addAll(sysUsers);
        }
        List<SysUser> collect = userList.stream().filter(SysUser -> SysUser.getUserId() != null).collect(Collectors.toList());
        //获取所有老师 去重
        List<SysUser> trrUserList = collect.stream().collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(SysUser::getUserId))), ArrayList::new));
        //课程集合
        List<SchoolClassMentor> schoolClassMentors = classMentorMapper.selectList(null);
        //老师信息
        List<SchoolTeacher> schoolTeachers = schoolTeacherMapper.selectList(null);
        //查出所有班级信息
        List<SchoolClass> schoolClasses = schoolClassMapper.selectList(null);

        List<TeacherFiles>  teacherFilesList = new ArrayList<>();
        for (SysUser user : trrUserList){
            //部门
            Map<String, Object> params = user.getParams();
            SchoolGrade schoolGrade = (SchoolGrade)params.get("grade");
            //获取级部
            //查看当前老师是否在班级中当班主任
            List<SchoolClass> yxyjList = schoolClasses.stream().filter(p -> p.getTeacherId() !=null &&  p.getTeacherId().equals(user.getUserId())).collect(Collectors.toList());
           String teahClassName = null;
           String className = null;
            //只取第一个
            if (!yxyjList.isEmpty()){
                teahClassName = yxyjList.get(0).getClassName();
                className = yxyjList.get(0).getClassName();
            }
            //班主任信息
            TeacherFiles teacherFiles = new TeacherFiles();
            teacherFiles.setTeacherId(user.getUserId());
            teacherFiles.setNoticeId(noticeId);
            teacherFiles.setFilesSemester(teacherFilesNotice.getNoticeYear()+"学年"+teacherFilesNotice.getNoticeSemester());
            teacherFiles.setGradeId(schoolGrade.getId());
            teacherFiles.setGradeName(schoolGrade.getGradeName());
            teacherFiles.setBzrClassName(teahClassName);
            teacherFiles.setState("1");
            teacherFiles = teacherFilesAddXx(teacherFiles,schoolTeachers); //老师个人信息
            //找到老师课程
            List<SchoolClass> schoolYept = this.getSchoolYept(schoolClassMentors, schoolClasses, user,schoolYear);
//            List<SchoolClassMentor> mentorByTeacherId = classMentorMapper.getMentorByTeacherId(user.getUserId(), schoolYear);
            if (!schoolYept.isEmpty()){
                    className = schoolYept.get(0).getClassName();
                }
            teacherFiles.setClassName(className);
            teacherFilesList.add(teacherFiles);
        }
        //导入数据库
        iTeacherFilesService.saveBatch(teacherFilesList);
        return i;
    }

    TeacherFiles teacherFilesAddXx(TeacherFiles teacherFiles,  List<SchoolTeacher> schoolTeachers){
        System.err.println(teacherFiles.toString());
        List<SchoolTeacher> collect = schoolTeachers.stream().filter(t -> t.getId().equals(teacherFiles.getTeacherId())).collect(Collectors.toList());
        SchoolTeacher schoolTeacher = collect.get(0);
        teacherFiles.setTeacherName(schoolTeacher.getTeacherName());
        teacherFiles.setIdCard(schoolTeacher.getIdCard());
        teacherFiles.setSex(schoolTeacher.getSex());
        teacherFiles.setEducation(schoolTeacher.getEducation());
        Date birthday = schoolTeacher.getBirthday();
        if(birthday!=null){
            SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy");
            Integer birthdayYear = Integer.valueOf(dateFormat.format(birthday));
            Date date = new Date();
            Integer nowYear = Integer.valueOf(dateFormat.format(date));
            teacherFiles.setAge(nowYear-birthdayYear);
        }
        teacherFiles.setTitle("");
        teacherFiles.setAppearance("");
        return teacherFiles;
    }

    /**
     * 修改教师档案通知
     * 
     * @param teacherFilesNotice 教室档案通知
     * @return 结果
     */
    @Override
    public int updateTeacherFilesNotice(TeacherFilesNotice teacherFilesNotice)
    {
        teacherFilesNotice.setUpdateTime(DateUtils.getNowDate());
        teacherFilesNotice.setNoticeName(teacherFilesNotice.getNoticeYear()+"学年"+teacherFilesNotice.getNoticeSemester()+"教师档案填写");
        int i = teacherFilesNoticeMapper.updateTeacherFilesNotice(teacherFilesNotice);
        Map map = new HashMap();
        map.put("noticeId",teacherFilesNotice.getId());
        map.put("filesSemester",teacherFilesNotice.getNoticeYear()+"学年"+teacherFilesNotice.getNoticeSemester());
        teacherFilesMapper.updateTeacherFilesName(map);
        return i;
    }

    @Override
    public int release(String id) {
        //通知
        TeacherFilesNotice teacherFilesNotice =new TeacherFilesNotice();
        teacherFilesNotice.setId(id);
        teacherFilesNotice.setUpdateTime(DateUtils.getNowDate());
        teacherFilesNotice.setNoticeState("2");
        teacherFilesNoticeMapper.updateTeacherFilesNotice(teacherFilesNotice);
        //修改任务状态
        int i = teacherFilesMapper.updateTeacherFilesState(id);
        return i;
    }

    @Override
    public int withdraw(String id) {
        TeacherFilesNotice teacherFilesNotice =new TeacherFilesNotice();
        teacherFilesNotice.setId(id);
        teacherFilesNotice.setUpdateTime(DateUtils.getNowDate());
        teacherFilesNotice.setNoticeState("1");
//        int i = teacherFilesMapper.updateTeacherFilesState1(id);
        int i = teacherFilesNoticeMapper.updateTeacherFilesNotice(teacherFilesNotice);
        return i;
    }

    @Override
    public int complete(String id) {
        TeacherFilesNotice teacherFilesNotice =new TeacherFilesNotice();
        teacherFilesNotice.setId(id);
        teacherFilesNotice.setUpdateTime(DateUtils.getNowDate());
        teacherFilesNotice.setNoticeState("7");
        int i = teacherFilesMapper.updateTeacherFilesState7(id);
        teacherFilesNoticeMapper.updateTeacherFilesNotice(teacherFilesNotice);
        return i;
    }

    /**
     * 批量删除教师档案通知
     * 
     * @param ids 需要删除的教室档案通知主键
     * @return 结果
     */
    @Override
    public int deleteTeacherFilesNoticeByIds(String[] ids)
    {
        return teacherFilesNoticeMapper.deleteTeacherFilesNoticeByIds(ids);
    }

    /**
     * 删除教师档案通知信息
     * 
     * @param ids 教室档案通知主键
     * @return 结果
     */
    @Override
    public int deleteTeacherFilesNoticeById(String[] ids)
    {
        int i = teacherFilesNoticeMapper.deleteTeacherFilesNoticeByIds(ids);
        for(String id :ids){
            teacherFilesMapper.deleteTeacherFilesByNoticeId(id);
        }
        return i;
    }


    /**
     * 条件查询转换
     * @return
     */

    private List<SchoolClass> getSchoolYept(List<SchoolClassMentor> mentorByTeacherId , List<SchoolClass> classVos , SysUser user,Integer schoolYear ){
        List<SchoolClass> list = new ArrayList<>();
        //找到当前教师任课的信息
        List<SchoolClassMentor> collect = mentorByTeacherId.stream().filter(p -> p.getTeacherId().equals(user.getUserId())).collect(Collectors.toList());
        //1.关联查询当前学年的班级
        for (SchoolClass classDate : classVos) {
            //1。学年是当前
            if (classDate.getSchoolYear().equals(schoolYear) ){
                if (collect.isEmpty()){
                    return new ArrayList<SchoolClass>();
                }
                //2.学科关联
                for (SchoolClassMentor cm :collect){
                        if (cm.getClassId() == classDate.getId()){
                            list.add(classDate);
                        }
                }
            }
        }
        return  list;
    }
}
