package com.seer.teach.user.filter;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.seer.teach.user.entity.AuthorityEntity;
import com.seer.teach.user.entity.RoleEntity;
import com.seer.teach.user.entity.UserRoleEntity;
import com.seer.teach.user.service.IAuthorityService;
import com.seer.teach.user.service.IRoleService;
import com.seer.teach.user.service.IUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Component
public class StpInterfaceImpl implements StpInterface {

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IAuthorityService authorityService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        Integer userId = Integer.valueOf(loginId.toString());
        List<AuthorityEntity> permissions = authorityService.getPermissionsByUserId(userId);
        if (CollUtil.isNotEmpty(permissions)) {
            return permissions.stream().map(AuthorityEntity::getAuthorityCode).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        Integer userId = Integer.valueOf(loginId.toString());
        log.info("user[{}] getRoleList:{}", userId,loginId);
        List<UserRoleEntity> userRoles = userRoleService.getListByUserId(userId);
        if (CollUtil.isNotEmpty(userRoles)) {
            Set<Integer> roleIds = userRoles.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toSet());
            Collection<RoleEntity> roles = roleService.getRoleListByRoleIds(roleIds);
            return roles.stream().map(RoleEntity::getRoleCode).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}