package com.ruoyi.web.controller.education;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.education.domain.EduCourseClass;
import com.ruoyi.education.service.IEduCourseClassService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;

/**
 * 开课计划Controller
 * 
 * @author ruoyi
 * @date 2024-09-26
 */
@RestController
@RequestMapping("/education/courseClass")
public class EduCourseClassController extends BaseController
{
    @Autowired
    private IEduCourseClassService eduCourseClassService;

    /**
     * 查询开课计划列表
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:list')")
    @GetMapping("/list")
    public TableDataInfo list(EduCourseClass eduCourseClass)
    {
        startPage();
        List<EduCourseClass> list = eduCourseClassService.selectEduCourseClassList(eduCourseClass);
        return getDataTable(list);
    }

    /**
     * 导出开课计划列表
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:export')")
    @Log(title = "开课计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EduCourseClass eduCourseClass)
    {
        List<EduCourseClass> list = eduCourseClassService.selectEduCourseClassList(eduCourseClass);
        ExcelUtil<EduCourseClass> util = new ExcelUtil<EduCourseClass>(EduCourseClass.class);
        util.exportExcel(response, list, "开课计划数据");
    }

    /**
     * 获取开课计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping(value = "/{classId}")
    public AjaxResult getInfo(@PathVariable("classId") Long classId)
    {
        return success(eduCourseClassService.selectEduCourseClassByClassId(classId));
    }

    /**
     * 新增开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:add')")
    @Log(title = "开课计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EduCourseClass eduCourseClass)
    {
        if ("NOT_UNIQUE".equals(eduCourseClassService.checkClassCodeUnique(eduCourseClass)))
        {
            return error("新增开课计划失败，班级编号已存在");
        }
        
        String capacityResult = eduCourseClassService.checkCapacityValid(eduCourseClass);
        if (!"VALID".equals(capacityResult))
        {
            return getCapacityErrorMessage(capacityResult);
        }
        
        String classroomConflictResult = eduCourseClassService.checkClassroomConflict(eduCourseClass);
        if ("CONFLICT".equals(classroomConflictResult))
        {
            return error("新增开课计划失败，教室时间冲突");
        }
        
        String teacherConflictResult = eduCourseClassService.checkTeacherConflict(eduCourseClass);
        if ("CONFLICT".equals(teacherConflictResult))
        {
            return error("新增开课计划失败，教师时间冲突");
        }
        
        eduCourseClass.setCreateBy(getUsername());
        return toAjax(eduCourseClassService.insertEduCourseClass(eduCourseClass));
    }

    /**
     * 修改开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:edit')")
    @Log(title = "开课计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EduCourseClass eduCourseClass)
    {
        if ("NOT_UNIQUE".equals(eduCourseClassService.checkClassCodeUnique(eduCourseClass)))
        {
            return error("修改开课计划失败，班级编号已存在");
        }
        
        String capacityResult = eduCourseClassService.checkCapacityValid(eduCourseClass);
        if (!"VALID".equals(capacityResult))
        {
            return getCapacityErrorMessage(capacityResult);
        }
        
        String classroomConflictResult = eduCourseClassService.checkClassroomConflict(eduCourseClass);
        if ("CONFLICT".equals(classroomConflictResult))
        {
            return error("修改开课计划失败，教室时间冲突");
        }
        
        String teacherConflictResult = eduCourseClassService.checkTeacherConflict(eduCourseClass);
        if ("CONFLICT".equals(teacherConflictResult))
        {
            return error("修改开课计划失败，教师时间冲突");
        }
        
        eduCourseClass.setUpdateBy(getUsername());
        return toAjax(eduCourseClassService.updateEduCourseClass(eduCourseClass));
    }

    /**
     * 删除开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:remove')")
    @Log(title = "开课计划", businessType = BusinessType.DELETE)
	@DeleteMapping("/{classIds}")
    public AjaxResult remove(@PathVariable Long[] classIds)
    {
        return toAjax(eduCourseClassService.deleteEduCourseClassByClassIds(classIds));
    }

    /**
     * 发布开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:publish')")
    @Log(title = "发布开课计划", businessType = BusinessType.UPDATE)
    @PutMapping("/publish/{classId}")
    public AjaxResult publishCourseClass(@PathVariable Long classId)
    {
        EduCourseClass courseClass = eduCourseClassService.selectEduCourseClassByClassId(classId);
        if (StringUtils.isNull(courseClass))
        {
            return error("开课计划不存在");
        }
        
        if (!"0".equals(courseClass.getStatus()))
        {
            return error("只有待发布状态的开课计划才能发布");
        }
        
        return toAjax(eduCourseClassService.publishCourseClass(classId));
    }

    /**
     * 批量发布开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:publish')")
    @Log(title = "批量发布开课计划", businessType = BusinessType.UPDATE)
    @PutMapping("/batchPublish")
    public AjaxResult batchPublishCourseClass(@RequestBody Long[] classIds)
    {
        return toAjax(eduCourseClassService.batchPublishCourseClass(classIds));
    }

    /**
     * 停止选课
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:edit')")
    @Log(title = "停止选课", businessType = BusinessType.UPDATE)
    @PutMapping("/stopEnrollment/{classId}")
    public AjaxResult stopEnrollment(@PathVariable Long classId)
    {
        EduCourseClass courseClass = eduCourseClassService.selectEduCourseClassByClassId(classId);
        if (StringUtils.isNull(courseClass))
        {
            return error("开课计划不存在");
        }
        
        if (!"1".equals(courseClass.getStatus()))
        {
            return error("只有可选课状态的开课计划才能停止选课");
        }
        
        return toAjax(eduCourseClassService.stopEnrollment(classId));
    }

    /**
     * 结课
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:edit')")
    @Log(title = "结课", businessType = BusinessType.UPDATE)
    @PutMapping("/finish/{classId}")
    public AjaxResult finishCourse(@PathVariable Long classId)
    {
        EduCourseClass courseClass = eduCourseClassService.selectEduCourseClassByClassId(classId);
        if (StringUtils.isNull(courseClass))
        {
            return error("开课计划不存在");
        }
        
        if (!"1".equals(courseClass.getStatus()) && !"2".equals(courseClass.getStatus()))
        {
            return error("只有可选课或已满额状态的开课计划才能结课");
        }
        
        return toAjax(eduCourseClassService.finishCourse(classId));
    }

    /**
     * 调整容量
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:capacity')")
    @Log(title = "调整容量", businessType = BusinessType.UPDATE)
    @PutMapping("/adjustCapacity/{classId}/{newCapacity}")
    public AjaxResult adjustCapacity(@PathVariable Long classId, @PathVariable Integer newCapacity)
    {
        if (newCapacity == null || newCapacity <= 0)
        {
            return error("容量必须大于0");
        }
        
        int result = eduCourseClassService.adjustCapacity(classId, newCapacity);
        if (result == -1)
        {
            return error("新容量不能小于已选课人数");
        }
        
        return toAjax(result);
    }

    /**
     * 获取指定学期的开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/semester/{semesterId}")
    public AjaxResult getBySemester(@PathVariable Long semesterId)
    {
        return success(eduCourseClassService.selectCourseClassBySemester(semesterId));
    }

    /**
     * 获取指定教师的开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/teacher/{teacherId}")
    public AjaxResult getByTeacher(@PathVariable Long teacherId)
    {
        return success(eduCourseClassService.selectCourseClassByTeacher(teacherId));
    }

    /**
     * 获取可选课的开课计划
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/enrollable")
    public AjaxResult getEnrollableCourseClasses()
    {
        return success(eduCourseClassService.selectEnrollableCourseClasses());
    }

    /**
     * 获取开课计划统计信息
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/statistics/{semesterId}")
    public AjaxResult getStatistics(@PathVariable Long semesterId)
    {
        return success(eduCourseClassService.getCourseClassStatistics(semesterId));
    }

    /**
     * 获取课程列表用于下拉选择
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/courseOptions")
    public AjaxResult getCourseOptions()
    {
        return success(eduCourseClassService.getCourseOptions());
    }

    /**
     * 获取教师列表用于下拉选择
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/teacherOptions")
    public AjaxResult getTeacherOptions()
    {
        return success(eduCourseClassService.getTeacherOptions());
    }

    /**
     * 获取教室列表用于下拉选择
     */
    @PreAuthorize("@ss.hasPermi('education:courseClass:query')")
    @GetMapping("/classroomOptions")
    public AjaxResult getClassroomOptions()
    {
        return success(eduCourseClassService.getClassroomOptions());
    }

    /**
     * 获取容量校验错误信息
     */
    private AjaxResult getCapacityErrorMessage(String capacityResult)
    {
        switch (capacityResult)
        {
            case "INVALID_CAPACITY":
                return error("容量必须大于0");
            case "ENROLL_LIMIT_EXCEED_CAPACITY":
                return error("选课人数上限不能超过容量");
            case "ENROLLED_EXCEED_LIMIT":
                return error("已选课人数超过了容量限制");
            default:
                return error("容量设置无效");
        }
    }
}