package com.yinlihupo.enlish.service.controller;

import com.yinlihupo.enlish.service.domain.dataobject.ClassDO;
import com.yinlihupo.enlish.service.domain.dataobject.GradeDO;
import com.yinlihupo.enlish.service.model.vo.classs.AddClassReqVO;
import com.yinlihupo.enlish.service.model.vo.classs.DeleteClassReqVO;
import com.yinlihupo.enlish.service.model.vo.classs.FindClassReqVO;
import com.yinlihupo.enlish.service.model.vo.classs.FindClassRspVO;
import com.yinlihupo.enlish.service.service.ClassService;
import com.yinlihupo.framework.biz.operationlog.aspect.ApiOperationLog;
import com.yinlihupo.framework.common.response.PageResponse;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RequestMapping("/class/")
@RestController
public class ClassController {

    @Resource
    private ClassService classService;

    @PostMapping("list")
    @ApiOperationLog(description = "查询班级列表")
    public PageResponse<FindClassRspVO> findClasses(@RequestBody FindClassReqVO findClassReqVO) {
        Integer page = findClassReqVO.getPage();
        Integer pageSize = findClassReqVO.getPageSize();
        int total = classService.getClassCount();

        List<ClassDO> classList = classService.findClassList(page, pageSize);
        Map<Integer, GradeDO> classId2GradeMap = classService.findClassIds2GradeMap(classList.stream().map(ClassDO::getId).toList());
        List<FindClassRspVO> findClassRspVOS = classList.stream().map(classDO -> FindClassRspVO.builder()
                .id(classDO.getId())
                .title(classDO.getTitle())
                .gradeId(classId2GradeMap.get(classDO.getId()) != null ? classId2GradeMap.get(classDO.getId()).getId() : 0)
                .gradeName(classId2GradeMap.get(classDO.getId()) != null ? classId2GradeMap.get(classDO.getId()).getTitle() : "")
                .build()).toList();

        return PageResponse.success(findClassRspVOS, page, total, pageSize);
    }

    @PostMapping("add")
    @ApiOperationLog(description = "添加班级")
    public void addClass(@RequestBody AddClassReqVO addClassReqVO) {
        classService.addClass(addClassReqVO.getTitle(), addClassReqVO.getGradeId());
    }

    @PostMapping("delete")
    @ApiOperationLog(description = "删除班级")
    public void deleteClass(@RequestBody DeleteClassReqVO deleteClassReqVO) {
        classService.deleteClass(deleteClassReqVO.getId());
    }
}
