package com.YuyeTech.HeartRate.utils;

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


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

/**
 * @author:slambb
 * @date:2019/12/27
 */
@Slf4j
public class TokenRequestWrapper extends HttpServletRequestWrapper {

    private String paramsUserId;
    private Integer paramsPlatform;

    public TokenRequestWrapper(HttpServletRequest request,String userId,Integer platform) {
        super(request);
        paramsUserId = userId;
        paramsPlatform = platform;
    }

    /**
     * 修改此方法主要是因为当RequestMapper中的参数为pojo类型时，
     * 会通过此方法获取所有的请求参数并进行遍历，对pojo属性赋值
     *
     * @return
     */
    @Override
    public Enumeration<String> getParameterNames() {
        Enumeration<String> enumeration = super.getParameterNames();
        ArrayList<String> list = Collections.list(enumeration);
        String token = super.getHeader("token");
        Integer platform = super.getIntHeader("platform");
        list.add("platform");
        log.info("getParameterNames token=="+token);
        //当有token字段时动态的添加uid字段
        if (StringUtils.isNotBlank(token)) {
            list.add("userId");
            return Collections.enumeration(list);
        } else {
            return super.getParameterNames();
        }
    }

    @Override
    public String[] getParameterValues(String name) {
        if ("userId".equals(name)) {
            return new String[]{paramsUserId};
        }
        if ("platform".equals(name)) {
            return new String[]{paramsPlatform.toString()};
        }
        return super.getParameterValues(name);
    }

}
