package com.crm.login.rely.backend.interceptor;

import com.crm.rely.backend.aspect.ControllerAop;
import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.constant.PrefixEnum;
import com.crm.rely.backend.core.entity.login.InfoEntity;
import com.crm.rely.backend.core.entity.user.info.UserInfoEntity;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.RedisService;
import com.crm.rely.backend.util.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletRequest;

/**
 * 实现注入对象参数 对象session对象必须继承BaseCustomerInfo
 *
 * @author houn
 */
public class CustomerInfoArgumentResolver implements WebArgumentResolver {

    @Autowired
    private RedisService redisService;
    @Autowired
    private ControllerAop controllerAop;

    public CustomerInfoArgumentResolver(RedisService redisService, ControllerAop controllerAop) {
        this.redisService = redisService;
        this.controllerAop = controllerAop;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) throws Exception {
        if (methodParameter.getParameterType() != null &&
                InfoEntity.class.isAssignableFrom(methodParameter.getParameterType())) {
            HttpServletRequest httpServletRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);

            InfoEntity infoEntity = HttpServletRequestUtil.getLoginInfo(methodParameter.getParameterType(),
                    httpServletRequest, redisService, true);

            //如果为空 直接不能登录
            if (infoEntity == null) {
                throw ServiceException.exception(Constants.INVALID);
            }


            return infoEntity;
        }
        return UNRESOLVED;
    }
}

