package com.ruoyi.course.common;


import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.course.enums.GradeEnum;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Component
public class GradeHelper {
    
    /**
     * 将逗号分隔的整数字符串转换为年级枚举列表
     */
    public List<GradeEnum> parseGradeLevel(String gradeLevel) {
        if (StringUtils.isBlank(gradeLevel)) {
            return Collections.emptyList();
        }
        
        List<GradeEnum> result = new ArrayList<>();
        String[] codes = gradeLevel.split(",");
        
        for (String codeStr : codes) {
            codeStr = codeStr.trim();
            if (codeStr.isEmpty()) continue;
            
            try {
                int code = Integer.parseInt(codeStr);
                GradeEnum grade = GradeEnum.fromCode(code);
                result.add(grade);
            } catch (NumberFormatException e) {
                // 如果是中文，尝试转换
                GradeEnum grade = GradeEnum.fromDisplayName(codeStr);
                if (grade != null) {
                    result.add(grade);
                }
            }
        }
        
        return result;
    }
    
    /**
     * 将年级枚举列表转换为逗号分隔的整数字符串
     */
    public String toGradeLevelString(List<GradeEnum> grades) {
        if (grades == null || grades.isEmpty()) {
            return "";
        }
        
        return grades.stream()
                .map(GradeEnum::getCode)
                .map(String::valueOf)
                .collect(Collectors.joining(","));
    }
    
    /**
     * 将逗号分隔的中文字符串转换为整数字符串
     */
    public String convertChineseToCodeString(String chineseGradeLevel) {
        List<GradeEnum> grades = parseGradeLevel(chineseGradeLevel);
        return toGradeLevelString(grades);
    }
    
    /**
     * 判断年级是否在年级列表中
     */
    public boolean containsGrade(String gradeLevel, GradeEnum targetGrade) {
        List<GradeEnum> grades = parseGradeLevel(gradeLevel);
        return grades.contains(targetGrade);
    }
}