package com.codvision.auth.config;

import cn.hutool.core.util.ObjectUtil;
import com.codvision.auth.entity.SysMenu;
import com.codvision.auth.entity.SysRole;
import com.codvision.auth.service.ISysMenuService;
import com.codvision.auth.service.ISysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hxl
 */
@Slf4j
@Component
public class ApplicationInitRunner implements ApplicationRunner {

    @Resource
    private ISysRoleService roleService;

    @Resource
    private ISysMenuService menuService;

    @Override
    public void run(ApplicationArguments args) {
        // 初始化超级管理员菜单权限
        initializeAdminMenus();
    }


    private void initializeAdminMenus() {
        SysRole sysRole = roleService.getById(1);
        if (ObjectUtil.isEmpty(sysRole)) {
            return;
        }

        List<SysMenu> sysMenuList = menuService.list();
        if (CollectionUtils.isEmpty(sysMenuList)) {
            return;
        }

        List<Integer> menuIdList = sysMenuList.stream().map(SysMenu::getId).collect(Collectors.toList());
        roleService.setRoleMenu(sysRole.getId(), menuIdList);
        log.info("The initialization of default system super administrator permissions has been completed...");
    }
}
