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.Clazz;
import com.ruoyi.course.domain.vo.ClassQueryVO;
import com.ruoyi.course.service.IClazzService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
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/clazz")
@Tag(name = "班级管理", description = "班级相关的CRUD操作")
public class ClazzController extends BaseController {

    @Autowired
    private IClazzService clazzService;

    @Operation(summary = "新增班级", description = "创建一个新的班级")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "新增成功"),
            @ApiResponse(responseCode = "500", description = "新增失败")
    })
    @PostMapping("/add")
    public R<Boolean> addClass(@RequestBody Clazz clazz) {
        boolean success = clazzService.save(clazz);
        return success ? R.ok(true, "新增成功") : R.error("新增失败");
    }

    @Operation(summary = "根据ID删除班级", description = "根据班级ID删除班级信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功"),
            @ApiResponse(responseCode = "404", description = "班级不存在"),
            @ApiResponse(responseCode = "500", description = "删除失败")
    })
    @DeleteMapping("/delete/{id}")
    public R<Boolean> deleteClass(
            @Parameter(description = "班级ID", required = true, example = "1")
            @PathVariable Long id) {
        boolean success = clazzService.removeById(id);
        return success ? R.ok(true, "删除成功") : R.error("删除失败");
    }

    @Operation(summary = "批量删除班级", description = "批量删除多个班级")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "批量删除成功"),
            @ApiResponse(responseCode = "400", description = "参数错误"),
            @ApiResponse(responseCode = "500", description = "批量删除失败")
    })
    @DeleteMapping("/batchDelete")
    public R<Boolean> batchDelete(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return R.paramError("请选择要删除的数据");
        }

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

    @Operation(summary = "修改班级信息", description = "更新班级信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "修改成功"),
            @ApiResponse(responseCode = "400", description = "ID不能为空"),
            @ApiResponse(responseCode = "404", description = "班级不存在"),
            @ApiResponse(responseCode = "500", description = "修改失败")
    })
    @PutMapping("/update")
    public R<Boolean> updateClass(@RequestBody Clazz clazz) {
        if (clazz.getId() == null) {
            return R.paramError("ID不能为空");
        }

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

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

    @Operation(summary = "根据ID查询班级", description = "根据班级ID获取班级详细信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "班级不存在")
    })
    @GetMapping("/get/{id}")
    public R<Clazz> getClassById(
            @Parameter(description = "班级ID", required = true, example = "1")
            @PathVariable Long id) {
        Clazz clazz = clazzService.getById(id);
        if (clazz == null) {
            return R.notFound("班级不存在");
        }
        return R.ok(clazz, "查询成功");
    }

    @Operation(summary = "查询所有班级", description = "获取所有班级列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @GetMapping("/list")
    public TableDataInfo listTeachers() {
        startPage();
        List<Clazz> list = clazzService.list();
        return getDataTable(list);
    }

    @Operation(summary = "分页查询班级列表", description = "根据条件分页查询班级列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @PostMapping("/page")
    public R<IPage<Clazz>> pageClasses(@RequestBody ClassQueryVO queryVO) {
        // 创建分页对象
        Page<Clazz> page = new Page<>(queryVO.getPageNum(), queryVO.getPageSize());

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

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

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

        if (StringUtils.hasText(queryVO.getClassType())) {
            wrapper.eq(Clazz::getClassType, queryVO.getClassType());
        }

        if (queryVO.getHeadTeacherId() != null) {
            wrapper.eq(Clazz::getHeadTeacherId, queryVO.getHeadTeacherId());
        }

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

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

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

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

    @Operation(summary = "简单分页查询（无条件）", description = "无条件分页查询班级列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @GetMapping("/page")
    public R<IPage<Clazz>> simplePage(
            @Parameter(description = "页码", required = false, example = "1")
            @RequestParam(defaultValue = "1") Integer pageNum,

            @Parameter(description = "每页条数", required = false, example = "10")
            @RequestParam(defaultValue = "10") Integer pageSize) {

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

        IPage<Clazz> result = clazzService.page(page);

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







    @Operation(summary = "统计班级数量", description = "统计班级总数或根据状态统计")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @GetMapping("/count")
    public R<Long> countClasses(
            @Parameter(description = "状态", required = false, example = "1")
            @RequestParam(required = false) Integer status) {
        LambdaQueryWrapper<Clazz> wrapper = new LambdaQueryWrapper<>();
        if (status != null) {
            wrapper.eq(Clazz::getStatus, status);
        }
        Long count = clazzService.count(wrapper);
        return R.ok(count, "查询成功");
    }


}