package com.zhangmeng.admin.manager.service.impl;

import com.zhangmeng.admin.manager.dao.PermissionDao;
import com.zhangmeng.admin.manager.service.PermissionService;
import com.zhangmeng.model.base.baseService.impl.AbstractBaseServiceImpl;
import com.zhangmeng.model.dto.Menu;
import com.zhangmeng.model.entity.Permission;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhangmeng
 * @version 1.0
 * @date 2021年1月7日22:32:54
 */
@Service
public class PermissionServiceImpl extends AbstractBaseServiceImpl<Permission> implements PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> findByUserId(Long userId) {
        return this.permissionDao.findByUserId(userId);
    }

    /**
     * 递归获取菜单tree
     *
     * @param permissions 权限列表
     * @return list
     */
    @Override
    public List<Menu> toUserMenus(List<Permission> permissions, Long parentId) {
        List<Menu> menuList = menuList(permissions);
        return toUserMenu(menuList, 0L);
    }

    private List<Menu> toUserMenu(List<Menu> menuList, Long parentId) {
        List<Menu> list = new ArrayList<>();
        if (menuList.size() > 0) {
            for (Menu menu : menuList) {
                if (parentId.equals(menu.getParent_id())) {
                    menu.setChildren(toUserMenu(menuList, menu.getId()));
                    list.add(menu);
                }
            }
        }
        return list;
    }

    private List<Menu> menuList(List<Permission> permissions) {
        List<Menu> menus = new ArrayList<>();
        if (permissions.size() > 0) {
            for (Permission permission : permissions) {
                Menu menu = new Menu();
                switch (permission.getType()){
                    case CATALOG:
                        menu.setType(0);
                        break;
                    case MENU:
                        menu.setType(1);
                        break;
                    case BUTTON:
                        menu.setType(2);
                        break;
                }
                BeanUtils.copyProperties(permission, menu);
                menus.add(menu);
            }
        }
        return menus;
    }


}
