package ink.wgink.login.oauth2.server.service.impl;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.exceptions.DependencyException;
import ink.wgink.interfaces.consts.ISystemConstant;
import ink.wgink.interfaces.menu.IMenuBaseService;
import ink.wgink.interfaces.role.IRoleMenuBaseService;
import ink.wgink.login.oauth2.server.pojo.pos.OAuth2ClientPO;
import ink.wgink.login.oauth2.server.service.IOAuth2ClientMenuService;
import ink.wgink.login.oauth2.server.service.IOAuth2ClientService;
import ink.wgink.pojo.dtos.menu.MenuDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @ClassName: OAuth2ClientMenuServiceImpl
 * @Description: OAauth2客户端菜单业务
 * @Author: wanggeng
 * @Date: 2021/9/22 11:33 上午
 * @Version: 1.0
 */
@Service
public class OAuth2ClientMenuServiceImpl extends DefaultBaseService implements IOAuth2ClientMenuService {

    @Autowired(required = false)
    private IRoleMenuBaseService roleMenuBaseService;
    @Autowired(required = false)
    private IMenuBaseService menuBaseService;
    @Autowired
    private IOAuth2ClientService oAuth2ClientService;

    @Override
    public List<MenuDTO> listAll(String clientId, List<String> roleIds) {
        if (roleMenuBaseService == null) {
            throw new DependencyException("角色依赖未引入");
        }
        if (menuBaseService == null) {
            throw new DependencyException("菜单依赖为引入");
        }
        OAuth2ClientPO oAuth2ClientPO = oAuth2ClientService.getPO(clientId);
        if (StringUtils.isBlank(oAuth2ClientPO.getMenuId())) {
            return new ArrayList<>();
        }
        List<String> menuIds;
        if (StringUtils.equals(roleIds.get(0), ISystemConstant.ADMIN)) {
            // 管理员菜单
            menuIds = roleMenuBaseService.listMenuId(ISystemConstant.ADMIN);
            // 管理员菜单为空，加载全部
            if (menuIds.isEmpty()) {
                return menuBaseService.listSystemMenu(oAuth2ClientPO.getMenuId());
            }
        } else {
            // 其他角色菜单
            menuIds = roleMenuBaseService.listMenuId(roleIds);
        }
        return menuBaseService.listSystemMenu(oAuth2ClientPO.getMenuId(), menuIds);
    }

}
