package com.lesingle.edu.controller.school;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.annotation.Log;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.LogOperationType;
import com.lesingle.edu.common.mapper.StudentMapper;
import com.lesingle.edu.mapper.ParentMapper;
import com.lesingle.edu.mapper.ParentStudentMapper;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.request.StudentCreateRequest;
import com.lesingle.edu.dto.request.StudentUpdateRequest;
import com.lesingle.edu.dto.request.TransferStudentRequest;
import com.lesingle.edu.dto.response.StudentImportTemplateResponse;
import com.lesingle.edu.dto.response.StudentResponse;
import com.lesingle.edu.dto.response.StudentTransferHistoryItemResponse;
import com.lesingle.edu.entity.Student;
import com.lesingle.edu.service.ClassService;
import com.lesingle.edu.service.StudentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Tag(name = "School - Student", description = "Student Management APIs for School")
@RestController
@RequestMapping("/api/v1/school/students")
@RequiredArgsConstructor
public class SchoolStudentController {

    private final StudentService studentService;
    private final ClassService classService;
    private final StudentMapper studentMapper;
    private final ParentMapper parentMapper;
    private final ParentStudentMapper parentStudentMapper;

    @Operation(summary = "Create student")
    @Log(module = LogModule.STUDENT, type = LogOperationType.CREATE, description = "创建学生")
    @PostMapping
    public Result<StudentResponse> createStudent(@Valid @RequestBody StudentCreateRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Student student = studentService.createStudent(tenantId, request);
        StudentResponse vo = studentMapper.toVO(student);
        vo.setClassId(request.getClassId());
        return Result.success(vo);
    }

    @Operation(summary = "Update student")
    @Log(module = LogModule.STUDENT, type = LogOperationType.UPDATE, description = "修改学生")
    @PutMapping("/{id}")
    public Result<StudentResponse> updateStudent(@PathVariable Long id, @RequestBody StudentUpdateRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Student student = studentService.updateStudentWithTenantCheck(id, tenantId, request);
        return Result.success(studentMapper.toVO(student));
    }

    @Operation(summary = "Get student by ID")
    @GetMapping("/{id}")
    public Result<StudentResponse> getStudent(@PathVariable Long id) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Student student = studentService.getStudentByIdWithTenantCheck(id, tenantId);
        StudentResponse vo = studentMapper.toVO(student);
        var clazz = classService.getPrimaryClassByStudentId(id);
        vo.setClassId(clazz != null ? clazz.getId() : null);

        // 设置家长信息（查询主要监护人）
        var parentRelation = parentStudentMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.lesingle.edu.entity.ParentStudent>()
                .eq(com.lesingle.edu.entity.ParentStudent::getStudentId, id)
                .eq(com.lesingle.edu.entity.ParentStudent::getIsPrimary, 1)
                .last("LIMIT 1")
        );
        if (parentRelation != null) {
            var parent = parentMapper.selectById(parentRelation.getParentId());
            vo.setParentName(parent != null ? parent.getName() : null);
            vo.setParentPhone(parent != null ? parent.getPhone() : null);
        }

        return Result.success(vo);
    }

    @Operation(summary = "Get student page")
    @GetMapping
    public Result<PageResult<StudentResponse>> getStudentPage(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) Long classId) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        Page<Student> page = studentService.getStudentPage(tenantId, pageNum, pageSize, keyword, grade, status, classId);
        List<StudentResponse> voList = studentMapper.toVO(page.getRecords());
        for (StudentResponse vo : voList) {
            // 设置班级
            var clazz = classService.getPrimaryClassByStudentId(vo.getId());
            vo.setClassId(clazz != null ? clazz.getId() : null);
            vo.setClassName(clazz != null ? clazz.getName() : null);

            // 设置家长信息（查询主要监护人）
            var parentRelation = parentStudentMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.lesingle.edu.entity.ParentStudent>()
                    .eq(com.lesingle.edu.entity.ParentStudent::getStudentId, vo.getId())
                    .eq(com.lesingle.edu.entity.ParentStudent::getIsPrimary, 1)
                    .last("LIMIT 1")
            );
            if (parentRelation != null) {
                var parent = parentMapper.selectById(parentRelation.getParentId());
                vo.setParentName(parent != null ? parent.getName() : null);
                vo.setParentPhone(parent != null ? parent.getPhone() : null);
            }
        }
        return Result.success(PageResult.of(voList, page.getTotal(), page.getCurrent(), page.getSize()));
    }

    @Operation(summary = "Transfer student to another class")
    @PostMapping("/{id}/transfer")
    public Result<Map<String, String>> transferStudent(
            @PathVariable Long id,
            @Valid @RequestBody TransferStudentRequest request) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        studentService.getStudentByIdWithTenantCheck(id, tenantId);
        classService.assignStudentToClass(id, request.getToClassId(), tenantId);
        return Result.success(Map.of("message", "调班成功"));
    }

    @Operation(summary = "Delete student")
    @Log(module = LogModule.STUDENT, type = LogOperationType.DELETE, description = "删除学生")
    @DeleteMapping("/{id}")
    public Result<Void> deleteStudent(@PathVariable Long id) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        studentService.deleteStudentWithTenantCheck(id, tenantId);
        return Result.success();
    }

    @Operation(summary = "Get student import template")
    @GetMapping("/import/template")
    public Result<StudentImportTemplateResponse> getImportTemplate() {
        return Result.success(new StudentImportTemplateResponse(
                Arrays.asList("姓名", "性别", "出生日期", "班级ID", "家长姓名", "家长电话"),
                Arrays.asList("张小明", "男", "2020-01-15", "1", "张三", "13800138000"),
                Arrays.asList(
                        "姓名为必填项",
                        "性别可选：男/女，默认为男",
                        "出生日期格式：YYYY-MM-DD",
                        "班级ID为必填项，可在班级管理中查看",
                        "家长姓名和家长电话为选填项"
                )
        ));
    }

    @Operation(summary = "Get student class transfer history")
    @GetMapping("/{id}/history")
    public Result<List<StudentTransferHistoryItemResponse>> getStudentClassHistory(@PathVariable Long id) {
        Long tenantId = SecurityUtils.getCurrentTenantId();
        studentService.getStudentByIdWithTenantCheck(id, tenantId);
        List<StudentTransferHistoryItemResponse> history = classService.getStudentClassHistory(id, tenantId);
        return Result.success(history);
    }

}
