package com.ruoyi.web.core.aspectj;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SmUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.ss.user.domain.SmUserVO;
import com.ruoyi.ss.user.service.ISmUserService;
import com.ruoyi.web.core.annotation.MchRequired;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 用户类型权限切面
 * @author 辉
 * 2024/3/8
 */
@Aspect
@Component
public class MchRequiredAspect {

    @Autowired
    private ISmUserService smUserService;

    @Autowired
    private TokenService tokenService;

    // 判断当前用户是否有权限访问
    @Before("@annotation(mchRequired)")
    public void doBefore(JoinPoint point, MchRequired mchRequired) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SmUser user = loginUser.getSmUser();
        ServiceUtil.assertion(user == null || user.getIsMch() == null, "获取用户信息异常");

        // 如果登录用户不是商家，那么查询数据库，当数据库是商家时，将商家的账户退出登录，随后前端可进行重新登录
        if (!user.getIsMch()) {
            SmUserVO dbUser = smUserService.selectSmUserByUserId(user.getUserId());
            if (dbUser.getIsMch()) {
                tokenService.delLoginUser(loginUser.getToken());
                throw new ServiceException("用户信息已变更，请重新登录", HttpStatus.UNAUTHORIZED);
            } else {
                throw new ServiceException("仅商家可进行该操作，若您已成为商家，请重新登录后重试");
            }
        }
    }

}
