/*
 * Copyright (c) 2023 codvision.com All Rights Reserved.
 */

package com.codvision.authcore.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.codvision.authcore.bean.SysUserBean;
import com.codvision.authcore.service.IAuthService;
import com.codvision.commoncore.exception.AuthException;
import org.springframework.context.ApplicationContext;

import java.util.Optional;

/**
 * 认证工具类
 *
 * @author lingee
 * @date 2023/7/18
 */
public class AuthUtil {

    /**
     * 获取token
     *
     * @return token
     */
    public static String getToken() {
        ApplicationContext context = SpringUtil.getApplicationContext();
        if (!context.containsBean("authService")) {
            return null;
        }
        IAuthService authService = SpringUtil.getBean(IAuthService.class);
        return authService.getAuthToken(RequestUtil.getRequest());
    }


    /**
     * 获取当前登录用户信息
     *
     * @return 用户信息
     */
    public static SysUserBean getCurrentUser() {
        ApplicationContext context = SpringUtil.getApplicationContext();
        if (!context.containsBean("authService")) {
            return new SysUserBean();
        }
        IAuthService authService = SpringUtil.getBean(IAuthService.class);
        String token = authService.getAuthToken(RequestUtil.getRequest());
        Optional.ofNullable(token).orElseThrow(() -> new AuthException(10002));
        SysUserBean sysUser = authService.getCurrentUserInfo(token);
        Optional.ofNullable(sysUser).orElseThrow(() -> new AuthException(10002));
        return sysUser;
    }

    /**
     * 判断是否已登录
     *
     * @return
     */
    public static boolean isLogin() {
        ApplicationContext context = SpringUtil.getApplicationContext();
        if (!context.containsBean("authService")) {
            return false;
        }
        IAuthService authService = SpringUtil.getBean(IAuthService.class);
        String token = authService.getAuthToken(RequestUtil.getRequest());
        if (StrUtil.isBlank(token)) {
            return false;
        }
        SysUserBean sysUser = authService.getCurrentUserInfo(token);
        if (ObjectUtil.isEmpty(sysUser)) {
            return false;
        }
        return true;
    }
}
