package com.ruoyi.enums;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Getter;

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

@AllArgsConstructor
@Getter
public enum QuestionType {
    Single(1, "单选题"), Multiple(2, "多选题"), Judgment(3, "判断题"), Fill(4, "填空题"),
    Subjective(5, "主观题"), Short(6, "简答题"), Essay(7, "问答题"), Analysis(8, "分析题");

    private final Integer val;
    private final String title;

    private static final Map<String, QuestionType> valMap = Maps.newHashMap();
    private static final Map<Integer, QuestionType> intValMap = Maps.newHashMap();

    @JsonValue
    public Integer getVal() {
        return val;
    }

    @JsonCreator
    public static QuestionType fromValue(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Integer) {
            return intValMap.get((Integer) value);
        }
        if (value instanceof String) {
            String str = (String) value;
            // 尝试作为数字字符串解析
            try {
                Integer intVal = Integer.parseInt(str);
                return intValMap.get(intVal);
            } catch (NumberFormatException e) {
                // 如果不是数字，尝试作为名称或标题查找
                return valMap.get(str);
            }
        }
        return null;
    }

    public static QuestionType of(Integer vol) {
        return valMap.get(vol.toString());
    }

    public static QuestionType of(String vol) {
        QuestionType type = valMap.get(vol);
        return null == type ? QuestionType.Subjective : type;
    }

    static {
        Arrays.stream(QuestionType.values()).forEach(t -> {
            valMap.put(t.val.toString(), t);
            valMap.put(t.title, t);
            valMap.put(t.name(), t);
            intValMap.put(t.val, t);
        });
    }
}
