package com.ruoyi.dz.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.dz.mapper.DzTeacherClassMapper;
import com.ruoyi.dz.mapper.DzClassesMapper;
import com.ruoyi.dz.domain.DzTeacherClass;
import com.ruoyi.dz.domain.DzSchool;
import com.ruoyi.dz.domain.DzClasses;
import com.ruoyi.dz.service.IDzTeacherClassService;
import com.ruoyi.dz.service.IDzSchoolService;
import com.ruoyi.common.enums.BoolValues;
import org.apache.commons.collections.CollectionUtils;

/**
 * 教师班级关系Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-12
 */
@Service
public class DzTeacherClassServiceImpl implements IDzTeacherClassService
{
    @Autowired
    private DzTeacherClassMapper dzTeacherClassMapper;
    @Autowired
    private IDzSchoolService dzSchoolService;
    @Autowired
    private DzClassesMapper dzClassesMapper;

    /**
     * 查询教师班级关系
     *
     * @param id 教师班级关系主键
     * @return 教师班级关系
     */
    @Override
    public DzTeacherClass selectDzTeacherClassById(String id)
    {
        return dzTeacherClassMapper.selectDzTeacherClassById(id);
    }

    /**
     * 查询教师班级关系列表
     *
     * @param dzTeacherClass 教师班级关系
     * @return 教师班级关系
     */
    @Override
    public List<DzTeacherClass> selectDzTeacherClassList(DzTeacherClass dzTeacherClass)
    {
        return dzTeacherClassMapper.selectDzTeacherClassList(dzTeacherClass);
    }

    @Override
    public List<DzTeacherClass> selectDzTeacherClassByTeacherIds(Collection<Long> teacherIds)
    {
        if (teacherIds == null || teacherIds.isEmpty()) {
            return new ArrayList<>();
        }
        return dzTeacherClassMapper.selectDzTeacherClassByTeacherIds(teacherIds);
    }

    /**
     * 新增教师班级关系
     *
     * @param dzTeacherClass 教师班级关系
     * @return 结果
     */
    @Override
    public int insertDzTeacherClass(DzTeacherClass dzTeacherClass)
    {
        return dzTeacherClassMapper.insertDzTeacherClass(dzTeacherClass);
    }

    @Override
    public int insertBatch(List<DzTeacherClass> list) {
        return dzTeacherClassMapper.insertBatch(list);
    }

    /**
     * 修改教师班级关系
     *
     * @param dzTeacherClass 教师班级关系
     * @return 结果
     */
    @Override
    public int updateDzTeacherClass(DzTeacherClass dzTeacherClass)
    {
        return dzTeacherClassMapper.updateDzTeacherClass(dzTeacherClass);
    }

    /**
     * 批量删除教师班级关系
     *
     * @param ids 需要删除的教师班级关系主键
     * @return 结果
     */
    @Override
    public int deleteDzTeacherClassByIds(String[] ids)
    {
        return dzTeacherClassMapper.deleteDzTeacherClassByIds(ids);
    }

    /**
     * 删除教师班级关系信息
     *
     * @param id 教师班级关系主键
     * @return 结果
     */
    @Override
    public int deleteDzTeacherClassById(String id)
    {
        return dzTeacherClassMapper.deleteDzTeacherClassById(id);
    }

    /**
     * 批量关联教师班级关系
     *
     * @param dzTeacherClass 教师班级关系（包含teacherId和classIds数组）
     */
    @Override
    public void batchBindTeacherClass(DzTeacherClass dzTeacherClass)
    {
        List<Long> insertClassIds = Arrays.stream(dzTeacherClass.getClassIds()).collect(Collectors.toList());
        //区分班级是学校还是校区对应的班级
        List<DzSchool> dzSchoolList = dzSchoolService.getDzSchoolByClassIds(insertClassIds);
        //关联校区
        Boolean isBindSchool = false;
        if (CollectionUtils.isNotEmpty(dzSchoolList) &&
                null == dzSchoolList.get(0).getDeptId() || dzSchoolList.get(0).getDeptId() <= 0) {
            isBindSchool = true;
        }

        DzTeacherClass cond = new DzTeacherClass().setTeacherId(dzTeacherClass.getTeacherId());
        List<DzTeacherClass> alreadyList = dzTeacherClassMapper.selectDzTeacherClassList(cond);
        List<Long> dbClassIds = alreadyList.stream().map(DzTeacherClass::getClassId).collect(Collectors.toList());
        //需要将dbClassIds中与isBindSchool不相同的剔除
        List<DzSchool> dzSchoolDbList = dzSchoolService.getDzSchoolByClassIds(dbClassIds);
        List<Long> schoolProcessList = new ArrayList<>();
        for (DzSchool dzSchool : dzSchoolDbList) {
            if (isBindSchool) {
                if (null == dzSchool.getDeptId() || dzSchool.getDeptId() <= 0) {
                    schoolProcessList.add(dzSchool.getId());
                }
            } else {
                if (null != dzSchool.getDeptId() && dzSchool.getDeptId() > 0) {
                    schoolProcessList.add(dzSchool.getId());
                }
            }
        }

        // 构建classId到schoolId的映射：通过查询classes表获取每个classId对应的schoolId
        final Map<Long, Long> classIdToSchoolIdMap;
        if (CollectionUtils.isNotEmpty(dbClassIds)) {
            List<DzClasses> classesList = dzClassesMapper.selectClassesByIds(dbClassIds);
            if (CollectionUtils.isNotEmpty(classesList)) {
                classIdToSchoolIdMap = classesList.stream()
                        .filter(clazz -> clazz.getClassId() != null && clazz.getSchoolId() != null)
                        .collect(Collectors.toMap(
                                DzClasses::getClassId,
                                DzClasses::getSchoolId,
                                (existing, replacement) -> existing
                        ));
            } else {
                classIdToSchoolIdMap = new HashMap<>();
            }
        } else {
            classIdToSchoolIdMap = new HashMap<>();
        }

        // 如果schoolProcessList为空就过滤，否则将schoolId不在schoolProcessList内的过滤
        if (CollectionUtils.isNotEmpty(schoolProcessList)) {
            alreadyList = alreadyList.stream()
                    .filter(item -> {
                        Long schoolId = classIdToSchoolIdMap.get(item.getClassId());
                        return schoolId != null && schoolProcessList.contains(schoolId);
                    })
                    .collect(Collectors.toList());
        } else {
            // 如果schoolProcessList为空，过滤掉所有记录
            alreadyList = new ArrayList<>();
        }

        final List<Long> finalDbClassIds = alreadyList.stream().map(DzTeacherClass::getClassId).collect(Collectors.toList());

        // 2. 找出需要删除的班级ID（存在于finalDbClassIds但不存在于insertClassIds）
        List<Long> deleteClassIds = finalDbClassIds.stream()
                .filter(dbId -> !insertClassIds.contains(dbId))
                .collect(Collectors.toList());

        // 3. 找出需要新增的班级ID（存在于insertClassIds但不存在于finalDbClassIds）
        List<Long> newClassIds = insertClassIds.stream()
                .filter(insertId -> !finalDbClassIds.contains(insertId))
                .collect(Collectors.toList());

        // 4. 执行删除操作
        if (!deleteClassIds.isEmpty()) {
            //alreadyList转换为Map<Long,Long>，key为classesId，value为id（删除时需要用id）
            Map<Long, Long> map = alreadyList.stream().collect(Collectors.toMap(DzTeacherClass::getClassId, DzTeacherClass::getId, (existing, replacement) -> existing));
            Long[] deleteIds = deleteClassIds.stream()
                    .map(classId -> map.get(classId))  // 通过classId获取对应的id
                    .filter(Objects::nonNull)          // 过滤掉null值
                    .toArray(Long[]::new);
            if (deleteIds.length > 0) {
                String[] stringDeleteIds = Arrays.stream(deleteIds)
                        .map(id -> String.valueOf(id))  // Long 转 String
                        .toArray(String[]::new);
                dzTeacherClassMapper.deleteDzTeacherClassByIds(stringDeleteIds);
            }
        }

        // 5. 执行新增操作
        Long teacherId = dzTeacherClass.getTeacherId();
        if (!newClassIds.isEmpty()) {
            List<DzTeacherClass> insertList = newClassIds.stream()
                    .map(classId -> {
                        DzTeacherClass insert = new DzTeacherClass();
                        insert.setTeacherId(teacherId);
                        insert.setClassId(classId);
                        insert.setSchoolId(dzTeacherClass.getSchoolId());
                        insert.setStatus(BoolValues.yes.getValue()); // 设置有效状态
                        // 设置结束日期：如果当前日期超过4月1日，则设置为第二年的4月1日，否则设置为当年的4月1日
                        insert.setOutDate(calculateOutDate());
                        return insert;
                    })
                    .collect(Collectors.toList());
            dzTeacherClassMapper.insertBatch(insertList);
        }
    }

    /**
     * 计算结束日期
     * 如果当前日期超过4月1日，则设置为第二年的4月1日，否则设置为当年的4月1日
     * @return 结束日期
     */
    private Date calculateOutDate() {
        Calendar calendar = Calendar.getInstance();
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH) + 1; // Calendar.MONTH 从0开始
        int currentDay = calendar.get(Calendar.DAY_OF_MONTH);

        // 判断当前日期是否超过4月1日
        if (currentMonth > 4 || (currentMonth == 4 && currentDay > 1)) {
            // 超过4月1日，设置为第二年的4月1日
            calendar.set(currentYear + 1, 3, 1); // 月份从0开始，4月是3
        } else {
            // 未超过4月1日，设置为当年的4月1日
            calendar.set(currentYear, 3, 1); // 月份从0开始，4月是3
        }

        // 将时间设置为0点0分0秒
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }
}
