package com.czg.service.account.service.impl;

import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.czg.account.entity.ShopPermission;
import com.czg.account.service.ShopPermissionService;
import com.czg.service.account.mapper.ShopPermissionMapper;
import org.springframework.stereotype.Service;

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

/**
 * 店铺权限 服务层实现。
 *
 * @author zs
 * @since 2025-02-18
 */
@Service
public class ShopPermissionServiceImpl extends ServiceImpl<ShopPermissionMapper, ShopPermission> implements ShopPermissionService{

    @Override
    public List<ShopPermission> getPermission() {
        // 构建 parentId -> Permission 映射
        List<ShopPermission> permissions = list();
        Map<Long, List<ShopPermission>> groupByParent = permissions.stream()
                .collect(Collectors.groupingBy(ShopPermission::getParentId));

        // 通过 stream 递归构建树
        return permissions.stream()
                .filter(p -> p.getParentId() == 0)
                .peek(p -> p.setChildren(getChildren(p.getId(), groupByParent)))
                .collect(Collectors.toList());
    }

    private static List<ShopPermission> getChildren(long parentId, Map<Long, List<ShopPermission>> groupByParent) {
        return groupByParent.getOrDefault(parentId, new ArrayList<>()).stream()
                .peek(child -> child.setChildren(getChildren(child.getId(), groupByParent)))
                .collect(Collectors.toList());
    }
}
