package com.younike.framework.aspectj;

import com.younike.common.constant.Constants;
import com.younike.common.constant.HttpStatus;
import com.younike.common.core.domain.AjaxResult;
import com.younike.common.utils.StringUtils;
import com.younike.framework.web.domain.MemberUserContext;
import com.younike.framework.web.service.JwtService;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员访问切面
 *
 * @author chenpengfei
 */
@Aspect
@Component
@Log4j2
public class MemberAccessAspect {

    @Autowired
    private JwtService jwtService;

    @Around("@annotation(com.younike.framework.config.MemberAccess)")
    public Object memberInfo(ProceedingJoinPoint pdj){
        log.info("MemberAccess --- " );
        /*result为连接点的放回结果*/
        Object result = null;
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
            String token = request.getHeader("Authorization");
            if (StringUtils.isNotBlank(token)) {
                Claims claims = jwtService.parseToken(token);
                Object o = claims.get(Constants.LOGIN_USER_KEY);
                if (o != null) {
                    new MemberUserContext(Long.valueOf(o.toString()));
                    try {
                        result = pdj.proceed();
                    } catch (Throwable e) {
                        e.printStackTrace();
                        return AjaxResult.error(e.getMessage());
                    }
                }
            } else {
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, "请登录!");
            }
        } else{
            log.info("请求缺失Attribute!");
            return AjaxResult.error("权限验证异常!");
        }
        log.info("--- MemberAccess" );
        return result;
    }
}
