package com.hs.admin.common.resolvers;

import com.hs.admin.common.Constants;
import com.hs.admin.common.annotations.CurrentUser;
import com.hs.admin.common.utils.TokenUtil;
import com.hs.admin.model.SysUser;
import com.hs.common.utils.RedisUtil;
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;

public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(CurrentUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,WebDataBinderFactory webDataBinderFactory) {
        String token = nativeWebRequest.getHeader(Constants.TOKEN_KEY);
        if(TokenUtil.checkToken(token)){
            SysUser user = (SysUser)RedisUtil.get(token);
            return user.getId();
        }
        return null;
    }
}
