package cn.com.poc.common.utils;


import cn.com.poc.support.security.oauth.constants.OauthConstants;
import cn.com.poc.support.security.oauth.entity.OpenPlatformEntity;
import cn.com.poc.support.security.oauth.entity.UserBaseEntity;
import cn.com.poc.user.entity.MemberInfoEntity;
import cn.com.yict.framemax.core.context.Context;
import cn.com.yict.framemax.data.model.UserBaseModel;
import cn.com.yict.framemax.frame.entity.UserSessionEntity;
import cn.com.yict.framemax.security.oauth.exception.TokenExpiredException;
import org.springframework.beans.BeanUtils;

import java.util.Locale;

/**
 * @author Focan Zhong
 * @create 2021/8/6
 */
public class BlContext {

    /**
     * 获取上下文用户
     *
     * @return
     */
    public static UserBaseEntity getCurrentUser() {
        UserBaseModel userBaseModel = Context.get().getCurrentUser();
        if (userBaseModel == null) {
            throw new TokenExpiredException();
        }
        return distinguishUserType(userBaseModel);
    }

    /**
     * 获取上下文用户 无异常
     *
     * @return
     */
    public static UserBaseEntity getCurrentUserNotException() {
        UserBaseModel userBaseModel = Context.get().getCurrentUser();
        if (userBaseModel == null) {
            return null;
        }
        return distinguishUserType(userBaseModel);
    }

    /**
     * 区分用户类型
     *
     * @param userBaseModel
     * @return
     */
    private static UserBaseEntity distinguishUserType(UserBaseModel userBaseModel) {
        UserBaseEntity userBaseEntity = new UserBaseEntity();
        BeanUtils.copyProperties(userBaseModel, userBaseEntity);
        if (Context.get().getCurrentUser() instanceof MemberInfoEntity) {
            userBaseEntity.setType(OauthConstants.OauthEnum.MEMBER_DOMAIN.name());
        }
        return userBaseEntity;
    }

    /**
     * 获取当前系统语言[小写]
     */
    public static String getCurrentLocaleLanguageToLowerCase() {
        return Context.get().getMessageSource().getCurrentLocale().toLanguageTag().toLowerCase();
    }
}
