package com.td.boss.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;


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 {

    @Value("${jwt.token}")
    private String tokenHeader;

    private String paramsUserId;

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

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

}
