package com.seer.teach.common.utils;

import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.exception.CommonException;
import com.seer.teach.common.utils.dto.GradeDTO;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

@Slf4j
public class GradeUtils {

    private static final Map<String, Integer> GRADE_MAP = new TreeMap<>();
    private static final List<GradeDTO> GRADE_LIST = new ArrayList<>();

    static {
        GRADE_MAP.put("一年级", 1);
        GRADE_MAP.put("二年级", 2);
        GRADE_MAP.put("三年级", 3);
        GRADE_MAP.put("四年级", 4);
        GRADE_MAP.put("五年级", 5);
        GRADE_MAP.put("六年级", 6);
        GRADE_MAP.put("七年级", 7);
        GRADE_MAP.put("八年级", 8);
        GRADE_MAP.put("九年级", 9);
        GRADE_MAP.put("高中", 10);

        GRADE_LIST.addAll(GRADE_MAP.entrySet().stream().map(item -> new GradeDTO(item.getValue(), item.getKey()))
                .sorted(Comparator.comparing(GradeDTO::getId))
                .collect(Collectors.toList()));
    }

    /**
     * 获取年级列表
     */
    public static List<GradeDTO> getList() {
        return GRADE_LIST;
    }

    public static String getNameById(Integer gradeId) {
        for (GradeDTO grade : GRADE_LIST) {
            if (grade.getId().equals(gradeId)) {
                return grade.getGrade();
            }
        }
        return "";
    }

    public static List<GradeDTO> getGradesByIds(Collection<Integer> gradeIds) {
        if (gradeIds == null || gradeIds.isEmpty()) {
            return new ArrayList<>();
        }

        return GRADE_LIST.stream()
                .filter(grade -> gradeIds.contains(grade.getId()))
                .collect(Collectors.toList());
    }

    /**
     * 根据年级名称获取年级ID
     */
    public static Integer getGradeIdByName(String gradeName) {
        Integer gradeId = GRADE_MAP.get(gradeName);
        if (gradeId != null) {
            return gradeId;
        }
        log.warn("未找到年级名称对应的ID: {}", gradeName);
        throw new CommonException(ResultCodeEnum.GRADE_ID_NOT_FOUND, "未找到年级名称对应的ID: " + gradeName);
    }

    public static List<Integer> getGradeIdsByType(Integer gradeType) {
        if (gradeType == null) {
            return Collections.emptyList();
        }
        switch (gradeType) {
            case 1:
                return Arrays.asList(1, 2, 3, 4, 5, 6);
            case 2:
                return Arrays.asList(7, 8, 9);
            case 3:
                return Arrays.asList(10);
        }
        return Collections.emptyList();
    }
}