package shop.alien.store.config;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.core.MethodParameter;
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;

import shop.alien.entity.store.UserLoginInfo;
import shop.alien.util.common.JwtUtil;
import shop.alien.util.common.TokenInfo;

public class TokenInfoArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(TokenInfo.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("Authorization");
        if (token != null) {
            try {
                JSONObject tokenInfo = JwtUtil.getTokenInfo(token);
//                DecodedJWT tokenInfo = JWTUtils.getTokenInfo(token);
                UserLoginInfo userLoginInfo = new UserLoginInfo();
                String phone = tokenInfo.getString("phone");
                String userName = tokenInfo.getString("userName");
                String userId = tokenInfo.getString("userId");
                String type = tokenInfo.getString("userType");
                userLoginInfo.setUserPhone(phone);
                userLoginInfo.setUserId(Integer.parseInt(userId));
                userLoginInfo.setUserName(userName);
                userLoginInfo.setToken(token);
                userLoginInfo.setType(type);
                // 这里返回用户信息，可根据需求调整续加
                return userLoginInfo;
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}