package com.ruoyi.education.service.impl;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.education.mapper.EduCourseClassMapper;
import com.ruoyi.education.domain.EduCourseClass;
import com.ruoyi.education.service.IEduCourseClassService;

/**
 * 开课计划Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-26
 */
@Service
public class EduCourseClassServiceImpl implements IEduCourseClassService 
{
    @Autowired
    private EduCourseClassMapper eduCourseClassMapper;

    /**
     * 查询开课计划
     * 
     * @param classId 开课计划主键
     * @return 开课计划
     */
    @Override
    public EduCourseClass selectEduCourseClassByClassId(Long classId)
    {
        return eduCourseClassMapper.selectEduCourseClassByClassId(classId);
    }

    /**
     * 查询开课计划列表
     * 
     * @param eduCourseClass 开课计划
     * @return 开课计划
     */
    @Override
    public List<EduCourseClass> selectEduCourseClassList(EduCourseClass eduCourseClass)
    {
        return eduCourseClassMapper.selectEduCourseClassList(eduCourseClass);
    }

    /**
     * 新增开课计划
     * 
     * @param eduCourseClass 开课计划
     * @return 结果
     */
    @Override
    public int insertEduCourseClass(EduCourseClass eduCourseClass)
    {
        if (eduCourseClass.getEnrolledCount() == null)
        {
            eduCourseClass.setEnrolledCount(0);
        }
        if (eduCourseClass.getStatus() == null)
        {
            eduCourseClass.setStatus("0");
        }
        eduCourseClass.setCreateTime(DateUtils.getNowDate());
        return eduCourseClassMapper.insertEduCourseClass(eduCourseClass);
    }

    /**
     * 修改开课计划
     * 
     * @param eduCourseClass 开课计划
     * @return 结果
     */
    @Override
    public int updateEduCourseClass(EduCourseClass eduCourseClass)
    {
        eduCourseClass.setUpdateTime(DateUtils.getNowDate());
        return eduCourseClassMapper.updateEduCourseClass(eduCourseClass);
    }

    /**
     * 批量删除开课计划
     * 
     * @param classIds 需要删除的开课计划主键
     * @return 结果
     */
    @Override
    public int deleteEduCourseClassByClassIds(Long[] classIds)
    {
        return eduCourseClassMapper.deleteEduCourseClassByClassIds(classIds);
    }

    /**
     * 删除开课计划信息
     * 
     * @param classId 开课计划主键
     * @return 结果
     */
    @Override
    public int deleteEduCourseClassByClassId(Long classId)
    {
        return eduCourseClassMapper.deleteEduCourseClassByClassId(classId);
    }

    /**
     * 根据班级编号查询开课计划
     * 
     * @param classCode 班级编号
     * @return 开课计划
     */
    @Override
    public EduCourseClass selectEduCourseClassByClassCode(String classCode)
    {
        return eduCourseClassMapper.selectEduCourseClassByClassCode(classCode);
    }

    /**
     * 查询指定学期的开课计划
     * 
     * @param semesterId 学期ID
     * @return 开课计划集合
     */
    @Override
    public List<EduCourseClass> selectCourseClassBySemester(Long semesterId)
    {
        return eduCourseClassMapper.selectCourseClassBySemester(semesterId);
    }

    /**
     * 查询指定教师的开课计划
     * 
     * @param teacherId 教师ID
     * @return 开课计划集合
     */
    @Override
    public List<EduCourseClass> selectCourseClassByTeacher(Long teacherId)
    {
        return eduCourseClassMapper.selectCourseClassByTeacher(teacherId);
    }

    /**
     * 查询可选课的开课计划
     * 
     * @return 开课计划集合
     */
    @Override
    public List<EduCourseClass> selectEnrollableCourseClasses()
    {
        return eduCourseClassMapper.selectEnrollableCourseClasses();
    }

    /**
     * 发布开课计划（将状态改为可选课）
     * 
     * @param classId 开课计划ID
     * @return 结果
     */
    @Override
    public int publishCourseClass(Long classId)
    {
        EduCourseClass courseClass = new EduCourseClass();
        courseClass.setClassId(classId);
        courseClass.setStatus("1");
        courseClass.setUpdateBy(SecurityUtils.getUsername());
        courseClass.setUpdateTime(DateUtils.getNowDate());
        return eduCourseClassMapper.updateEduCourseClass(courseClass);
    }

    /**
     * 批量发布开课计划
     * 
     * @param classIds 开课计划ID数组
     * @return 结果
     */
    @Override
    public int batchPublishCourseClass(Long[] classIds)
    {
        return eduCourseClassMapper.batchUpdateStatus(classIds, "1");
    }

    /**
     * 停止选课（将状态改为已满额）
     * 
     * @param classId 开课计划ID
     * @return 结果
     */
    @Override
    public int stopEnrollment(Long classId)
    {
        EduCourseClass courseClass = new EduCourseClass();
        courseClass.setClassId(classId);
        courseClass.setStatus("2");
        courseClass.setUpdateBy(SecurityUtils.getUsername());
        courseClass.setUpdateTime(DateUtils.getNowDate());
        return eduCourseClassMapper.updateEduCourseClass(courseClass);
    }

    /**
     * 结课（将状态改为已结课）
     * 
     * @param classId 开课计划ID
     * @return 结果
     */
    @Override
    public int finishCourse(Long classId)
    {
        EduCourseClass courseClass = new EduCourseClass();
        courseClass.setClassId(classId);
        courseClass.setStatus("3");
        courseClass.setUpdateBy(SecurityUtils.getUsername());
        courseClass.setUpdateTime(DateUtils.getNowDate());
        return eduCourseClassMapper.updateEduCourseClass(courseClass);
    }

    /**
     * 校验班级编号是否唯一
     * 
     * @param eduCourseClass 开课计划
     * @return 结果
     */
    @Override
    public String checkClassCodeUnique(EduCourseClass eduCourseClass)
    {
        Long classId = StringUtils.isNull(eduCourseClass.getClassId()) ? -1L : eduCourseClass.getClassId();
        EduCourseClass info = eduCourseClassMapper.selectEduCourseClassByClassCode(eduCourseClass.getClassCode());
        if (StringUtils.isNotNull(info) && info.getClassId().longValue() != classId.longValue())
        {
            return "NOT_UNIQUE";
        }
        return "UNIQUE";
    }

    /**
     * 校验容量设置是否合理
     * 
     * @param eduCourseClass 开课计划
     * @return 结果
     */
    @Override
    public String checkCapacityValid(EduCourseClass eduCourseClass)
    {
        if (eduCourseClass.getCapacity() == null || eduCourseClass.getCapacity() <= 0)
        {
            return "INVALID_CAPACITY";
        }
        
        if (eduCourseClass.getEnrollLimit() != null && eduCourseClass.getEnrollLimit() > 0)
        {
            if (eduCourseClass.getEnrollLimit() > eduCourseClass.getCapacity())
            {
                return "ENROLL_LIMIT_EXCEED_CAPACITY";
            }
        }
        
        if (eduCourseClass.getEnrolledCount() != null && eduCourseClass.getEnrolledCount() > 0)
        {
            Integer limit = eduCourseClass.getEnrollLimit() != null && eduCourseClass.getEnrollLimit() > 0 
                ? eduCourseClass.getEnrollLimit() : eduCourseClass.getCapacity();
            if (eduCourseClass.getEnrolledCount() > limit)
            {
                return "ENROLLED_EXCEED_LIMIT";
            }
        }
        
        return "VALID";
    }

    /**
     * 校验教室时间冲突
     * 
     * @param eduCourseClass 开课计划
     * @return 结果
     */
    @Override
    public String checkClassroomConflict(EduCourseClass eduCourseClass)
    {
        if (eduCourseClass.getClassroomId() == null || StringUtils.isEmpty(eduCourseClass.getWeekday()) 
            || StringUtils.isEmpty(eduCourseClass.getTimeSlot()) || eduCourseClass.getSemesterId() == null)
        {
            return "NO_CONFLICT";
        }
        
        int conflictCount = eduCourseClassMapper.checkClassroomConflict(
            eduCourseClass.getClassroomId(),
            eduCourseClass.getWeekday(),
            eduCourseClass.getTimeSlot(),
            eduCourseClass.getSemesterId(),
            eduCourseClass.getClassId()
        );
        
        return conflictCount > 0 ? "CONFLICT" : "NO_CONFLICT";
    }

    /**
     * 校验教师时间冲突
     * 
     * @param eduCourseClass 开课计划
     * @return 结果
     */
    @Override
    public String checkTeacherConflict(EduCourseClass eduCourseClass)
    {
        if (eduCourseClass.getTeacherId() == null || StringUtils.isEmpty(eduCourseClass.getWeekday()) 
            || StringUtils.isEmpty(eduCourseClass.getTimeSlot()) || eduCourseClass.getSemesterId() == null)
        {
            return "NO_CONFLICT";
        }
        
        int conflictCount = eduCourseClassMapper.checkTeacherConflict(
            eduCourseClass.getTeacherId(),
            eduCourseClass.getWeekday(),
            eduCourseClass.getTimeSlot(),
            eduCourseClass.getSemesterId(),
            eduCourseClass.getClassId()
        );
        
        return conflictCount > 0 ? "CONFLICT" : "NO_CONFLICT";
    }

    /**
     * 更新已选课人数
     * 
     * @param classId 班级ID
     * @param enrolledCount 已选人数
     * @return 结果
     */
    @Override
    public int updateEnrolledCount(Long classId, Integer enrolledCount)
    {
        return eduCourseClassMapper.updateEnrolledCount(classId, enrolledCount);
    }

    /**
     * 调整容量
     * 
     * @param classId 班级ID
     * @param newCapacity 新容量
     * @return 结果
     */
    @Override
    public int adjustCapacity(Long classId, Integer newCapacity)
    {
        EduCourseClass courseClass = eduCourseClassMapper.selectEduCourseClassByClassId(classId);
        if (StringUtils.isNull(courseClass))
        {
            return 0;
        }
        
        if (newCapacity < courseClass.getEnrolledCount())
        {
            return -1;
        }
        
        EduCourseClass updateClass = new EduCourseClass();
        updateClass.setClassId(classId);
        updateClass.setCapacity(newCapacity);
        updateClass.setUpdateBy(SecurityUtils.getUsername());
        updateClass.setUpdateTime(DateUtils.getNowDate());
        
        return eduCourseClassMapper.updateEduCourseClass(updateClass);
    }

    /**
     * 获取开课计划统计信息
     * 
     * @param semesterId 学期ID
     * @return 统计结果
     */
    @Override
    public Object getCourseClassStatistics(Long semesterId)
    {
        EduCourseClass queryParam = new EduCourseClass();
        queryParam.setSemesterId(semesterId);
        List<EduCourseClass> classList = eduCourseClassMapper.selectEduCourseClassList(queryParam);
        
        Map<String, Object> statistics = new HashMap<>();
        int totalClasses = classList.size();
        int publishedClasses = 0;
        int fullClasses = 0;
        int finishedClasses = 0;
        int totalCapacity = 0;
        int totalEnrolled = 0;
        
        for (EduCourseClass courseClass : classList)
        {
            if ("1".equals(courseClass.getStatus()) || "2".equals(courseClass.getStatus()))
            {
                publishedClasses++;
            }
            if ("2".equals(courseClass.getStatus()))
            {
                fullClasses++;
            }
            if ("3".equals(courseClass.getStatus()))
            {
                finishedClasses++;
            }
            
            totalCapacity += courseClass.getCapacity() != null ? courseClass.getCapacity() : 0;
            totalEnrolled += courseClass.getEnrolledCount() != null ? courseClass.getEnrolledCount() : 0;
        }
        
        statistics.put("totalClasses", totalClasses);
        statistics.put("publishedClasses", publishedClasses);
        statistics.put("fullClasses", fullClasses);
        statistics.put("finishedClasses", finishedClasses);
        statistics.put("totalCapacity", totalCapacity);
        statistics.put("totalEnrolled", totalEnrolled);
        statistics.put("enrollmentRate", totalCapacity > 0 ? (double)totalEnrolled / totalCapacity * 100 : 0);
        
        return statistics;
    }

    /**
     * 获取课程列表用于下拉选择
     * 
     * @return 课程选项集合
     */
    @Override
    public List<Object> getCourseOptions()
    {
        return eduCourseClassMapper.getCourseOptions();
    }

    /**
     * 获取教师列表用于下拉选择
     * 
     * @return 教师选项集合
     */
    @Override
    public List<Object> getTeacherOptions()
    {
        return eduCourseClassMapper.getTeacherOptions();
    }

    /**
     * 获取教室列表用于下拉选择
     * 
     * @return 教室选项集合
     */
    @Override
    public List<Object> getClassroomOptions()
    {
        return eduCourseClassMapper.getClassroomOptions();
    }
}