package com.ics.admin.resolver;

import com.ics.admin.service.IIcsCustomerStaffService;
import com.ics.common.annotation.LoginStaff;
import com.ics.common.core.domain.IcsCustomerStaff;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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 org.wf.jwtp.provider.Token;
import org.wf.jwtp.util.SubjectUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 有@LoginStaff注解的方法参数，注入当前登录用户
 *
 */
@Configuration
public class LoginStaffHandlerResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IIcsCustomerStaffService customerStaffService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(IcsCustomerStaff.class) && parameter.hasParameterAnnotation(LoginStaff.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest nativeWebRequest, WebDataBinderFactory factory) throws Exception {
        // 获取用户
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

        Token token = SubjectUtil.getToken(request);
        Long userId = Long.valueOf(token.getUserId());
        if (userId == null) {
            return null;
        }
        return customerStaffService.selectIcsCustomerStaffById(userId);
    }
}