package cn.reghao.autodop.dmaster.rbac.service;

import cn.reghao.autodop.dmaster.rbac.db.crud.RoleCrud;
import cn.reghao.autodop.dmaster.rbac.db.query.RoleQuery;
import cn.reghao.autodop.dmaster.rbac.model.po.Menu;
import cn.reghao.autodop.dmaster.rbac.model.po.Role;
import cn.reghao.autodop.dmaster.rbac.model.po.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * @author reghao
 * @date 2020-06-19 16:36:53
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {
    private final String rolePrefix = "ROLE_";
    private final RoleQuery roleQuery;
    private RoleCrud roleCrud;

    public RoleServiceImpl(RoleQuery roleQuery, RoleCrud roleCrud) {
        this.roleQuery = roleQuery;
        this.roleCrud = roleCrud;
    }

    @Override
    public void addOrModify(Role role) {
        String title = rolePrefix + role.getTitle();
        role.setTitle(title);
        roleCrud.save(role);
    }

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

        role.getMenus().clear();
        roleCrud.save(role);
        roleCrud.delete(role);
    }

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