package com.seer.teach.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.seer.teach.admin.convert.EvalutionConvert;
import com.seer.teach.admin.response.EvaluationRecordResp;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.annotation.LogPrint;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.iot.api.UserDeviceServiceApi;
import com.seer.teach.teacher.api.SubjectServiceApi;
import com.seer.teach.teacher.api.dto.SubjectDTO;
import com.seer.teach.teacher.module.entity.EvaluationTasksEntity;
import com.seer.teach.teacher.service.EvaluationTasksService;
import com.seer.teach.teacher.service.KnowledgePointService;
import com.seer.teach.teacher.service.VersionsService;
import com.seer.teach.user.api.GradeServiceApi;
import com.seer.teach.user.api.dto.GradeDTO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RequestMapping("/evaluation")
@RestController
@Tag(name = "后台-用户测评")
@Validated
@RequiredArgsConstructor
public class EvaluationAdminController {

    private final EvaluationTasksService evaluationTasksService;

    private final UserDeviceServiceApi userDeviceServiceApi;

    private final GradeServiceApi gradeServiceApi;

    private final SubjectServiceApi subjectServiceApi;

    private final VersionsService versionsService;

    private final KnowledgePointService knowledgePointService;

    /**
     * 获取用户测评分页查询记录
     */
    @Operation(summary = "获取用户测评分页查询记录")
    @GetMapping("/{page}/{size}/{deviceId}")
    @LogPrint
    @SaCheckPermission("teacher:admin:evaluation:getEvaluationRecord")
    public ResultBean<PageListBean<EvaluationRecordResp>> getEvaluationRecordByDeviceId(
            @PathVariable("deviceId") @NotNull(message = "设备ID不可为空") Integer deviceId,
            @Parameter(description = "页码") @PathVariable("page") Integer page,
            @Parameter(description = "每页数量") @PathVariable("size") Integer size) {
        Integer userId = userDeviceServiceApi.getUserIdByDeviceId(deviceId);
        IPage<EvaluationTasksEntity> recordsPage = evaluationTasksService.getEvaluationRecordByDeviceId(userId, page, size);
        Map<Integer, GradeDTO> gradeMap = gradeServiceApi.getGradeList().stream().
                collect(Collectors.toMap(GradeDTO::getId, Function.identity()));
        Map<Integer, SubjectDTO> subjectMap = subjectServiceApi.getSubjectlist().stream().
                collect(Collectors.toMap(SubjectDTO::getId, Function.identity()));
        List<Integer> knowIds = recordsPage.getRecords().stream()
                .map(EvaluationTasksEntity::getKnowId)
                .collect(Collectors.toList());
        HashMap<Integer, Integer> subjectIdsByKnowIds = versionsService.getSubjectIdsByKnowIds(knowIds);
        HashMap<Integer, Integer> gradeIdWithKnowId = knowledgePointService.getGradeIdWithKnowId(knowIds);
        // 转换为响应列表
        List<EvaluationRecordResp> respList = recordsPage.getRecords().stream().map(record -> {
            String grade = gradeMap.get(gradeIdWithKnowId.get(record.getKnowId())).getGrade();
            Integer subjectId = subjectIdsByKnowIds.get(record.getKnowId());
            String subject = subjectMap.get(subjectId).getSubject();
            return EvalutionConvert.INSTANCE.convertOne(record.getId(), grade, subject,
                    record.getQuestionCount(), record.getCreateTime());
        }).collect(Collectors.toList());
        //转换为PageListBean
        PageListBean<EvaluationRecordResp> result = PageConverterUtils.convertPageListBean(recordsPage, list -> respList);
        return ResultBean.success(result);
    }
}
