package com.starry.admin.common.aspect;

import com.starry.admin.common.conf.ThreadLocalRequestDetail;
import com.starry.admin.common.exception.ServiceException;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.custom.service.impl.PlayCustomUserInfoServiceImpl;
import com.starry.admin.modules.weichat.service.WxTokenService;
import com.starry.common.constant.Constants;
import com.starry.common.constant.HttpStatus;
import com.starry.common.utils.StringUtils;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 限流处理
 *
 * @author ruoyi
 */
@Slf4j
@Aspect
@Component
public class CustomUserLoginAspect {

    @Resource
    private PlayCustomUserInfoServiceImpl customUserInfoService;

    @Resource
    private WxTokenService tokenService;
    @Resource
    private HttpServletRequest request;

    @Before("@annotation(customUserLogin)")
    public void doBefore(JoinPoint point, CustomUserLogin customUserLogin) {
        String userToken = request.getHeader(Constants.CUSTOM_USER_LOGIN_TOKEN);
        if (StringUtils.isEmpty(userToken)) {
            throw new ServiceException("token为空", HttpStatus.UNAUTHORIZED);
        }
        if (userToken.startsWith(Constants.TOKEN_PREFIX)) {
            userToken = userToken.replace(Constants.TOKEN_PREFIX, "");
        }
        // 解析token
        String userId;
        try {
            userId = tokenService.getWxUserIdByToken(userToken);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new ServiceException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
        PlayCustomUserInfoEntity entity = customUserInfoService.selectById(userId);
        if (Objects.isNull(entity)) {
            throw new ServiceException("未查询到有效用户", HttpStatus.UNAUTHORIZED);
        }
        if (!userToken.equals(entity.getToken())) {
            throw new ServiceException("token异常", HttpStatus.UNAUTHORIZED);
        }
        ThreadLocalRequestDetail.setRequestDetail(entity);
    }
}
