package top.continew.admin.common.config.mybatis;

import cn.hutool.core.convert.Convert;
import top.continew.admin.common.model.dto.LoginUser;
import top.continew.admin.common.util.helper.LoginHelper;
import top.continew.starter.data.mp.datapermission.DataPermissionCurrentUser;
import top.continew.starter.data.mp.datapermission.DataPermissionFilter;
import top.continew.starter.data.mp.datapermission.DataScope;

import java.util.stream.Collectors;

/**
 * 数据权限过滤器实现类
 *
 * @author Charles7c
 * @since 2023/12/21 21:19
 */
public class DataPermissionFilterImpl implements DataPermissionFilter {

    @Override
    public boolean isFilter() {
        LoginUser loginUser = LoginHelper.getLoginUserSafely();
        // 如果用户未登录，不进行数据权限过滤
        if (loginUser == null) {
            return false;
        }
        return !loginUser.isAdmin();
    }

    @Override
    public DataPermissionCurrentUser getCurrentUser() {
        LoginUser loginUser = LoginHelper.getLoginUserSafely();
        // 如果用户未登录，返回null
        if (loginUser == null) {
            return null;
        }
        DataPermissionCurrentUser currentUser = new DataPermissionCurrentUser();
        currentUser.setUserId(Convert.toStr(loginUser.getId()));
        currentUser.setDeptId(Convert.toStr(loginUser.getDeptId()));
        currentUser.setRoles(loginUser.getRoles()
            .stream()
            .map(r -> new DataPermissionCurrentUser.CurrentUserRole(Convert.toStr(r.getId()), DataScope.valueOf(r
                .getDataScope()
                .name())))
            .collect(Collectors.toSet()));
        return currentUser;
    }
}