package com.starry.admin.common.aspect;

import com.starry.admin.common.conf.ThreadLocalRequestDetail;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.exception.ServiceException;
import com.starry.admin.modules.clerk.module.entity.PlayClerkUserInfoEntity;
import com.starry.admin.modules.clerk.service.impl.PlayClerkUserInfoServiceImpl;
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 ClerkUserLoginAspect {

    @Resource
    private PlayClerkUserInfoServiceImpl clerkUserInfoService;

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

    @Before("@annotation(clerkUserLogin)")
    public void doBefore(JoinPoint point, ClerkUserLogin clerkUserLogin) {
        String userToken = request.getHeader(Constants.CLERK_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);
        }
        PlayClerkUserInfoEntity entity = clerkUserInfoService.selectById(userId);
        if (Objects.isNull(entity)) {
            throw new ServiceException("未查询到有效用户", HttpStatus.UNAUTHORIZED);
        }
        try {
            clerkUserInfoService.ensureClerkSessionIsValid(entity);
        } catch (CustomException e) {
            log.warn("Clerk token rejected due to status change, clerkId={} message={}", entity.getId(), e.getMessage());
            throw new ServiceException(e.getMessage(), HttpStatus.UNAUTHORIZED);
        }
        if (!userToken.equals(entity.getToken())) {
            throw new ServiceException("token异常", HttpStatus.UNAUTHORIZED);
        }
        ThreadLocalRequestDetail.setRequestDetail(entity);
    }
}
