<%_ if (position === 'import') { _%>
import <%= packageName %>.security.SecurityUtils;
    <%_ if (useMultiTenant) { _%>
import <%= packageName %>.SpringBootUtil;
import com.diboot.core.util.BeanUtils;
import <%= packageName %>.service.ViewPermissionQueryService;
import <%= packageName %>.service.criteria.ViewPermissionCriteria;
    <%_ } _%>
<%_ } _%>
<%_ if (position === 'methodInterface') { _%>

    /**
     * get all viewPermission by currentUserLogin
     *
     * @return List<ViewPermissionDTO>
     */
    public List<ViewPermissionDTO> getAllByLogin();
<%_ } _%>
<%_ if (position === 'method') {
    const manyListName = ormTool !== 'mybatis' ? 'Set' : 'List';
    const manyListType = ormTool !== 'mybatis' ? 'LinkedHashSet' : 'ArrayList'; _%>
    <%_ if (ormTool === 'mybatis' && databaseTypeSql) { _%>

    /**
     * get all viewPermission by currentUserLogin
     *
     * @return List<ViewPermissionDTO>
     */
    public List<ViewPermissionDTO> getAllByLogin() {
        List<ViewPermission> resultList = new ArrayList<>();
        // 根据login获得用户的角色
        SecurityUtils.getCurrentUserId().ifPresent(userId -> {
            List<ViewPermission> viewPermissionsByUserId = this.viewPermissionRepository.findAllViewPermissionsByUserId(userId);
            List<ViewPermission> addViewPermissions = new ArrayList<>();
            viewPermissionsByUserId.forEach(viewPermission -> {
                Binder.bindRelations(viewPermission, new String[] { "parent", "authorities" });
                while (viewPermission != null && viewPermission.getParent() != null) {
                    <%= primaryKey.type%> parentId = viewPermission.getParent().getId();
                    if (viewPermissionsByUserId.stream().noneMatch(viewPermissionDTO1 -> viewPermissionDTO1.getId().equals(parentId))) {
                        ViewPermission oneNoChildren = viewPermissionRepository.findById(parentId).orElse(null);
                        if (oneNoChildren != null) {
                            addViewPermissions.add(oneNoChildren);
                            viewPermission = oneNoChildren;
                            Binder.bindRelations(viewPermission, new String[] { "parent", "authorities" });
                        } else {
                            viewPermission = null;
                        }
                    } else {
                        viewPermission = null;
                    }
                }
            });
            viewPermissionsByUserId.addAll(addViewPermissions);
            // 已经找到所有的当前User相关的ViewPermissions及上级，接下来转换为树形结构。
            viewPermissionsByUserId.forEach(userViewPermission -> {
                if (userViewPermission.getParent() == null) {
                    <%= primaryKey.type%> finalId = userViewPermission.getId();
                    if (resultList.stream().noneMatch(resultViewPermissionDTO -> resultViewPermissionDTO.getId().equals(finalId))) {
                        resultList.add(userViewPermission);
                    }
                } else {
                    ViewPermission topParent = null;
                    while (userViewPermission != null && userViewPermission.getParent() != null) {
                        <%= primaryKey.type%> tempId = userViewPermission.getParent().getId();
                        Optional<ViewPermission> tempViewPermission = viewPermissionsByUserId.stream().filter(viewPermission -> viewPermission.getId().equals(tempId)).findAny();
                        if (tempViewPermission.isPresent()) {
                            ViewPermission viewPermission = tempViewPermission.orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>);
                            if (viewPermission.getParent() == null) {
                                topParent = viewPermission;
                                viewPermission.getChildren().add(userViewPermission);
                                userViewPermission = null;
                            } else {
                                viewPermission.getChildren().add(userViewPermission);
                                userViewPermission = viewPermission;
                            }
                        } else {
                            userViewPermission = null;
                        }
                    }
                    if (topParent != null) {
                        ViewPermission finalTopParent = topParent;
                        Optional<ViewPermission> any = resultList.stream().filter(resultViewPermission -> resultViewPermission.getId().equals(finalTopParent.getId())).findAny();
                        if (any.isPresent()) {
                            // 处理子列表
                            List<ViewPermission> resultChildren = any.orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>).getChildren();
                            List<ViewPermission> unCheckChildren = topParent.getChildren();
                            addToResult(resultChildren,unCheckChildren);
                        } else {
                            resultList.add(topParent);
                        }
                    }
                }
            });
        });
        return viewPermissionMapper.toDto(resultList);
    }
        <%_ if (useMultiTenant) { _%>
    /**
     * 根据租户ID复制所有的可视权限
     */
    @Transactional
    public List<ViewPermission> createTenantViewPermissions(Long tenantId) {
        log.debug("Request to createTenantViewPermissions : {}", tenantId);
        List<ViewPermission> result = new ArrayList<>();
        ViewPermissionQueryService viewPermissionQueryService = SpringBootUtil.getBean(ViewPermissionQueryService.class);
        IPage<ViewPermissionDTO> viewPermissions = viewPermissionQueryService.findAllTop(new ViewPermissionCriteria(), new Page<>(0, 1000));
        viewPermissions.getRecords().forEach(viewPermissionDTO -> {
            ViewPermission viewPermission = viewPermissionMapper.toEntity(viewPermissionDTO);
            viewPermission.setId(null);
            viewPermission.setTenantId(tenantId);
            viewPermissionRepository.insert(viewPermission);
            result.add(viewPermission);
            // 复制子节点
            copyChildren(viewPermissionDTO.getChildren(), tenantId, viewPermission.getId());
        });
        return result;
    }

    /**
     * 复制子节点
     */
    @Transactional
    public void copyChildren(List<ViewPermissionDTO> children, Long tenantId, Long newParentId) {
        for (ViewPermissionDTO child : children) {
            ViewPermission newChild = new ViewPermission();
            BeanUtils.copyProperties(child, newChild);
            newChild.setId(null);
            newChild.setParentId(newParentId);
            newChild.setTenantId(tenantId);
            this.save(newChild);
            copyChildren(child.getChildren(), tenantId, newChild.getId());
        }
    }
        <%_ } _%>
    <%_ } else { _%>
    /**
     * get all viewPermission by currentUserLogin
     *
     * @return List<ViewPermissionDTO>
     */
    @Transactional(readOnly = true)
    public List<ViewPermissionDTO> getAllByLogin() {
        List<ViewPermission> resultList = new ArrayList<>();
        // 获得所有角色的viewPermission。
        <%_ if (reactive) { _%>
        if (Boolean.FALSE.equals(SecurityUtils.isAuthenticated().block())) {
        <%_ } else { _%>
        if (!SecurityUtils.isAuthenticated()) {
        <%_ } _%>
            return viewPermissionMapper.toDto(resultList);
        }
        String username = SecurityUtils.getCurrentUserLogin().orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>);
        List<ViewPermission> userViewPermissions = viewPermissionRepository.findAllViewPermissionsByCurrentUser(username)<%= reactive ? '.collectList().block()' : ''%>;
        List<ViewPermission> addViewPermissions = new ArrayList<>();
        userViewPermissions.forEach(
            viewPermission -> {
                while (viewPermission != null && viewPermission.getParent() != null) {
                    <%= primaryKey.type%> parentId = viewPermission.getParent().getId();
                    if (
                        userViewPermissions
                            .stream()
                            .noneMatch(viewPermission1 -> viewPermission1.getId().equals(parentId))
                    ) {
                        Optional<ViewPermission> oneNoChildren = viewPermissionRepository.<%= databaseTypeSql ? 'findOneWithEagerRelationships' : 'findById'%>(parentId)<%= reactive ? '.blockOptional()' : ''%>;
                        if (oneNoChildren.isPresent()) {
                            addViewPermissions.add(oneNoChildren.get());
                            viewPermission = oneNoChildren.get();
                        } else {
                            viewPermission = null;
                        }
                    } else {
                        viewPermission = null;
                    }
                }
            }
        );
        userViewPermissions.addAll(addViewPermissions);
        // 已经找到所有的当前User相关的ViewPermissions及上级，接下来转换为树形结构。
        userViewPermissions.forEach(
            userViewPermission -> {
                if (userViewPermission.getParent() == null) {
                    <%= primaryKey.type%> finalId = userViewPermission.getId();
                    if (
                        resultList
                            .stream()
                            .noneMatch(resultViewPermission -> resultViewPermission.getId().equals(finalId))
                    ) {
                        resultList.add(userViewPermission);
                    }
                } else {
                    ViewPermission topParent = null;
                    while (userViewPermission != null && userViewPermission.getParent() != null) {
                        <%= primaryKey.type%> tempId = userViewPermission.getParent().getId();
                        Optional<ViewPermission> tempViewPermission = userViewPermissions
                            .stream()
                            .filter(viewPermission -> viewPermission.getId().equals(tempId))
                            .findAny();
                        if (tempViewPermission.isPresent()) {
                            ViewPermission viewPermission = tempViewPermission.orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>);
                            if (viewPermission.getParent() == null) {
                                topParent = viewPermission;
                                viewPermission.getChildren().add(userViewPermission);
                                userViewPermission = null;
                            } else {
                                viewPermission.getChildren().add(userViewPermission);
                                userViewPermission = viewPermission;
                            }
                        } else {
                            userViewPermission = null;
                        }
                    }
                    if (topParent != null) {
                        ViewPermission finalTopParent = topParent;
                        Optional<ViewPermission> any = resultList
                            .stream()
                            .filter(
                                resultViewPermission -> resultViewPermission.getId().equals(finalTopParent.getId())
                            )
                            .findAny();
                        if (any.isPresent()) {
                            // 处理子列表
                            Set<ViewPermission> resultChildren = any.get().getChildren();
                            Set<ViewPermission> unCheckChildren = topParent.getChildren();
                            addToResult(resultChildren, unCheckChildren);
                        } else {
                            resultList.add(topParent);
                        }
                    }
                }
            }
        );
        return viewPermissionMapper.toDto(resultList);
    }

    <%_ } _%>

    private void addToResult(<%= manyListName%><ViewPermission> resultChildren, <%= manyListName%><ViewPermission> unCheckChildren) {
        if (!unCheckChildren.isEmpty()) {
            unCheckChildren.forEach(child -> {
                <%= primaryKey.type%> childId = child.getId();
                Optional<ViewPermission> any = resultChildren.stream().filter(viewPermission -> viewPermission.getId().equals(childId)).findFirst();
                if (any.isPresent()) {
                    addToResult(any.orElseThrow(<% if (javaVersion === '8') { %>() -> new NoSuchElementException("No value present")<% } %>).getChildren(), child.getChildren());
                } else {
                    resultChildren.add(child);
                }
            });
        }
    }
<%_ } _%>
