package com.tuoheng.miniprogram.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.SecurityUserUtils;
import com.tuoheng.miniprogram.dao.TenantMapper;
import com.tuoheng.miniprogram.dao.UserMapper;
import com.tuoheng.miniprogram.entity.Tenant;
import com.tuoheng.miniprogram.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Optional;

/**
 * 直接从该工具类中获取当前登录用户信息
 */
@Component
public class CurrentUserUtil {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TenantMapper tenantMapper;

    private static CurrentUserUtil currentUserUtil;

    @PostConstruct
    public void init() {
        currentUserUtil = this;
        currentUserUtil.userMapper = this.userMapper;
        currentUserUtil.tenantMapper = this.tenantMapper;
    }

    /**
     * 私有构造器
     **/
    private CurrentUserUtil() {
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    public static User getUserInfo() {
        String username = SecurityUserUtils.username();
        User user = currentUserUtil.userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getMark, 1).eq(User::getStatus, 1).eq(User::getUsername, username));
        if (null == user) {
            Tenant tenant = currentUserUtil.tenantMapper.selectOne(Wrappers.<Tenant>lambdaQuery().eq(Tenant::getMark, 1).eq(Tenant::getStatus, 1).eq(Tenant::getUsername, username));
            if (null == tenant) {
                throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "该用户并未创建");
            }
        }
        return user;
    }

    /**
     * 获取用户编号
     *
     * @return
     */
    public static String getUserId() {
        User user = getUserInfo();
        return Optional.ofNullable(user.getId()).orElseThrow(() ->
                new ServiceException(HttpStatus.BAD_REQUEST.value(), "未获取到当前用户信息!"));
    }

    /**
     * 租户ID
     *
     * @return
     */
    public static String getTenantId() {
        User user = getUserInfo();
        return Optional.ofNullable(user.getTenantId()).orElseThrow(() ->
                new ServiceException(HttpStatus.BAD_REQUEST.value(), "未获取到当前租户信息!"));
    }
}
