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.common.TeacherTimetableResponse;
import com.ruoyi.course.domain.Teacher;
import com.ruoyi.course.domain.vo.TeacherQueryVO;
import com.ruoyi.course.service.ITeacherService;
import com.ruoyi.course.service.impl.TeacherScheduleService;
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/teacher")
@Tag(name = "教师管理", description = "教师相关的CRUD操作和课表管理")
public class TeacherController extends BaseController {

    @Autowired
    private ITeacherService teacherService;

    @Operation(summary = "新增教师", description = "创建一个新的教师")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "新增成功"),
            @ApiResponse(responseCode = "500", description = "新增失败")
    })
    @PostMapping("/add")
    public R<Boolean> addTeacher(@RequestBody Teacher teacher) {
        boolean success = teacherService.save(teacher);
        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> deleteTeacher(
            @Parameter(description = "教师ID", required = true, example = "1")
            @PathVariable Long id) {
        boolean success = teacherService.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 = teacherService.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> updateTeacher(@RequestBody Teacher teacher) {
        if (teacher.getId() == null) {
            return R.paramError("ID不能为空");
        }

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

        boolean success = teacherService.updateById(teacher);
        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<Teacher> getTeacherById(
            @Parameter(description = "教师ID", required = true, example = "1")
            @PathVariable Long id) {
        Teacher teacher = teacherService.getById(id);
        if (teacher == null) {
            return R.notFound("教师不存在");
        }
        return R.ok(teacher, "查询成功");
    }

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

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

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

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

        if (StringUtils.hasText(queryVO.getTeacherName())) {
            wrapper.like(Teacher::getTeacherName, queryVO.getTeacherName());
        }

        if (StringUtils.hasText(queryVO.getTeacherType())) {
            wrapper.eq(Teacher::getTeacherType, queryVO.getTeacherType());
        }

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

        if (StringUtils.hasText(queryVO.getTitle())) {
            wrapper.eq(Teacher::getTitle, queryVO.getTitle());
        }

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

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

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

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

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

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

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

        IPage<Teacher> result = teacherService.page(page);

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



    @Operation(summary = "根据教师类型和状态查询", description = "根据教师类型和状态组合查询教师列表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功")
    })
    @GetMapping("/listByTypeAndStatus")
    public R<List<Teacher>> listByTypeAndStatus(
            @Parameter(description = "教师类型", required = true, example = "专职教师")
            @RequestParam String teacherType,
            @Parameter(description = "状态", required = true, example = "1")
            @RequestParam Integer status) {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Teacher::getTeacherType, teacherType);
        wrapper.eq(Teacher::getStatus, status);
        wrapper.orderByDesc(Teacher::getCreateTime);

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

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

    @Autowired
    private TeacherScheduleService teacherScheduleService;

    @Operation(summary = "获取教师课表", description = "获取指定教师在指定学期的课表")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "404", description = "教师不存在")
    })
    @GetMapping("/{teacherId}/timetable")
    public R<TeacherTimetableResponse> getTeacherTimetable(
            @Parameter(description = "教师ID", required = true, example = "1")
            @PathVariable Long teacherId,
            @Parameter(description = "学期", required = true, example = "2025-2026-1")
            @RequestParam String semester) {
        TeacherTimetableResponse timetable =
                teacherScheduleService.getTeacherTimetable(teacherId, semester);
        return R.ok(timetable, "查询成功");
    }
}