package org.springblade.etl.controller.bi;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.CaseInsensitiveMap;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.base.Enums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.exception.ServiceException;
import org.springblade.datasource.context.DialectContext;
import org.springblade.datasource.enums.DsTypeEnum;
import org.springblade.datasource.model.TableColumnDto;
import org.springblade.datasource.model.TableViewDto;
import org.springblade.datasource.transform.ColumnEnum;
import org.springblade.datasource.transform.ColumnInfo;
import org.springblade.datasource.transform.RunnerLoadOne;
import org.springblade.datasource.transform.TransformContext;
import org.springblade.datasource.transform.general.GeneralEnum;
import org.springblade.datasource.transform.general.GeneralModel;
import org.springblade.etl.dto.ReportViewDTO;
import org.springblade.etl.dto.TableCategoryDTO;
import org.springblade.etl.dto.TransformColumnsDTO;
import org.springblade.etl.dto.TransformGeneralColumnsDTO;
import org.springblade.etl.dto.vo.ColumnInfoColumnEnumVO;
import org.springblade.etl.dto.vo.ColumnInfoGeneralEnumVO;
import org.springblade.etl.entity.*;
import org.springblade.etl.entity.bi.ReportDatasource;
import org.springblade.etl.service.*;
import org.springblade.etl.service.bi.ReportDatasourceService;
import org.springblade.etl.service.bi.TableCategoryRelationService;
import org.springblade.etl.service.bi.TableCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 产品报表基础信息 控制器
 *
 * @author BladeX
 * @since 2021-03-10
 */
@RestController
@RequestMapping("report/baseInfo")
@Api(value = "数据库表基础信息", tags = "数据库表基础信息 ReportBaseController")
@Slf4j
public class ReportBaseController extends BladeController {

//	@Resource
//	private IReportBaseInfoService reportBaseInfoService;

//	@Resource
//	private ReportBaseService reportBaseService;

    @Resource
    TransformContext transformContext;

//	@Autowired
//	private IReportDatasourcePermService reportDatasourcePermService;
//
//	@Autowired
//	private IReportDatasourceTablePermService reportDatasourceTablePermService;

//	@Autowired
//	private DataPermClient dataPermClient;

    //	@Resource
//	private BladeRedis bladeRedis;
    @Resource
    private ReportDatasourceService reportDatasourceService;

    @Autowired
    private DialectContext dialectContext;
    @Autowired
    private TableCategoryRelationService tableCategoryRelationService;
    @Autowired
    private TableCategoryService tableCategoryService;
    @Autowired
    private SqlColumnService sqlColumnService;
    @Autowired
    private EtlColumnSystemService etlColumnSystemService;
    @Autowired
    private QueryWrapperService queryWrapperService;

//    /**
//     * 获取报表视图
//     */
//    @GetMapping("/listViewsByDataSource")
//    @ApiOperationSupport(order = 1)
//    @ApiOperation(value = "根据数据源获取报表视图", notes = "")
////	@Cacheable(cacheNames = "baseInfo", key = "#datasourceId")
//    public R<IPage<TableCategoryDTO>> list(HttpServletRequest request,
//                                           @ApiParam("数据源Id") @RequestParam Integer datasourceId,
//                                           @ApiParam("分类id") @RequestParam(required = false) Integer classifyId,
//                                           @ApiParam("表名") @RequestParam(required = false) String tableName,
//                                           @ApiParam("分页参数") Query query) throws SQLException {
//        return R.data(getTableView(datasourceId, classifyId, tableName, query, getUser()));
//    }


//    /**
//     * 获取报表视图的字段信息
//     */
//    @GetMapping("/listColumnsByDatasource")
//    @ApiOperationSupport(order = 2)
//    @ApiOperation(value = "根据数据源获取报表视图的字段信息", notes = "")
////	@Cacheable(cacheNames = "baseInfo", key = "#reportViewDTO")
//    public R<List<TableColumnDto>> listColumnsByDatasource(ReportViewDTO reportViewDTO, HttpServletRequest request) throws ClassNotFoundException, SQLException {
//        String viewName = reportViewDTO.getTableViewName();
//        if (StrUtil.isAllBlank(viewName)) {
//            return R.fail("视图名称不可以为空");
//        }
//        ReportDatasource datasource = reportDatasourceService.getById(reportViewDTO.getDatasourceId());
//        if (null == datasource) {
//            return R.fail("数据源id错误");
//        }
////		List<ReportColumnDTO> list = reportBaseInfoService.selectReportColumnList(datasource, viewName);
//        List<TableColumnDto> list = dialectContext.getDialect(datasource.getDsTypeSyl()).listTableColumnsByTableViewName(datasource, viewName);
//        return R.data(list);
//    }

    /**
     * 获取报表视图的字段信息
     */
    @PostMapping("/transformColumns")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "源数据集字段类型翻译到目标数据集的字段类型", notes = "")
    public R<List<ColumnInfoColumnEnumVO>> transformColumns(@RequestBody TransformColumnsDTO dto) {
        List<GeneralModel> generalColumnList = dto.getGeneralColumnList();
        if (CollectionUtil.isEmpty(generalColumnList)) {
            return R.fail("转换字段不能为空!");
        }
        if (generalColumnList.stream().anyMatch(v -> v.getSourceColumn() == null || StrUtil.isBlank(v.getColumnName()) || StrUtil.isBlank(v.getType()))) {
            return R.fail("表字段信息缺少必要字段!");
        }
        generalColumnList.stream().forEach(v -> {
            if (!v.getSourceColumn() && !Enums.getIfPresent(GeneralEnum.class, v.getType().toUpperCase(Locale.ROOT)).isPresent()) {
                log.error("错误得通用转换模型字段类型!,GeneralModel:{}", JSONUtil.toJsonStr(v));
                throw new ServiceException("错误得通用转换模型字段类型:" + v.getType() + "!");
            }
        });
        //字段类别清洗
        List<GeneralModel> collect = generalColumnList.stream().map(v -> {
            if (v.getType().contains("UNSIGNED")) {
                v.setType(v.getType().replace(" UNSIGNED", ""));
            }
            return v;
        }).collect(Collectors.toList());

        ReportDatasource targetDatabase = reportDatasourceService.getById(dto.getTargetDatabase());
        List<SqlColumn> info = new ArrayList<>();

        Integer sourceDsType = dto.getSourceDsType();
        if (sourceDsType != null) {
            info = RunnerLoadOne.getInfo(sourceDsType);
            assert info != null;
            List<SqlColumn> finalInfo = info;
            collect.stream().forEach(v -> {
                if (v.getSourceColumn() && finalInfo.stream().noneMatch(v2 -> v2.getColumnType().equalsIgnoreCase(v.getType()))) {
                    log.error("转换模型源端字段类型错误!源类型,类型:{},GeneralModel:{}", DsTypeEnum.resolve(sourceDsType).name(), JSONUtil.toJsonStr(v));
                    throw new ServiceException("转换模型源端字段类型缺失!源类型:" + DsTypeEnum.resolve(sourceDsType).name() + ",字段类型:" + v.getType() + ",字段名称:" + v.getColumnName() + ",请联系管理员添加!");
                }
            });
        }

        List<ColumnInfo> columnInfos = transformContext.transformColumns(targetDatabase, collect, info);
        List<ColumnInfoColumnEnumVO> vos = columnInfos.stream().map(v -> {
            ColumnInfoColumnEnumVO c = new ColumnInfoColumnEnumVO();
            c.setColumnName(v.getColumnName());
            c.setColumnType(v.getColumnType());
            c.setColumnComments(v.getColumnComments());
            c.setColumnSize(v.getColumnSize());
            c.setDataType(v.getDataType());
            c.setDecimalDigits(v.getDecimalDigits());
            c.setNullAbleStatus(v.getNullAbleStatus());
            c.setDestColumnName(generalColumnList.stream().filter(v2 -> v2.getColumnName().equalsIgnoreCase(v.getColumnName())).findAny().orElse(new GeneralModel()).getDestColumnName());
            return c;
        }).collect(Collectors.toList());

        if (StrUtil.isNotEmpty(dto.getTargetTable())) {
            R<List<ColumnInfoColumnEnumVO>> result = determineGeneratedAndTargetTable(dto, targetDatabase, vos);
            if (result != null) return result;

        }
        return R.data(vos);
    }

    private R<List<ColumnInfoColumnEnumVO>> determineGeneratedAndTargetTable(TransformColumnsDTO dto, ReportDatasource targetDatabase, List<ColumnInfoColumnEnumVO> vos) {
        List<ColumnInfo> sourceColumn = transformContext.getSourceColumn(dto.getTargetTable(), targetDatabase);

        Map<String, ColumnInfoColumnEnumVO> map = vos.stream().collect(Collectors.toMap(ColumnInfoColumnEnumVO::getDestColumnName, v -> v, (a, b) -> a));
        CaseInsensitiveMap<String, ColumnInfoColumnEnumVO> caseInsensitiveMap = new CaseInsensitiveMap<>();
        caseInsensitiveMap.putAll(map);

        if (sourceColumn.size() != vos.size()) {
            return R.fail("生成表和目标表字段数量不符!");
        }
        for (ColumnInfo targetTable : sourceColumn) {
            ColumnInfoColumnEnumVO generatedTable = caseInsensitiveMap.get(targetTable.getColumnName());
            if (generatedTable == null) {
                String format = String.format("目标表字段= %s 不存在!", targetTable.getColumnName());
                return R.fail(format);
            }
            if (!generatedTable.getColumnType().equals(targetTable.getColumnType())) {
                String format = String.format("目标表和生成表字段类型不符!目标字段= %s ,字段类型= %s , 生成表字段= %s , 字段类型= %s",
                        targetTable.getColumnName(),
                        targetTable.getColumnType().name(),
                        generatedTable.getDestColumnName(),
                        generatedTable.getColumnType().name());
                return R.fail(format);
            }
            Integer columnSize = generatedTable.getColumnSize();
            if (targetDatabase.getDsType() == 1) {
                columnSize = columnSize / 2;
            }
            if (columnSize > targetTable.getColumnSize()) {
                String format = String.format("目标表字段长度小于生成表字段成都!目标字段= %s ,字段长度= %s , 生成表字段= %s , 字段长度= %s",
                        targetTable.getColumnName(),
                        targetTable.getColumnType().name(),
                        columnSize,
                        generatedTable.getColumnType().name());
                return R.fail(format);
            }
        }
        return null;
    }

    /**
     * 获取报表视图的字段信息
     */
    @PostMapping("/transformGeneralColumns")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "源数据集字段类型翻译到通用字段类型", notes = "")
    public R<List<ColumnInfoGeneralEnumVO>> transformGeneralColumns(@RequestBody TransformGeneralColumnsDTO dto) {
        Integer sourceDsType = dto.getSourceDsType();
        if (sourceDsType == null) {
            return R.fail("源数据库类型不能为空!");
        }
        List<GeneralModel> generalColumnList = dto.getGeneralColumnList();
        if (CollectionUtil.isEmpty(generalColumnList)) {
            return R.fail("转换字段不能为空!");
        }
        if (generalColumnList.stream().anyMatch(v -> v.getSourceColumn() == null || StrUtil.isBlank(v.getColumnName()) || StrUtil.isBlank(v.getType()))) {
            return R.fail("表字段信息缺少必要字段!");
        }
        generalColumnList.stream().forEach(v -> {
            if (!v.getSourceColumn() && !Enums.getIfPresent(GeneralEnum.class, v.getType().toUpperCase(Locale.ROOT)).isPresent()) {
                log.error("错误得通用转换模型字段类型!,GeneralModel:{}", JSONUtil.toJsonStr(v));
                throw new ServiceException("错误得通用转换模型字段类型:" + v.getType() + "!");
            }
        });
        //字段类别清洗
        List<GeneralModel> collect = generalColumnList.stream().map(v -> {
            if (v.getType().contains("UNSIGNED")) {
                v.setType(v.getType().replace(" UNSIGNED", ""));
            }
            return v;
        }).collect(Collectors.toList());

        List<SqlColumn> info = new ArrayList<>();
        info = RunnerLoadOne.getInfo(sourceDsType);
        List<SqlColumn> finalInfo = info;
        collect.stream().forEach(v -> {
            if (v.getSourceColumn() && finalInfo.stream().noneMatch(v2 -> v2.getColumnType().equalsIgnoreCase(v.getType()))) {
                log.error("转换模型源端字段类型错误!源类型,类型:{},GeneralModel:{}", DsTypeEnum.resolve(sourceDsType).name(), JSONUtil.toJsonStr(v));
                throw new ServiceException("转换模型源端字段类型缺失.源类型:" + DsTypeEnum.resolve(sourceDsType).name() + ",字段类型:" + v.getType() + ",字段名称:" + v.getColumnName() + ",请联系管理员添加!");
            }
        });

        List<ColumnInfo> columnInfos = transformContext.transformColumns(sourceDsType, collect, info);
        List<ColumnInfoGeneralEnumVO> vos = columnInfos.stream().map(v -> {
            ColumnInfoGeneralEnumVO c = new ColumnInfoGeneralEnumVO();
            c.setColumnName(v.getColumnName());
            c.setColumnType(ColumnEnumTransformGeneralEnum(v.getColumnType(), v.getColumnSize()));
            c.setColumnComments(v.getColumnComments());
            c.setColumnSize(v.getColumnSize());
            c.setDataType(v.getDataType());
            c.setDecimalDigits(v.getDecimalDigits());
            c.setNullAbleStatus(v.getNullAbleStatus());
            return c;
        }).collect(Collectors.toList());
        return R.data(vos);
    }

    private GeneralEnum ColumnEnumTransformGeneralEnum(ColumnEnum columnType, Integer columnSize) {
        switch (columnType) {
            case DECIMAL:
                return GeneralEnum.DECIMAL;
            case STRING:
                return GeneralEnum.STRING;
            case LONG:
                return GeneralEnum.BIGINT;
            case INTEGER:
                if (columnSize != null && columnSize < 2) {
                    return GeneralEnum.TINYINT;
                }
                return GeneralEnum.INT;
            case DOUBLE:
                return GeneralEnum.DOUBLE;
            case FLOAT:
                return GeneralEnum.FLOAT;
            case DATE:
                return GeneralEnum.DATE;
            default:
                return null;
        }
    }
//
//    public IPage<TableCategoryDTO> getTableView(Integer datasourceId, Integer classifyId, String tableName, Query query, BladeUser user) {
//        IPage<TableCategoryDTO> page = new Page<>();
//        page.setRecords(new ArrayList<>());
//        if (query.getSize() != null) {
//            page.setSize(query.getSize());
//        } else {
//            page.setSize(Integer.MAX_VALUE);
//        }
//        if (query.getCurrent() != null) {
//            page.setCurrent(query.getCurrent());
//        } else {
//            page.setCurrent(1);
//        }
//        page.setTotal(0);
//        page.setPages(0);
//
//        ReportDatasource datasource = reportDatasourceService.getById(datasourceId);
//        if (null == datasource) {
//            return page;
//        }
//        List<TableViewDto> list = dialectContext.getDialect(datasource.getDsTypeSyl()).listTableViewsByDatasource(datasource);
//        if (classifyId == null && StrUtil.isNotEmpty(tableName)) {
////            list = dialectContext.getDialect(datasource.getDsTypeSyl()).listTableViewsByDatasource(datasource, tableName);
//            list = list.stream().filter(tableViewDto -> tableViewDto.getTableViewName().contains(tableName)).collect(Collectors.toList());
//        }
////        if (CollectionUtil.isNotEmpty(list)) { //处理权限组
////            List<TableViewDto> finalList = list;
////            reportDatasourcePermissionService.dealTablePermission(user.getUserId(), datasourceId,
////                    permTableNameSet -> {
////                        if (permTableNameSet.isEmpty()) {
////                            finalList.clear();
////                        } else {
////                            finalList.removeIf(it -> !permTableNameSet.contains(it.getTableViewName()));
////                        }
////                    });
////        }
//        if ((classifyId == null || classifyId < 1)) {
//            if (CollectionUtil.isEmpty(list)) {
//                return null;
//            }
//            // 对查询结果进行分页
//            List<TableViewDto> subList = list;
//            if (query.getSize() == null || query.getSize() > list.size()) {
//                page.setSize(list.size());
//            }
//            if (query.getSize() != null && query.getSize() < list.size()) {
//                subList = list.stream().skip((query.getCurrent() - 1) * query.getSize()).limit(query.getSize()).
//                        collect(Collectors.toList());
//            }
//            List<TableCategoryDTO> tableCategorys = new ArrayList<>();
//            List<TableCategoryDTO> tableCategoryRelations = tableCategoryRelationService.getInfoByDatasourceId(datasourceId);
//            for (TableViewDto tableViewDto : subList) {
//                TableCategoryDTO tableCategoryDTO = BeanUtil.toBean(tableViewDto, TableCategoryDTO.class);
//                boolean bool = true;
//                for (TableCategoryDTO tableCategoryRelation : tableCategoryRelations) {
//                    if (tableCategoryRelation.getTableViewName().equals(tableViewDto.getTableViewName())) {
//                        tableCategorys.add(tableCategoryRelation);
//                        bool = false;
//                        break;
//                    }
//                }
//                if (bool) {
//                    tableCategorys.add(tableCategoryDTO);
//                }
//            }
//            page.setRecords(tableCategorys);
//            page.setTotal(list.size());
//            page.setPages(subList.size() % page.getSize());
//        }
//        // 如果分类id不为空且表名字为空
//        if (classifyId != null) {
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("category_id", classifyId);
//            if (StrUtil.isNotEmpty(tableName)) {
//                queryWrapper.like("table_view_name", tableName);
//            }
//            queryWrapper.orderByDesc("order_index");
//            Page<TableCategoryRelation> tableCategoryRelations = tableCategoryRelationService.page(new Page<>(page.getCurrent(), page.getSize()), queryWrapper);
//
//            //过滤需要权限访问的表
//            TableCategory tableCategory = tableCategoryService.getById(classifyId);
//
//            List<TableCategoryDTO> data = new ArrayList<>();
//            if (null != tableCategoryRelations && CollectionUtil.isNotEmpty(tableCategoryRelations.getRecords())) {
//                tableCategoryRelations.getRecords().forEach(tableCategoryRelation -> {
//                    TableCategoryDTO dto = new TableCategoryDTO();
//                    if (null != tableCategory) {
//                        dto.setCategoryName(tableCategory.getCategoryName());
//                        dto.setDatasourceId(tableCategory.getDatasourceId());
//                    }
//                    dto.setCategoryId(tableCategoryRelation.getCategoryId());
//                    dto.setOrderIndex(tableCategoryRelation.getOrderIndex());
//                    dto.setTableViewName(tableCategoryRelation.getTableViewName());
//                    dto.setTableComments(tableCategoryRelation.getTableComments());
//
//                    data.add(dto);
//                });
//            }
//            page.setTotal(tableCategoryRelations.getTotal());
//            page.setRecords(data);
//            page.setPages(tableCategoryRelations.getPages());
//        }
//        return page;
//    }

    @GetMapping("/get/sql-columns")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "查询字段映射列表", notes = "")
    public R<IPage<SqlColumn>> getSqlColumns(SqlColumn sqlColumn, Query query) {

//        Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(getUser().getUserId());
//        if (!checkSuperPermRet) {
//            throw new ServiceException("没有操作权限");
//        }
        String sqlColumnType = "";
        String columnType = "";
        if (StrUtil.isNotEmpty(sqlColumn.getSqlColumnType())) {
            sqlColumnType = sqlColumn.getSqlColumnType();
            sqlColumn.setSqlColumnType(null);
        }
        if (StrUtil.isNotEmpty(sqlColumn.getColumnType())) {

            columnType = sqlColumn.getColumnType();
            sqlColumn.setColumnType(null);
        }
        LambdaQueryWrapper<SqlColumn> queryWrapper = Condition.getQueryWrapper(sqlColumn).lambda().orderByAsc(SqlColumn::getDsType, SqlColumn::getSqlColumnType);
        queryWrapper.like(StrUtil.isNotEmpty(sqlColumnType), SqlColumn::getSqlColumnType, sqlColumnType);
        queryWrapper.like(StrUtil.isNotEmpty(columnType), SqlColumn::getColumnType, columnType);
        return R.data(sqlColumnService.page(Condition.getPage(query), queryWrapper));
    }

    @PostMapping("/save/sql-columns")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "保存字段映射关系", notes = "")
    public R<Integer> saveSqlColumns(@RequestBody SqlColumn sqlColumn) {

//        Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(getUser().getUserId());
//        if (!checkSuperPermRet) {
//            throw new ServiceException("没有操作权限");
//        }
        sqlColumnService.saveOrUpdateDo(sqlColumn);
        return R.data(sqlColumn.getId());
    }

    @PostMapping("/remove/sql-columns")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "删除字段映射关系", notes = "")
    public R<String> removeSqlColumns(@RequestBody List<Integer> ids) {

//        Boolean checkSuperPermRet = dataPermClient.checkSuperPermission(getUser().getUserId());
//        if (!checkSuperPermRet) {
//            throw new ServiceException("没有操作权限");
//        }

        return R.data(sqlColumnService.removeSqlColumns(ids));
    }

    @GetMapping("/get/system-columns")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "查询数据库保留字段", notes = "")
    public R<IPage<EtlColumnSystem>> page(EtlColumnSystem etlColumnSystem, Query query) {
        String name = "";
        if (StrUtil.isNotEmpty(etlColumnSystem.getName())) {
            name = etlColumnSystem.getName();
            etlColumnSystem.setName(null);
        }
        LambdaQueryWrapper<EtlColumnSystem> queryWrapper = Condition.getQueryWrapper(etlColumnSystem).lambda().orderByAsc(EtlColumnSystem::getDbType);
        queryWrapper.like(StrUtil.isNotEmpty(name), EtlColumnSystem::getName, name);
        return R.data(etlColumnSystemService.page(Condition.getPage(query), queryWrapper));
    }

//    @PostMapping("/save/system-columns")
//    @ApiOperationSupport(order = 8)
//    @ApiOperation(value = "保存数据库保留字段", notes = "")
//    public R<Integer> saveOrUpdate(@RequestBody EtlColumnSystem etlColumnSystem) {
//        etlColumnSystemService.saveOrUpdate(etlColumnSystem);
//        return R.data(etlColumnSystem.getId());
//    }

//    @PostMapping("/remove/system-columns")
//    @ApiOperationSupport(order = 9)
//    @ApiOperation(value = "删除数据库保留字段", notes = "")
//    public R<Boolean> saveOrUpdate(@RequestBody List<Integer> ids) {
//
//        return R.data(etlColumnSystemService.removeBatchByIds(ids));
//    }

    @GetMapping("/data-browser")
    @ApiOperation(value = "浏览数据", notes = "支持自定义分页")
    public R<IPage<Map<String, Object>>> dataBrowser(@RequestParam Integer datasourceId,
                                                     @RequestParam String tableName,
                                                     Query query) {
        String sqlStatement = "select * from " + tableName;
        ReportDatasource reportDatasource = reportDatasourceService.getById(datasourceId);
        if (reportDatasource == null) {
            return R.fail("数据源不存在");
        }
        if (reportDatasource.getDsTypeSyl() == DsTypeEnum.sqlserver) {  //SQLServer需要添加上schema查询
            String dbSchema = dialectContext.getDialect(reportDatasource.getDsTypeSyl()).dbSchema(reportDatasource);
            sqlStatement = "select * from " + dbSchema + "." + tableName;
        }
        return R.data(queryWrapperService.tempSelectPageList(new Page<>(query.getCurrent(), query.getSize()),
                reportDatasource, sqlStatement));
    }

    @GetMapping("/test-map")
    @ApiOperation(value = "测试map", notes = "测试map")
    public R<List<SqlColumn>> testMap() {

        return R.data(RunnerLoadOne.getInfo(0));
    }
}
