package com.ema.common.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.web.multipart.support.MultipartFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 请求参数脱敏工具类,
 * 用于日志打印时,对敏感属性字段进行脱敏处理
 */
public class ArgsDesensitizationUtil {

    /**
     * 过滤参数,排除敏感属性字段
     *
     * @param args
     * @param deseFields 敏感属性字段列表
     * @return
     */
    public static String filterArgs(Object[] args, List<String> deseFields) {
        List<Object> filterList = CollUtil.newArrayList();
        Arrays.stream(args).filter(object ->
                !(object instanceof MultipartFilter)
                        && !(object instanceof HttpServletRequest)
                        && !(object instanceof HttpServletResponse)
        ).forEach(object -> {
            JSONObject obj = toJSONObject(object);
            if(obj != null && CollUtil.isNotEmpty(deseFields)) {
                deseFields.forEach(exclude -> {
                    if(obj.containsKey(exclude)){
                        obj.put(exclude, "******");
                    }
                });
                filterList.add(obj);
            }else {
                filterList.add(object);
            }

        });
        return JSONUtil.toJsonStr(filterList);
    }

    /**
     * 对象转JSONObject
     *
     * @param object
     * @return
     */
    private static JSONObject toJSONObject(Object object) {
        if (object instanceof Map || object instanceof Collection ||
                object instanceof String || object instanceof Number ||
                object instanceof Boolean) {
            return null;
        }
        try {
            return JSONUtil.parseObj(object);
        } catch (Exception e) {
            return null;
        }
    }


}
