package com.gitee.sop.admin.service.sys;

import com.gitee.sop.admin.common.support.ServiceSupport;
import com.gitee.sop.admin.dao.entity.SysRoleResource;
import com.gitee.sop.admin.dao.mapper.SysRoleResourceMapper;
import com.gitee.sop.admin.service.sys.dto.SysRoleResourceDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author 六如
 */
@Service
public class SysRoleResourceService implements ServiceSupport<SysRoleResource, SysRoleResourceMapper> {


    /**
     * 保存角色菜单配置
     *
     * @param sysRoleResourceDTO 入参
     * @return 返回影响行数
     */
    @Transactional(rollbackFor = Exception.class)
    public int saveRoleResource(SysRoleResourceDTO sysRoleResourceDTO) {
        Long roleId = sysRoleResourceDTO.getRoleId();
        // 删除之前的
        this.deleteByColumn(SysRoleResource::getRoleId, roleId);

        List<SysRoleResource> saveList = sysRoleResourceDTO.getResourceIds().stream()
                .map(resourceId -> {
                    SysRoleResource sysRoleResource = new SysRoleResource();
                    sysRoleResource.setRoleId(roleId);
                    sysRoleResource.setResourceId(resourceId);
                    sysRoleResource.setAddBy(sysRoleResourceDTO.getAddBy());
                    sysRoleResource.setUpdateBy(sysRoleResourceDTO.getAddBy());
                    return sysRoleResource;
                })
                .collect(Collectors.toList());

        return this.saveBatch(saveList);
    }

    public List<Long> listRoleResource(Long roleId) {
        return this.query()
                .eq(SysRoleResource::getRoleId, roleId)
                .listUniqueValue(SysRoleResource::getResourceId);
    }

    public List<Long> listRoleResource(Collection<Long> roleIds) {
        return this.query()
                .in(SysRoleResource::getRoleId, roleIds)
                .listUniqueValue(SysRoleResource::getResourceId);
    }

}
