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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TermRange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yangtz.cs.liu.campus.domain.accessory.SchoolAccessory;
import yangtz.cs.liu.campus.domain.award.Award;
import yangtz.cs.liu.campus.domain.material.Material;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClass;
import yangtz.cs.liu.campus.domain.schoolClass.SchoolClassMentor;
import yangtz.cs.liu.campus.domain.teacherFiles.*;
import yangtz.cs.liu.campus.domain.thesis.Thesis;
import yangtz.cs.liu.campus.domain.training.Training;
import yangtz.cs.liu.campus.mapper.accessory.AccessoryMapper;
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.*;
import yangtz.cs.liu.campus.service.teacherFiles.ITeacherFilesService;
import yangtz.cs.liu.wechat.vo.schoolClass.SchoolClassVo;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 教师档案Service业务层处理
 *
 * @author ruoyi
 * @date 2023-09-06
 */
@Service
public class TeacherFilesServiceImpl  extends ServiceImpl<TeacherFilesMapper, TeacherFiles> implements ITeacherFilesService
{
    @Autowired
    private TeacherFilesMapper teacherFilesMapper;

    @Autowired
    private TeacherFilesMaterialMapper FmaterialMapper;

    @Autowired
    private TeacherFilesThesisMapper FthesisMapper;

    @Autowired
    private TeacherFilesAwardMapper FawardMapper;

    @Autowired
    private TeacherFilesTrainingMapper FtrainingMapper;

    @Autowired
    private TeacherFilesNoticeMapper teacherFilesNoticeMapper;

    @Autowired
    private TeacherFilesDeletRecordMapper teacherFilesDeletRecordMapper;
    @Autowired
    private SchoolClassMapper schoolClassMapper;
    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;

    @Autowired
    private SchoolGradeMapper gradeMapper;

    @Autowired
    private SchoolClassMentorMapper classMentorMapper;

    @Autowired
    private AccessoryMapper accessoryMapper;

    /**
     * 查询教师档案
     *
     * @param id 教师档案主键
     * @return 教师档案
     */
    @Override
    public TeacherFilesVO selectTeacherFilesById(Long id)
    {


        TeacherFilesVO teacherFiles = teacherFilesMapper.selectTeacherFilesById(id);
        //教师档案课题编写情况
        List<TeacherFilesMaterial> teacherFilesMaterials = FmaterialMapper.selectTeacherFilesMaterialListByFilesId(id);
        for (TeacherFilesMaterial date :teacherFilesMaterials){
            LambdaQueryWrapper<SchoolAccessory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SchoolAccessory::getBusinessId,date.gettId())
                    .eq(SchoolAccessory::getAccessoryType,"材料编写附件");
            List<SchoolAccessory> accessories = accessoryMapper.selectList(wrapper);
            date.setAccessories(accessories);
        }
        teacherFiles.setMaterialList(teacherFilesMaterials);
        //论文
        List<TeacherFilesThesis> teacherFilesTheses = FthesisMapper.selectTeacherFilesThesisListByFilesId(id);
        for (TeacherFilesThesis date : teacherFilesTheses){
            LambdaQueryWrapper<SchoolAccessory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SchoolAccessory::getBusinessId,date.gettId())
                    .eq(SchoolAccessory::getAccessoryType,"论文情况附件");
            List<SchoolAccessory> accessories = accessoryMapper.selectList(wrapper);
            date.setSchoolAccessoryList(accessories);
        }
        teacherFiles.setThesisList(teacherFilesTheses);
        //教师档案培训情况
        List<TeacherFilesTraining> teacherFilesTrainings = FtrainingMapper.selectTeacherFilesTrainingListByFilesId(id);
        for (TeacherFilesTraining date :teacherFilesTrainings){
            LambdaQueryWrapper<SchoolAccessory> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SchoolAccessory::getBusinessId,date.gettId())
                    .eq(SchoolAccessory::getAccessoryType,"培训情况附件");
            List<SchoolAccessory> accessories = accessoryMapper.selectList(wrapper);
            date.setAccessories(accessories);
        }
        teacherFiles.setTrainingList(teacherFilesTrainings);
        //教师档案获奖情况
        List<TeacherFilesAward> teacherFilesAwards = FawardMapper.selectTeacherFilesAwardListByFilesId(id);
            for (TeacherFilesAward date :teacherFilesAwards){
                LambdaQueryWrapper<SchoolAccessory> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SchoolAccessory::getBusinessId,date.gettId())
                        .eq(SchoolAccessory::getAccessoryType,"获奖情况附件");
                List<SchoolAccessory> accessories = accessoryMapper.selectList(wrapper);
                date.setAccessories(accessories);
            }
        teacherFiles.setAwardList(teacherFilesAwards);
        return teacherFiles;
    }

    /**
     * 查询教师档案列表
     *
     * @param teacherFiles 教师档案
     * @return 教师档案
     */
    @Override
    public List<TeacherFiles> selectTeacherFilesList(TeacherFiles teacherFiles)
    {
        return teacherFilesMapper.selectTeacherFilesList(teacherFiles);
    }

    /**
     * 统计已发布
     * @param teacherFiles 教师档案
     * @return
     */
    @Override
    public int countYfb(TeacherFiles teacherFiles) {
        return teacherFilesMapper.countYfb(teacherFiles);
    }

    /**
     * 统计已确认
     * @param teacherFiles 教师档案
     * @return
     */
    @Override
    public int countYqr(TeacherFiles teacherFiles) {
        return teacherFilesMapper.countYqr(teacherFiles);
    }


    public List<TeacherFilesNotice> selctTeacherByUserId(TeacherFiles teacherFiles) {
        return teacherFilesNoticeMapper.selctTeacherByUserId(teacherFiles);
    }

    /**
     * 新增教师档案
     *
     * @param teacherFiles 教师档案
     * @return 结果
     */
    @Override
    public int insertTeacherFiles(TeacherFiles teacherFiles)
    {
        return teacherFilesMapper.insertTeacherFiles(teacherFiles);
    }

    /**
     * 修改教师档案
     *
     * @param teacherFiles 教师档案
     * @return 结果
     */
    @Override
    public int updateTeacherFiles(TeacherFiles teacherFiles)
    {
        return teacherFilesMapper.updateTeacherFiles(teacherFiles);
    }

    /**
     * 批量删除教师档案
     *
     * @param ids 需要删除的教师档案主键
     * @return 结果
     */
    @Override
    public int deleteTeacherFilesByIds(Long[] ids)
    {
        //1.保留人员到删除信息表中
        for (int i=0 ; i < ids.length ;i++){
            TeacherFilesVO teacherFilesVO = teacherFilesMapper.selectTeacherFilesById(ids[i]);
            TeacherFilesDeletRecord teacherFilesDeletRecord = new TeacherFilesDeletRecord();
            teacherFilesDeletRecord.setTel(teacherFilesVO.getIdCard() == null ? "" : teacherFilesVO.getIdCard());
            teacherFilesDeletRecord.setUserName(teacherFilesVO.getTeacherName());
            teacherFilesDeletRecord.setGruoName(teacherFilesVO.getGradeName());
            teacherFilesDeletRecord.setUserId(teacherFilesVO.getTeacherId());
            teacherFilesDeletRecord.setTId(teacherFilesVO.getNoticeId());
            teacherFilesDeletRecord.setGId(teacherFilesVO.getGradeId());
            teacherFilesDeletRecordMapper.addTeacherFilesDeletRecord(teacherFilesDeletRecord);
        }
        //2.删除人员
        int i = teacherFilesMapper.deleteTeacherFilesByIds(ids);
        return i;
    }


    /**
     * 查询老师
     * @param tId
     * @return
     */
    @Override
    public List<TeacherFilesDeletRecord> getTeacherRocer(String tId) {
        List<TeacherFilesDeletRecord> teacherRocer = teacherFilesDeletRecordMapper.getTeacherRocer(tId);
        return teacherRocer;
    }


    /**
     * 新增老师数据
     * @param ids
     * @return
     */
    @Override
    public Integer teacherAdd(Long[] ids) {
        List<TeacherFiles>  teacherFilesList = new ArrayList<>();

        for (int i =0; i< ids.length ;i++){
         TeacherFilesDeletRecord byid = teacherFilesDeletRecordMapper.getByid(ids[i]);
            TeacherFilesNotice teacherFilesNotice = teacherFilesNoticeMapper.selectTeacherFilesNoticeById(byid.getTId().toString());
            List<SchoolClassVo> schoolClassVos = schoolClassMapper.selectTeacherByTeachId(byid.getUserId());
        String teahClassName = null;
        String className = null;
        //只取第一个
        if (!schoolClassVos.isEmpty()){
            teahClassName = schoolClassVos.get(0).getClassName();
            className = schoolClassVos.get(0).getClassName();
        }
        //班主任信息
        TeacherFiles teacherFiles = new TeacherFiles();
        teacherFiles.setTeacherId(byid.getUserId());
        teacherFiles = teacherFilesAddXx(teacherFiles);
        teacherFiles.setNoticeId(byid.getTId().toString());
        teacherFiles.setFilesSemester(teacherFilesNotice.getNoticeYear()+"学年"+teacherFilesNotice.getNoticeSemester());
        teacherFiles.setGradeId(byid.getGId());
        teacherFiles.setGradeName(byid.getGruoName());
        teacherFiles.setBzrClassName(teahClassName);
        teacherFiles.setState("1");
        teacherFiles = teacherFilesAddXx(teacherFiles); //老师个人信息
        //找到老师课程
        // TODO 修改最新学年
        int schoolYear = gradeMapper.isNewSchoolYear();
        List<SchoolClassMentor> mentorByTeacherId = classMentorMapper.getMentorByTeacherId(byid.getUserId(), schoolYear);
        if (!mentorByTeacherId.isEmpty()){
            teacherFiles.setCourseName(mentorByTeacherId.get(0).getCourseName());
            if (StringUtils.isEmpty(className)){
                //根据课程关联找寻班级
                SchoolClass schoolClass = schoolClassMapper.selectById(mentorByTeacherId.get(0).getClassId());
                className = schoolClass.getClassName();
            }
        }
        teacherFiles.setClassName(className);
        teacherFilesList.add(teacherFiles);
            teacherFilesDeletRecordMapper.deletRecord(ids[i]);
        }
        //导入数据库
        teacherFilesList.forEach(date->{
            teacherFilesMapper.insertTeacherFiles(date);
        });

        //删除id

        return 1;
    }

    /**
     * 删除教师档案信息
     *
     * @param id 教师档案主键
     * @return 结果
     */
    @Override
    public int deleteTeacherFilesById(Long id)
    {
        return teacherFilesMapper.deleteTeacherFilesById(id);
    }

    @Override
    public int synchronous(Long id) {
        TeacherFilesVO teacherFiles = teacherFilesMapper.selectTeacherFilesById(id);
        TeacherFilesNotice teacherFilesNotice = teacherFilesNoticeMapper.selectTeacherFilesNoticeById(teacherFiles.getNoticeId());
        Map map = new HashMap<>();
        map.put("teacherId",teacherFiles.getTeacherId());
        TermRange termRange = DateUtils.getTermRange(teacherFilesNotice.getNoticeYear(), teacherFilesNotice.getNoticeSemester());
        map.put("startDay",termRange.getStartDay());
        map.put("endDay",termRange.getEndDay());
        FthesisMapper.deleteTeacherFilesThesisByFilesId(id);
        for (Thesis thesis:FthesisMapper.selectThesisList(map)){
            TeacherFilesThesis teacherFilesThesis = new TeacherFilesThesis();
            teacherFilesThesis.setFilesId(id);
            teacherFilesThesis.settId(thesis.getId());
            teacherFilesThesis.setThesisName(thesis.getThesisName());
            teacherFilesThesis.setLevel(thesis.getLevel());
            teacherFilesThesis.setGrade(thesis.getGrade());
            teacherFilesThesis.setPublishTime(thesis.getPublishTime());
            FthesisMapper.insertTeacherFilesThesis(teacherFilesThesis);
        }
        FmaterialMapper.deleteTeacherFilesMaterialByFilesId(id);
        for (Material material:FmaterialMapper.selectMaterialList(map)){
            TeacherFilesMaterial teacherFilesMaterial = new TeacherFilesMaterial();
            teacherFilesMaterial.setFilesId(id);
            teacherFilesMaterial.settId(material.getId());
            teacherFilesMaterial.setName(material.getName());
            teacherFilesMaterial.setPublishTime(material.getPublishTime());
            FmaterialMapper.insertTeacherFilesMaterial(teacherFilesMaterial);
        }
        FawardMapper.deleteTeacherFilesAwardByFilesId(id);
        for(Award award : FawardMapper.selectAwardList(map)){
            TeacherFilesAward teacherFilesAward =new TeacherFilesAward();
            teacherFilesAward.setFilesId(id);
            teacherFilesAward.settId(award.getId());
            teacherFilesAward.setAwardName(award.getAwardName());
            teacherFilesAward.setAwardTime(award.getAwardTime());
            teacherFilesAward.setGradeOfAward(award.getGradeOfAward());
            teacherFilesAward.setLicenseIssuingAuthority(award.getLicenseIssuingAuthority());
            FawardMapper.insertTeacherFilesAward(teacherFilesAward);
        }
        FtrainingMapper.deleteTeacherFilesTrainingByFilesId(id);
        for (Training training : FtrainingMapper.selectTrainingList(map)){
            TeacherFilesTraining teacherFilesTraining = new TeacherFilesTraining();
            teacherFilesTraining.setFilesId(id);
            teacherFilesTraining.settId(training.getId());
            teacherFilesTraining.setTrainingName(training.getTrainingName());
            teacherFilesTraining.setTrainingTime(training.getTrainingTime());
            teacherFilesTraining.setIsQualified(training.getIsQualified());
            FtrainingMapper.insertTeacherFilesTraining(teacherFilesTraining);
        }
        return 1;
    }

    @Override
    public List<Long> getGradeId(Long teacherId) {
        return teacherFilesMapper.getGradeId(teacherId);
    }


    TeacherFiles teacherFilesAddXx(TeacherFiles teacherFiles){
        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectSchoolTeacherById(teacherFiles.getTeacherId());
        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;
    }
}
