package com.iformall.domain.vo.invest;

import com.iformall.common.ErrorCode;
import com.iformall.domain.po.MallUserInfo;
import com.iformall.enums.EnumInvestUserType;
import com.iformall.exception.MallinkException;

import java.util.Objects;

public class InvestUserContext {

	private static final ThreadLocal<MallUserInfo> USER_INFO_THREAD_LOCAL = ThreadLocal.withInitial(MallUserInfo::new);
	private static final ThreadLocal<EnumInvestUserType> MANAGER_THREAD_LOCAL = ThreadLocal.withInitial(() -> EnumInvestUserType.MANAGER);


	public static Long getUserId() {
		if (Objects.isNull(getUser())) return null;
		return getUser().getId();
	}

	public static MallUserInfo getUser() {
		return USER_INFO_THREAD_LOCAL.get();
	}

	public static Long getDataUser() {
		if (isManager()) {
			return null;
		} else {
			return getUserId();
		}
	}

	public static void setUser(MallUserInfo user) {
		if (user != null) {
			USER_INFO_THREAD_LOCAL.set(user);
		}
	}

	public static void setInvestUserType(EnumInvestUserType type) {
		if(Objects.isNull(type)) {
			throw new MallinkException(ErrorCode.USER_NO_PERMISSION.getCode(), "用户的数据权限未配置");
		}
		MANAGER_THREAD_LOCAL.set(type);
	}

	public static boolean isManager() {
		return Objects.equals(MANAGER_THREAD_LOCAL.get(), EnumInvestUserType.MANAGER);
	}

	public static void remove() {
		USER_INFO_THREAD_LOCAL.remove();
		MANAGER_THREAD_LOCAL.remove();
	}
}
