package cn.reghao.oss.console.account.service.impl;

import cn.reghao.oss.console.account.db.query.RoleQuery;
import cn.reghao.oss.console.account.db.repository.MenuRepository;
import cn.reghao.oss.console.account.db.repository.RoleRepository;
import cn.reghao.oss.console.account.model.constant.RoleType;
import cn.reghao.oss.console.account.model.po.Menu;
import cn.reghao.oss.console.account.model.po.Role;
import cn.reghao.oss.console.account.model.po.User;
import cn.reghao.oss.console.account.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author reghao
 * @date 2020-06-19 16:36:53
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {
    private final RoleQuery roleQuery;
    private final RoleRepository roleRepository;
    private final MenuRepository menuRepository;

    public RoleServiceImpl(RoleQuery roleQuery, RoleRepository roleRepository, MenuRepository menuRepository) {
        this.roleQuery = roleQuery;
        this.roleRepository = roleRepository;
        this.menuRepository = menuRepository;
    }

    public void initRole() {
        List<Role> roleList = roleRepository.findAll();
        if (roleList.isEmpty()) {
            roleList = new ArrayList<>();
            for (RoleType roleType : RoleType.values()) {
                roleList.add(new Role(roleType.name(), roleType.getDesc()));
            }
            roleRepository.saveAll(roleList);

            List<Menu> menus = menuRepository.findAll();
            if (!menus.isEmpty()) {
                Role role = roleRepository.findByName(RoleType.ROLE_ADMIN.name());
                role.setMenus(new HashSet<>(menus));
                roleRepository.save(role);
            }
        }
    }

    @Override
    public void addOrModify(Role role) {
        String title = String.format("ROLE_%s", role.getName());
        role.setName(title.toUpperCase(Locale.ROOT));
        roleRepository.save(role);
    }

    @Override
    public void delete(Integer roleId) {
        Role role = roleRepository.getOne(roleId);
        List<User> users = roleQuery.getUsersByRole(role);
        if (!users.isEmpty()) {
            log.error("还有用户分配有本角色");
            return;
        }

        role.getMenus().clear();
        roleRepository.delete(role);
    }

    @Override
    public void setRoleMenus(Integer roleId, Set<Menu> menus) {
        Role role = roleRepository.getOne(roleId);
        role.setMenus(menus);
        roleRepository.save(role);
    }

    @Override
    public Role getRole(int roleId) {
        return roleRepository.getOne(roleId);
    }
}
