package com.chushang.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.chushang.datascope.constants.ScopeConstants;
import com.chushang.datascope.entity.DataScopeEntity;
import com.chushang.security.auth.AuthUtil;
import com.chushang.system.entity.po.SysRole;
import com.chushang.system.entity.po.SysUser;
import com.chushang.system.service.ISysDeptService;
import com.chushang.system.service.ISysMenuService;
import com.chushang.system.service.ISysPermissionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author by zhaowenyuan create 2022/8/19 09:43
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl implements ISysPermissionService {

    private final ISysMenuService menuService;
    private final ISysDeptService deptService;

    @Override
    public Set<String> getRolePermission(SysUser sysUser) {
//        // 包含的角色
        List<SysRole> roleList = sysUser.getRoles();
        if (sysUser.isAdmin()){
            // 需要 判断下是否包含 特殊管理员
            return Set.of(AuthUtil.SUPER_ADMIN);
        }else {
            Set<String> roles = new HashSet<>();
            roleList.stream().filter(Objects::nonNull)
                    .forEach(r -> roles.addAll(Set.of(r.getRoleKey().trim().split(","))));
            return roles;
        }
    }

    /**
     * 获取菜单数据权限
     */
    @Override
    public Set<String> getMenuPermission(SysUser sysUser) {
        Set<String> perms = new HashSet<>();
        List<SysRole> roles = sysUser.getRoles();
        // 包含有 admin 角色 --> 即为超级管理员账号
        if (sysUser.isAdmin()){
            perms.add("*:*:*");
        }else {
            // 判断 是否包含有管理员角色
            // roles 必定不为空
            if (CollectionUtil.isNotEmpty(roles)){
                for (SysRole role : roles) {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
                // 添加 roleIds
                sysUser.setRoleIds(roles.stream().map(SysRole::getRoleId).toArray(Long[]::new));
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(sysUser.getUserId()));
            }
        }
        return perms;
    }

    /**
     * 这个会不会慢? 因为是 for 循环
     */
    public List<DataScopeEntity> getDataScopes(SysUser sysUser){
        List<SysRole> roles = sysUser.getRoles();
        return roles.parallelStream().map(role -> {
            // 用于角色 控制,
            String dataScope = role.getDataScope();
            Long roleId = role.getRoleId();
            Long deptId = sysUser.getDeptId();
            Long userId = sysUser.getUserId();
            Set<String> permissions = role.getPermissions();
            Set<String> deptIds = new HashSet<>();
            // 需要roleId
            if (ScopeConstants.DATA_SCOPE_CUSTOM.equals(dataScope)) {
                List<String> longs = deptService.listScopeDeptIdByRoleId(roleId);
                deptIds.addAll(longs);
            }
            // 部门及以下
            else if (ScopeConstants.DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                List<String> longs = deptService.listScopeDeptIdByDeptId(deptId);
                deptIds.addAll(longs);
            }
            // 部门 为空时, 不让其看到全部的, -1 的部门id 必定不存在
            if (CollectionUtil.isEmpty(deptIds)) deptIds.add("-1");
            return DataScopeEntity.builder()
                    .scope(dataScope)
                    .roleId(roleId)
                    .userId(userId)
                    .deptId(deptId)
                    .permissions(permissions)
                    .deptIds(deptIds)
                    .build();
        }).collect(Collectors.toList());
    }
}
