package com.zfire.mall.manager.config.aop;

import com.aliyuncs.utils.StringUtils;
import com.zfire.mall.manager.annotation.ApiNotAuth;
import com.zfire.mall.manager.bean.admin.AdminUserCom;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.exception.RemoteServiceException;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.plus.entity.AdminRole;
import com.zfire.mall.manager.plus.service.AdminRoleService;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.constant.Constant;
import com.zfire.mall.manager.helper.ResponseHelper;
import com.zfire.mall.manager.utils.CommonUtils;
import com.zfire.mall.manager.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.omg.CORBA.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
@Order(1)
public class ApiAspect {

    @Value("${spring.profiles.active}")
    private String profiles;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AdminRoleService adminRoleService;

    @Pointcut("@annotation(io.swagger.annotations.ApiOperation)")
    public void auth() {}

    @Before("auth()")
    public void doBefore(JoinPoint joinPoint) throws RemoteServiceException {
            start(joinPoint);
    }

    private void start(JoinPoint joinPoint) throws RemoteServiceException {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        Method sourceMethod = getSourceMethod(joinPoint);
        HttpServletRequest request = attributes.getRequest();
        ApiNotAuth apiNotAuth = sourceMethod.getAnnotation(ApiNotAuth.class);

        String token = CommonUtils.getToken(request);
        String userId = CommonUtils.getUserId(request);

        if(apiNotAuth != null){
            return;
        }
        if(!profiles.equals("prd")){
            if(request.getHeader(Constant.TOKEN_NAME) != null && request.getHeader(Constant.TOKEN_NAME).equals("1111")){
                return;
            }
            if(request.getParameter(Constant.TOKEN_NAME) != null && request.getParameter(Constant.TOKEN_NAME).equals("1111")){
                return;
            }
        }

        AdminUserCom adminUserCom = (AdminUserCom) redisUtil.get(Constant.RedisPrefix.TOKEN_MGR + token);
        if(adminUserCom != null) {
            this.closeSys(adminUserCom.getRoleName());
        }

        if (StringUtils.isEmpty(userId) || adminUserCom == null) {
            throw new RemoteServiceException(ResponseHelper.ResponseCode_AUTH_ERROR, "请求不合法");
        }

    }

    private Method getSourceMethod(JoinPoint jp) {
        Method proxyMethod = ((MethodSignature) jp.getSignature()).getMethod();
        try {
            return jp.getTarget().getClass().getMethod(proxyMethod.getName(), proxyMethod.getParameterTypes());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        }
        return null;
    }


    //强制禁止试用系统
    public void closeSys(String roleName){
        Integer count = adminRoleService.lambdaQuery()
                .eq(AdminRole::getVisitSysStatus, false)
                .eq(AdminRole::getName, roleName).count();
        if(count > 0){
            throw new RemoteServiceException("系统更新，请重新登录");
        }
    }

}
