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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.sys.dto.SysUserRelResourceDTO;
import com.patzn.lims.sys.entity.SysUserRelResource;
import com.patzn.lims.sys.mapper.SysUserRelResourceMapper;
import com.patzn.lims.sys.service.ISysUserRelResourceService;
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 2018-06-22
 */
@Service
public class SysUserRelResourceServiceImpl extends BaseServiceImpl<SysUserRelResourceMapper, SysUserRelResource> implements ISysUserRelResourceService {


    @Override
    public List<SysUserRelResource> list(Long userId) {
        return list(Wrappers.<SysUserRelResource>query().eq("user_id", userId).orderByAsc("sort"));
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean save(Long userId, SysUserRelResourceDTO dto) {
        if (null == dto || CollectionUtils.isEmpty(dto.getRelList())) {
            return false;
        }
        baseMapper.delete(Wrappers.<SysUserRelResource>query().eq("user_id", userId));
        return super.saveBatch(dto.getRelList().stream().map(d -> {
            SysUserRelResource rel = new SysUserRelResource();
            rel.setUserId(userId);
            rel.setResourceId(d.getResourceId());
            rel.setSort(d.getSort());
            rel.setDisplay(d.getDisplay());
            return rel;
        }).collect(toList()));
    }
}
