package com.xueyi.common.web.utils;


import com.xueyi.common.web.annotation.ResponseMessage;
import com.xueyi.common.web.constant.ResponseCode;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


/**
 * 重写请求参数工具类，支持项目内自定义
 */
public class ResponseCodeUtil {
    private static Class<ResponseMessage> ANNO_CLAZZ = ResponseMessage.class;
    private static String INTEGER_CLAZZ_STR = "class java.lang.Integer";

    public ResponseCodeUtil() {
    }

    public static Map<Integer, Map<String, String>> getResponseCodeAndMsgMap() {
        Map<Integer, Map<String, String>> responseMap = new HashMap();
        Class<ResponseCode> responseCodeClazz = ResponseCode.class;
        //扩展支持原有的状态码和消息
        Class<ResponseCode> superResponseCodeClazz = (Class<ResponseCode>) responseCodeClazz.getSuperclass();
        Field[] fields = responseCodeClazz.getDeclaredFields();
        Field[] fields2 = superResponseCodeClazz.getDeclaredFields();

        fields = ArrayUtils.addAll(fields,fields2);
        Integer fieldValue = 0;

        try {
            Field[] var4 = fields;
            int var5 = fields.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Field f = var4[var6];
                if (f.isAnnotationPresent(ANNO_CLAZZ) && f.getGenericType().toString().equals(INTEGER_CLAZZ_STR)) {
                    f.setAccessible(true);
                    fieldValue = (Integer)f.get(responseCodeClazz);
                    responseMap.put(fieldValue, getFieldAnnotationAttrs(f));
                }
            }

            return responseMap;
        } catch (IllegalArgumentException var8) {
            new Throwable("ResponseCode field type must be java.lang.Integer");
        } catch (IllegalAccessException var9) {
            new Throwable("Please use field.setAccessible(true) in " + ResponseCodeUtil.class.getName());
        }

        return null;
    }

    private static Map<String, String> getFieldAnnotationAttrs(Field f) {
        ResponseMessage httpResponseMsg = (ResponseMessage)f.getAnnotation(ANNO_CLAZZ);
        String[] lang = httpResponseMsg.lang();
        String[] msgInfo = httpResponseMsg.msg();
        Integer langSize = lang.length;
        Integer msgInfoSize = msgInfo.length;
        if (langSize != msgInfoSize) {
            new Throwable("Please check HttpResponseMsg annotation field in " + f.getName() + " field");
        }

        Map<String, String> attrsMap = new HashMap();

        for(int i = 0; i < langSize; ++i) {
            attrsMap.put(lang[i], msgInfo[i]);
        }

        return attrsMap;
    }
}
