package com.xxfc.platform.common.resover;

import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.xxfc.platform.common.annotaion.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author libin
 * @version 1.0
 * @description
 * @data 2019/7/8 20:17
 */
@ConditionalOnBean(value = UserFeign.class)
@Component
public class LoginUserParamResolver implements HandlerMethodArgumentResolver {

    @Value("${auth.user.token-header:Authorization}")
    private String tokenHeader;

    @Autowired
     private UserFeign userFeign;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader(tokenHeader);
        Class<?> parameterType = parameter.getParameterType();
        if (AppUserDTO.class.equals(parameterType)){
            return  userFeign.userDetailByToken(token).getData();
        }
        if (UserDTO.class.equals(parameterType)){
          return  userFeign.userinfoByToken(token).getData();
        }
        return null;
    }
}
