package com.malk.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Slf4j
public abstract class UtilServlet {

    /**
     * 获取 formData 参数转 map
     *
     * @return
     */
    public static Map<String, Object> getParamMap(HttpServletRequest req) {
        Map map = new HashMap();
        Map<String, String[]> paramMap = req.getParameterMap();
        if (paramMap != null && !paramMap.isEmpty()) {
            Set<String> keySet = paramMap.keySet();
            Iterator var4 = keySet.iterator();
            while (true) {
                while (var4.hasNext()) {
                    String key = (String) var4.next();
                    String[] values = paramMap.get(key);
                    if (values != null && values.length != 0) {
                        if (values.length == 1) {
                            map.put(key, values[0]);
                        } else {
                            map.put(key, values);
                        }
                    } else {
                        map.put(key, "");
                    }
                }
                return (Map) map;
            }
        } else {
            return (Map) map;
        }
    }

    /**
     * 判断map取值是否为空
     */
    public static String isNull(Map param, String... keys) {
        for (String key : keys) {
            if (!param.containsKey(key) || param.get(key) == null || String.valueOf(param.get(key)).trim().equals("")
                    || String.valueOf(param.get(key)).trim().equals("null")) {
                return key;
            }
        }
        return null;
    }

    /**
     * 判断map取值是否为空
     */
    public static String isNull(Map param, String keys) {
        return isNull(param, keys.split(", "));
    }

    public static boolean isNotNull(Map param, String... keys) {
        return StringUtils.isBlank(isNull(param, keys));
    }

    /**
     * 获取所有header
     */
    public static Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headerMap = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            String value = request.getHeader(name);
            headerMap.put(name, value);
        }
        return headerMap;
    }
}
