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

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springblade.datasource.support.DynamicDataSourceSupport;
import org.springblade.etl.entity.bi.ReportDatasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class QueryWrapperService {

	@Autowired
	private QueryService queryService;
	
	@Autowired
	private DynamicDataSourceSupport dynamicDataSourceSupport;
	
	public List<Map<String, Object>> select(ReportDatasource ds, String sql) {
		if(!dynamicDataSourceSupport.exists(ds.getPoolName())) {
			dynamicDataSourceSupport.addDs(ds);
		}
		return queryService.select(ds.getPoolName(), sql);
	}
	
	public List<Map<String, Object>> selectPageList(IPage<?> page, ReportDatasource ds, String sql) {
		if(!dynamicDataSourceSupport.exists(ds.getPoolName())) {
			dynamicDataSourceSupport.addDs(ds);
		}
		return queryService.selectPageList(page, ds.getPoolName(), sql);
	}
	
	public IPage<Map<String, Object>> selectPage(IPage<?> page, ReportDatasource ds, String sql) {
		if(!dynamicDataSourceSupport.exists(ds.getPoolName())) {
			dynamicDataSourceSupport.addDs(ds);
		}
		return queryService.selectPage(page, ds.getPoolName(), sql);
	}
	
	/**
	 * 临时查询
	 * @param ds
	 * @param sql
	 * @return
	 */
	public Map<String, Object> tempSelectOne(ReportDatasource ds, String sql) {
		if(!dynamicDataSourceSupport.exists(ds.getPoolName())) {
			dynamicDataSourceSupport.addDs(ds);
		}
		try {
			return queryService.selectOne(ds.getPoolName(), sql);
		} finally {
			try {
				dynamicDataSourceSupport.removeDs(ds.getPoolName());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		}
	}

	public IPage<Map<String, Object>> tempSelectPageList(IPage<?> page, ReportDatasource ds, String sql) {
		if(!dynamicDataSourceSupport.exists(ds.getPoolName())) {
			dynamicDataSourceSupport.addDs(ds);
		}
		try {
			return queryService.selectPage(page, ds.getPoolName(), sql);
		}  finally {
			try {
				dynamicDataSourceSupport.removeDs(ds.getPoolName());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
			}
		}
	}
}
