/**
 * 
 */
package org.springblade.etl.service.bi;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springblade.etl.entity.bi.ReportDatasourcePermission;
import org.springblade.etl.mapper.ReportDatasourcePermissionMapper;
import org.springblade.system.client.DataPermClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author wookvn
 *
 */
@Service
public class ReportDatasourcePermissionService extends ServiceImpl<ReportDatasourcePermissionMapper, ReportDatasourcePermission> {

	@Autowired
	private DataPermClient dataPermClient;
	
	/**
	 * 处理表权限
	 * @param userId
	 * @param dsId
	 * @param consumer - 回调函数
	 */
	public void dealTablePermission(Long userId, Integer datasourceId, java.util.function.Consumer<Set<String>> consumer) {
		Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(userId);
		if(checkSuperPermRet == null || !checkSuperPermRet) {
			//查询有权限的用户
			QueryWrapper<ReportDatasourcePermission> queryWrapper = Wrappers.<ReportDatasourcePermission>query()
					.eq("b.user_id", userId).eq("a.datasource_id", datasourceId);
			List<ReportDatasourcePermission> permDataList = baseMapper.listPerm(queryWrapper);
			Set<String> dataSet = new HashSet<>();
			if(CollectionUtil.isNotEmpty(permDataList)) {
				permDataList.stream().filter(f -> StrUtil.isNotBlank(f.getTableNames())).forEach(t -> dataSet.addAll(JSON.parseArray(t.getTableNames(), String.class)));
			}
			consumer.accept(dataSet);
		}
	}
	
}
