package org.dromara.common.satoken.core.service;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import org.dromara.common.core.domain.vo.SysProjectRoleMenuVo;
import org.dromara.common.core.domain.vo.SysProjectRolePermissionVo;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.PermissionService;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * sa-token 权限管理实现类
 *
 * @author Lion Li
 */
public class SaPermissionImpl implements StpInterface {

    /**
     * 获取菜单权限列表
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser) || !loginUser.getLoginId().equals(loginId)) {
            PermissionService permissionService = getPermissionService();
            if (ObjectUtil.isNotNull(permissionService)) {
                List<String> list = StringUtils.splitList(loginId.toString(), ":");
                return getPermissionListByProjectId(permissionService.getMenuPermission(Long.parseLong(list.get(1))), null);
            } else {
                throw new ServiceException("PermissionService 实现类不存在");
            }
        }
        UserType userType = UserType.getUserType(loginUser.getUserType());
        // 系统用户
        if (userType == UserType.SYS_USER) {
            Long projectId = loginUser.getProjectId();
            List<SysProjectRoleMenuVo> menuPermission = loginUser.getMenuPermission();
            return getPermissionListByProjectId(menuPermission, projectId);
        } else if (userType == UserType.APP_USER) {
            // 其他端 自行根据业务编写
        }
        return new ArrayList<>();
    }

    /**
     * 获取角色权限列表
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (ObjectUtil.isNull(loginUser) || !loginUser.getLoginId().equals(loginId)) {
            PermissionService permissionService = getPermissionService();
            if (ObjectUtil.isNotNull(permissionService)) {
                List<String> list = StringUtils.splitList(loginId.toString(), ":");
                return getRoleListByProjectId(permissionService.getRolePermission(Long.parseLong(list.get(1))), null);
            } else {
                throw new ServiceException("PermissionService 实现类不存在");
            }
        }
        UserType userType = UserType.getUserType(loginUser.getUserType());
        // 系统用户
        if (userType == UserType.SYS_USER) {
            Long projectId = loginUser.getProjectId();
            List<SysProjectRolePermissionVo> rolePermission = loginUser.getRolePermission();
            return getRoleListByProjectId(rolePermission, projectId);
        } else if (userType == UserType.APP_USER) {
            // 其他端 自行根据业务编写
        }
        return new ArrayList<>();
    }

    private PermissionService getPermissionService() {
        try {
            return SpringUtils.getBean(PermissionService.class);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取菜单权限列表
     *
     * @param menuPermission 菜单权限
     * @param projectId      当前用户所在项目id
     * @return 菜单权限列表
     */
    private List<String> getPermissionListByProjectId(List<SysProjectRoleMenuVo> menuPermission, Long projectId) {
        if (CollUtil.isNotEmpty(menuPermission)) {
            if (projectId != null) {
                Map<Long, List<SysProjectRoleMenuVo>> map = menuPermission.stream()
                    .collect(Collectors.groupingBy(SysProjectRoleMenuVo::getProjectId));
                if (map.containsKey(projectId)) {
                    return map.get(projectId).stream()
                        .map(SysProjectRoleMenuVo::getProjectPermissions)
                        .flatMap(Set::stream)
                        .filter(s -> !s.isEmpty())
                        .distinct()
                        .toList();
                }
            }
            List<Set<String>> setList = menuPermission.stream().map(SysProjectRoleMenuVo::getProjectPermissions).toList();
            return setList.stream().flatMap(Set::stream).filter(s -> !s.isEmpty()).distinct().toList();
        } else {
            return new ArrayList<>();
        }
    }

    /**
     * 获取角色权限列表
     *
     * @param rolePermission 角色权限
     * @param projectId      当前用户所在项目id
     * @return 角色权限列表
     */
    private List<String> getRoleListByProjectId(List<SysProjectRolePermissionVo> rolePermission, Long projectId) {
        if (CollUtil.isNotEmpty(rolePermission)) {
            if (projectId != null) {
                Map<Long, List<SysProjectRolePermissionVo>> map = rolePermission.stream()
                    .collect(Collectors.groupingBy(SysProjectRolePermissionVo::getProjectId));
                if (map.containsKey(projectId)) {
                    return map.get(projectId).stream()
                        .map(SysProjectRolePermissionVo::getProjectRoles)
                        .flatMap(Set::stream)
                        .filter(s -> !s.isEmpty())
                        .distinct()
                        .toList();
                }
            }
            List<Set<String>> list = rolePermission.stream().map(SysProjectRolePermissionVo::getProjectRoles).toList();
            return list.stream().flatMap(Set::stream).filter(s -> !s.isEmpty()).distinct().toList();
        } else {
            return new ArrayList<>();
        }
    }

}
