package com.njcn.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njcn.user.mapper.RoleComponentMapper;
import com.njcn.user.pojo.param.RoleParam;
import com.njcn.user.pojo.po.RoleComponent;
import com.njcn.user.service.IRoleComponentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2021-12-13
 */
@Service
public class RoleComponentServiceImpl extends ServiceImpl<RoleComponentMapper, RoleComponent> implements IRoleComponentService {

    @Override
    public List<String> selectRoleComponent(List<String> idList) {
        return this.lambdaQuery().in(RoleComponent::getRoleId,idList).list().stream().map(RoleComponent::getComponentId).collect(Collectors.toList());
    }

    @Override
    public boolean updateRoleComponent(RoleParam.RoleFunctionComponent roleFunctionComponent) {
        deleteComponentsByRoleIndex(roleFunctionComponent.getId());
        if (!roleFunctionComponent.getIdList().isEmpty()){
            RoleComponent roleComponent = new RoleComponent();
            roleComponent.setRoleId(roleFunctionComponent.getId());
            roleFunctionComponent.getIdList().forEach(
                    pojo->{
                        roleComponent.setComponentId(pojo);
                        this.baseMapper.insert(roleComponent);
                    });
        }
        return true;
    }

    /**
     * 根据角色删除组件
     * @param roleIndex 角色索引
     */
    public boolean deleteComponentsByRoleIndex(String roleIndex) {
        QueryWrapper<RoleComponent> roleComponentQueryWrapper = new QueryWrapper<>();
        roleComponentQueryWrapper.eq("sys_role_component.role_id",roleIndex);
        int row = this.baseMapper.delete(roleComponentQueryWrapper);
        return row > 0;
    }
}
