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.Student;
import com.ruoyi.course.domain.vo.StudentQueryVO;
import com.ruoyi.course.service.IStudentService;
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>
 *
 * @author xu
 * @since 2025-12-14
 */
@RestController
@RequestMapping("/course/student")
@Api(tags = "学生管理")
public class StudentController extends BaseController {

    @Autowired
    private IStudentService studentService;

    @ApiOperation("新增学生")
    @PostMapping("/add")
    public R<Boolean> addStudent(@RequestBody Student student) {
        // 设置创建时间
        student.setCreateTime(LocalDateTime.now());

        boolean success = studentService.save(student);
        return success ? R.ok(true, "新增成功") : R.error("新增失败");
    }

    @ApiOperation("根据ID删除学生")
    @DeleteMapping("/delete/{id}")
    public R<Boolean> deleteStudent(@PathVariable Long id) {
        boolean success = studentService.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 = studentService.removeByIds(ids);
        return success ? R.ok(true, "批量删除成功") : R.error("批量删除失败");
    }

    @ApiOperation("修改学生信息")
    @PutMapping("/update")
    public R<Boolean> updateStudent(@RequestBody Student student) {
        if (student.getId() == null) {
            return R.paramError("ID不能为空");
        }

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

    @ApiOperation("根据ID查询学生")
    @GetMapping("/get/{id}")
    public R<Student> getStudentById(@PathVariable Long id) {
        Student student = studentService.getById(id);
        if (student == null) {
            return R.notFound("学生不存在");
        }
        return R.ok(student, "查询成功");
    }

    @ApiOperation("查询所有学生")
    @GetMapping("/list")
    public TableDataInfo listStudents() {
        startPage();
        List<Student> list = studentService.list();
        return getDataTable(list);
    }

    @ApiOperation("分页查询学生列表")
    @PostMapping("/page")
    public R<IPage<Student>> pageStudents(@RequestBody StudentQueryVO queryVO) {
        // 创建分页对象
        Page<Student> page = new Page<>(queryVO.getPageNum(), queryVO.getPageSize());

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

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

        if (StringUtils.hasText(queryVO.getName())) {
            wrapper.like(Student::getName, queryVO.getName());
        }

        if (queryVO.getClassId() != null) {
            wrapper.eq(Student::getClassId, queryVO.getClassId());
        }

        if (StringUtils.hasText(queryVO.getGrade())) {
            wrapper.eq(Student::getGrade, queryVO.getGrade());
        }

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

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

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

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

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

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

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

        IPage<Student> result = studentService.page(page);

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

    @ApiOperation("根据状态查询学生")
    @GetMapping("/listByStatus/{status}")
    public R<List<Student>> listByStatus(@PathVariable Integer status) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStatus, status);
        wrapper.orderByDesc(Student::getCreateTime);

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

    @ApiOperation("根据年级和状态查询")
    @GetMapping("/listByGradeAndStatus")
    public R<List<Student>> listByGradeAndStatus(
            @ApiParam(value = "年级") @RequestParam String grade,
            @ApiParam(value = "状态") @RequestParam Integer status) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getGrade, grade);
        wrapper.eq(Student::getStatus, status);
        wrapper.orderByDesc(Student::getCreateTime);

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

    @ApiOperation("根据班级ID查询学生")
    @GetMapping("/listByClass/{classId}")
    public R<List<Student>> listByClass(@PathVariable Long classId) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getClassId, classId);
        wrapper.orderByDesc(Student::getCreateTime);

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

    @ApiOperation("根据学号查询学生")
    @GetMapping("/getByStudentNo/{studentNo}")
    public R<Student> getByStudentNo(@PathVariable String studentNo) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getStudentNo, studentNo);

        Student student = studentService.getOne(wrapper);
        if (student == null) {
            return R.notFound("学生不存在");
        }
        return R.ok(student, "查询成功");
    }

    @ApiOperation("统计学生数量")
    @GetMapping("/count")
    public R<Long> countStudents(
            @ApiParam(value = "班级ID") @RequestParam(required = false) Long classId,
            @ApiParam(value = "年级") @RequestParam(required = false) String grade,
            @ApiParam(value = "状态") @RequestParam(required = false) Integer status) {

        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        if (classId != null) {
            wrapper.eq(Student::getClassId, classId);
        }
        if (StringUtils.hasText(grade)) {
            wrapper.eq(Student::getGrade, grade);
        }
        if (status != null) {
            wrapper.eq(Student::getStatus, status);
        }

        Long count = studentService.count(wrapper);
        return R.ok(count, "查询成功");
    }

    @ApiOperation("根据多个学号查询学生")
    @PostMapping("/listByStudentNos")
    public R<List<Student>> listByStudentNos(@RequestBody List<String> studentNos) {
        if (studentNos == null || studentNos.isEmpty()) {
            return R.paramError("学号列表不能为空");
        }

        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Student::getStudentNo, studentNos);
        wrapper.orderByDesc(Student::getCreateTime);

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

    @ApiOperation("根据班级ID分页查询学生")
    @GetMapping("/pageByClass/{classId}")
    public R<IPage<Student>> pageByClass(
            @PathVariable Long classId,
            @ApiParam(value = "页码", defaultValue = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,
            @ApiParam(value = "每页条数", defaultValue = "10")
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getClassId, classId);
        wrapper.orderByDesc(Student::getCreateTime);

        IPage<Student> result = studentService.page(page, wrapper);
        return R.ok(result, "查询成功");
    }
}