// fs-company模块
package com.fs.core.config;

import com.fs.common.core.domain.entity.SysUser;
import com.fs.common.enums.DataScopeEnum;
import com.fs.common.utils.StringUtils;
import com.fs.core.security.LoginUser;
import com.fs.core.security.SecurityUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 登录上下文回调实现
 */
@Component
public class LoginContextCallback implements com.fs.common.config.LoginContextCallback, ApplicationContextAware {

    private static ApplicationContext applicationContext;
    /** 所有权限标识 */
    private static final String ALL_PERMISSION = "*:*:*";
    @Override
    public Long getUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return loginUser != null ? loginUser.getUser().getUserId() : null;
    }

    @Override
    public Long getCompanyUserId() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public String getUsername() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        return loginUser.getUsername();
    }

    @Override
    public String getCompanyUserName() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Long getCompanyId() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Long getDeptId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        return user.getDeptId();
    }


    @Override
    public boolean hasPermission(String permission){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Set<String> permissions = loginUser.getPermissions();
        if(loginUser.getUser().isAdmin()){
            return true;
        }
        return permissions.contains(ALL_PERMISSION) || permissions.contains(StringUtils.trim(permission));
    }


    @Override
    public DataScopeEnum getDataScope(){
        return null;
    }




    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        LoginContextCallback.applicationContext = applicationContext;
    }
}
