package com.tax.zone.aop;


import com.yxcheng.token.common.annotation.RuleT;
import com.yxcheng.token.common.model.JsonResult;
import com.yxcheng.token.common.model.RuleModel;
import com.yxcheng.token.common.model.SafeModel;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
@ResponseBody
public class RuleAop {

//    @Autowired
//    private UserClient userClient;

    //切入点
    @Pointcut("@annotation(com.yxcheng.token.common.annotation.RuleT)")
    public void rule() {

    }

    @Around("rule() && @annotation(ruleT)")
    public JsonResult beforeExec(ProceedingJoinPoint joinPoint, RuleT ruleT) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String interfaceMethod = request.getServletPath();
        JsonResult rpcResult = new JsonResult();
        String ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        Object[] objects = joinPoint.getArgs();
        for (Object obj : objects) {
            if (obj instanceof SafeModel) {
                SafeModel safeModel = (SafeModel) obj;

                RuleModel ruleModel = new RuleModel();
                ruleModel.setUserName(safeModel.getAccessKeyID());
                ruleModel.setTaxno(safeModel.getTaxno());
                ruleModel.setIpAddr(ip);
                ruleModel.setFunctionCode(ruleT.value());

//                rpcResult = userClient.checkRule(ruleModel);
                if (checkUserSafe(rpcResult)) {
                    //若校验成功，继续方法的执行，并获取返回结果，返回给前端
                    try {
                        Object object = joinPoint.proceed();
                        if (object instanceof JsonResult) {
                            return (JsonResult) object;
                        }
                    } catch (Throwable throwable) {
                        throw new Exception(throwable);
                    }
                }
            }
        }
        return rpcResult;
    }

    private boolean checkUserSafe(JsonResult result) {
        return result != null && "0".equals(result.getErrorCode());
    }
}
