package com.ruoyi.course.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.course.common.R;
import com.ruoyi.course.domain.Course;
import com.ruoyi.course.domain.vo.CourseQueryVO;
import com.ruoyi.course.service.ICourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 课程信息表 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/course/courses")
@Api(tags = "课程管理")
public class CourseController extends BaseController {

    @Autowired
    private ICourseService courseService;

    @ApiOperation("新增课程")
    @PostMapping("/add")
    public R<Boolean> addCourse(@RequestBody Course course) {
        boolean success = courseService.save(course);
        return success ? R.ok(true, "新增成功") : R.error("新增失败");
    }

    @ApiOperation("根据ID删除课程")
    @DeleteMapping("/delete/{id}")
    public R<Boolean> deleteCourse(@PathVariable Long id) {
        boolean success = courseService.removeById(id);
        return success ? R.ok(true, "删除成功") : R.error("删除失败");
    }

    @ApiOperation("批量删除课程")
    @DeleteMapping("/batchDelete")
    public R<Boolean> batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return R.paramError("请选择要删除的数据");
        }

        boolean success = courseService.removeByIds(ids);
        return success ? R.ok(true, "批量删除成功") : R.error("批量删除失败");
    }

    @ApiOperation("修改课程信息")
    @PutMapping("/update")
    public R<Boolean> updateCourse(@RequestBody Course course) {
        if (course.getId() == null) {
            return R.paramError("ID不能为空");
        }

        // 设置更新时间
        course.setUpdateTime(LocalDateTime.now());

        boolean success = courseService.updateById(course);
        return success ? R.ok(true, "修改成功") : R.error("修改失败");
    }

    @ApiOperation("根据ID查询课程")
    @GetMapping("/get/{id}")
    public R<Course> getCourseById(@PathVariable Long id) {
        Course course = courseService.getById(id);
        if (course == null) {
            return R.notFound("课程不存在");
        }
        return R.ok(course, "查询成功");
    }

    @ApiOperation("查询所有课程")
    @GetMapping("/list")
    public TableDataInfo listTeachers() {
        startPage();
        List<Course> list = courseService.list();
        return getDataTable(list);
    }

    @ApiOperation("分页查询课程列表")
    @PostMapping("/page")
    public R<IPage<Course>> pageCourses(@RequestBody CourseQueryVO queryVO) {
        // 创建分页对象
        Page<Course> page = new Page<>(queryVO.getPageNum(), queryVO.getPageSize());

        // 创建查询条件
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();

        // 添加查询条件（非空判断）
        if (StringUtils.hasText(queryVO.getCourseCode())) {
            wrapper.like(Course::getCourseCode, queryVO.getCourseCode());
        }

        if (StringUtils.hasText(queryVO.getCourseName())) {
            wrapper.like(Course::getCourseName, queryVO.getCourseName());
        }

        if (StringUtils.hasText(queryVO.getCourseType())) {
            wrapper.eq(Course::getCourseType, queryVO.getCourseType());
        }

        if (StringUtils.hasText(queryVO.getSubject())) {
            wrapper.eq(Course::getSubject, queryVO.getSubject());
        }

        if (StringUtils.hasText(queryVO.getGradeLevel())) {
            wrapper.eq(Course::getGradeLevel, queryVO.getGradeLevel());
        }

        if (queryVO.getPriority() != null) {
            wrapper.eq(Course::getPriority, queryVO.getPriority());
        }

        if (queryVO.getCrossClass() != null) {
            wrapper.eq(Course::getCrossClass, queryVO.getCrossClass());
        }

        if (queryVO.getStatus() != null) {
            wrapper.eq(Course::getStatus, queryVO.getStatus());
        }

        // 按创建时间倒序
        wrapper.orderByDesc(Course::getCreateTime);

        // 执行分页查询
        IPage<Course> result = courseService.page(page, wrapper);

        return R.ok(result, "查询成功");
    }

    @ApiOperation("简单分页查询（无条件）")
    @GetMapping("/page")
    public R<IPage<Course>> simplePage(
            @ApiParam(value = "页码", defaultValue = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,

            @ApiParam(value = "每页条数", defaultValue = "10")
            @RequestParam(defaultValue = "10") Integer pageSize) {

        Page<Course> page = new Page<>(pageNum, pageSize);

        IPage<Course> result = courseService.page(page);

        return R.ok(result, "查询成功");
    }






    @ApiOperation("统计课程数量")
    @GetMapping("/count")
    public R<Long> countCourses(
            @ApiParam(value = "状态") @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            wrapper.eq(Course::getStatus, status);
        }
        Long count = courseService.count(wrapper);
        return R.ok(count, "查询成功");
    }

    @ApiOperation("根据优先级查询课程")
    @GetMapping("/listByPriority/{priority}")
    public R<List<Course>> listByPriority(
            @PathVariable Integer priority,
            @ApiParam(value = "状态", required = false) @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getPriority, priority);
        
        if (status != null) {
            wrapper.eq(Course::getStatus, status);
        }
        
        wrapper.orderByDesc(Course::getCreateTime);

        List<Course> list = courseService.list(wrapper);
        return R.ok(list, "查询成功");
    }
}