package com.patzn.lims.sys.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.sys.entity.SysRoleRelResource;
import com.patzn.lims.sys.mapper.SysRoleRelResourceMapper;
import com.patzn.lims.sys.service.ISysRoleRelResourceService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 角色资源关联表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2017-08-03
 */
@Service
public class SysRoleRelResourceServiceImpl extends BaseServiceImpl<SysRoleRelResourceMapper, SysRoleRelResource> implements ISysRoleRelResourceService {

    @Override
    public IPage<SysRoleRelResource> page(Page<SysRoleRelResource> page, SysRoleRelResource sysRoleRelResource) {
        return page(page, Wrappers.query(sysRoleRelResource));
    }

    @Override
    public List<SysRoleRelResource> list(SysRoleRelResource sysRoleRelResource) {
        return list(Wrappers.query(sysRoleRelResource));
    }

    @Override
    public List<SysRoleRelResource> getRelResource(Long roleId) {
        return list(Wrappers.<SysRoleRelResource>query()
                .select("resource_id").eq("role_id", roleId));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addRelResource(Long roleId, List<Long> resourceIds) {
        if (null == roleId || CollectionUtils.isEmpty(resourceIds)) {
            return false;
        }
        return baseMapper.delete(Wrappers.<SysRoleRelResource>query()
                .eq("role_id", roleId)) >= 0
                && saveBatch(resourceIds.stream().map(resourceId -> {
            SysRoleRelResource rel = new SysRoleRelResource();
            rel.setRoleId(roleId);
            rel.setResourceId(resourceId);
            return rel;
        }).collect(toList()));
    }
}
