package com.schoolinout.system.service.impl;

import com.schoolinout.common.constant.DictConstants;
import com.schoolinout.common.exception.ServiceException;
import com.schoolinout.common.utils.DateUtils;
import com.schoolinout.system.domain.Clazz;
import com.schoolinout.system.domain.Teacher;
import com.schoolinout.system.domain.TeacherClassRelation;
import com.schoolinout.system.domain.dto.AddTeacherClassRelationDto;
import com.schoolinout.system.domain.dto.BindClassTeacherMain;
import com.schoolinout.system.domain.dto.RelationListDto;
import com.schoolinout.system.domain.vo.TeacherClassInfoVo;
import com.schoolinout.system.mapper.ClazzMapper;
import com.schoolinout.system.mapper.TeacherClassRelationMapper;
import com.schoolinout.system.mapper.TeacherMapper;
import com.schoolinout.system.service.ITeacherClassRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 老师-班级关系Service业务层处理
 *
 * @author sakura
 * @date 2024-01-04
 */
@Service
public class TeacherClassRelationServiceImpl implements ITeacherClassRelationService {
    @Autowired
    private TeacherClassRelationMapper teacherClassRelationMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private ClazzMapper clazzMapper;

    /**
     * 查询老师-班级关系
     *
     * @param id 老师-班级关系主键
     * @return 老师-班级关系
     */
    @Override
    public TeacherClassRelation selectTeacherClassRelationById(Long id) {
        return teacherClassRelationMapper.selectTeacherClassRelationById(id);
    }

    /**
     * 查询老师-班级关系列表
     *
     * @param teacherClassRelation 老师-班级关系
     * @return 老师-班级关系
     */
    @Override
    public List<TeacherClassRelation> selectTeacherClassRelationList(TeacherClassRelation teacherClassRelation) {
        return teacherClassRelationMapper.selectTeacherClassRelationList(teacherClassRelation);
    }

    /**
     * 新增老师-班级关系
     *
     * @param teacherClassRelation 老师-班级关系
     * @return 结果
     */
    @Override
    public int insertTeacherClassRelation(TeacherClassRelation teacherClassRelation) {
        teacherClassRelation.setCreateTime(DateUtils.getNowDate());
        return teacherClassRelationMapper.insertTeacherClassRelation(teacherClassRelation);
    }

    /**
     * 修改老师-班级关系
     *
     * @param teacherClassRelation 老师-班级关系
     * @return 结果
     */
    @Override
    public int updateTeacherClassRelation(TeacherClassRelation teacherClassRelation) {
        teacherClassRelation.setUpdateTime(DateUtils.getNowDate());
        return teacherClassRelationMapper.updateTeacherClassRelation(teacherClassRelation);
    }

    /**
     * 批量删除老师-班级关系
     *
     * @param ids 需要删除的老师-班级关系主键
     * @return 结果
     */
    @Override
    public int deleteTeacherClassRelationByIds(Long[] ids) {
        return teacherClassRelationMapper.deleteTeacherClassRelationByIds(ids);
    }

    /**
     * 删除老师-班级关系信息
     *
     * @param id 老师-班级关系主键
     * @return 结果
     */
    @Override
    public int deleteTeacherClassRelationById(Long id) {
        return teacherClassRelationMapper.deleteTeacherClassRelationById(id);
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, ServiceException.class})
    public int bindTeacherClass(AddTeacherClassRelationDto form) {
        // 先查询原班级关系数据
        TeacherClassRelation queryRelation = new TeacherClassRelation();
        // 先查询当前教师包含的所有的关系
        queryRelation.setTeacherId(form.getTeacherId());
        queryRelation.setSchoolId(form.getSchoolId());
        List<TeacherClassRelation> existingRelations = teacherClassRelationMapper.selectTeacherClassRelationList(queryRelation);

        // 将现有关系映射为班级ID集合
        Set<Long> existingClassIds = existingRelations.stream()
                .map(TeacherClassRelation::getClassId)
                .collect(Collectors.toSet());
        List<Long> newClassIds = form.getClassId();
        if (newClassIds == null || newClassIds.isEmpty()) {
            teacherClassRelationMapper.deleteAllRelationsForClass(form.getSchoolId(), null, form.getTeacherId());
        } else if (existingClassIds == null || existingClassIds.isEmpty()) {
            teacherClassRelationMapper.insertRelationBatchForClassId(form.getSchoolId(), form.getTeacherId(), newClassIds);
        } else {
            // 计算要删除的id
            List<Long> classIdsToRemove = existingClassIds.stream()
                    .filter(item -> !newClassIds.contains(item))
                    .collect(Collectors.toList());
            // 计算要新增的id
            boolean classIdsToAdd = newClassIds.removeAll(classIdsToRemove);

            // 执行批量删除
            if (!classIdsToRemove.isEmpty()) {
                teacherClassRelationMapper.deleteRelationBatchForClassId(form.getSchoolId(), form.getTeacherId(), classIdsToRemove);
            }

            // 执行批量插入
            if (classIdsToAdd) {
                teacherClassRelationMapper.insertRelationBatchForClassId(form.getSchoolId(), form.getTeacherId(), newClassIds);
            }
        }

        return 1;
    }

    @Override
    public List<TeacherClassInfoVo> queryTeacherBindClassList(RelationListDto form) {
        return teacherClassRelationMapper.selectTeacherClass(form.getSchoolId(), form.getTeacherId(), form.getClassId());
    }

    @Override
    public String bindClassTeacherMain(BindClassTeacherMain form) {
        // step1：检测该学校下面是否存在对应的班级和教师
        Clazz clazz = clazzMapper.selectClazzByIdAndSchoolId(form.getClassId(), form.getSchoolId());
        if (clazz == null) {
            throw new ServiceException("当前学校不存在该班级");
        }

        // step2：判断是否是要绑定
        String teacherMain = form.getTeacherMain();
        String ans = "";
        if (DictConstants.SYS_DICT_YES.equals(teacherMain)) {
            if (form.getTeacherId() == null) {
                throw new ServiceException("教师不能为空");
            }
            Teacher teacher = teacherMapper.selectTeacherByIdAndSchoolId(form.getTeacherId(), form.getSchoolId());
            if (teacher == null) {
                throw new ServiceException("当前学校不存在该教师");
            }
            // step3：校验当前要绑定的教师是否已经绑定了其他班级的班主任
            TeacherClassRelation teacherMainRelation = teacherClassRelationMapper.selectTeacherMain(form.getSchoolId(), form.getTeacherId(), null);
            if (teacherMainRelation != null) {
                throw new ServiceException("当前教师已经绑定有其他班的班主任，无法再次绑定");
            }
            // step3：解绑和更新绑定的操作
            // 解绑
            teacherClassRelationMapper.updateTeacherMainBindRelation(form.getSchoolId(), form.getClassId(), null, form.getTeacherMain(), DictConstants.SYS_DICT_NO);
            // 更新绑定
            teacherClassRelationMapper.updateTeacherMainBindRelation(form.getSchoolId(), form.getClassId(), form.getTeacherId(), null, DictConstants.SYS_DICT_YES);
            ans = "绑定成功！";
        } else if (DictConstants.SYS_DICT_NO.equals(teacherMain)) { // step3：解绑操作
            // 解绑
            teacherClassRelationMapper.updateTeacherMainBindRelation(form.getSchoolId(), form.getClassId(), null, DictConstants.SYS_DICT_YES, DictConstants.SYS_DICT_NO);
            ans = "解绑成功";
        }

        return ans;
    }

    @Override
    public List<Long> listTeacherBindClass(Long teacherId) {
        return teacherClassRelationMapper.selectTeacherBindClass(teacherId);
    }
}
