package net.tccn.dbq;

import net.tccn.base.MetaKit;
import net.tccn.base.PageBean;
import net.tccn.dbq.fbean.FBean;
import net.tccn.dbq.jdbc.api.DbKit;
import net.tccn.dbq.parser.ParseMysql;
import net.tccn.dbq.parser.Parser;
import net.tccn.meta.MetaService;
import net.tccn.meta.MetaTable;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class DbExecutors {
    private final static Parser PARSER = new ParseMysql();

    public static PageBean findPage(FBean fBean) throws ExecutionException, InterruptedException {
        //sql解析
        String[] sqls = PARSER.parse(fBean);

        //当前的业务 => 获取主表 信息 => 数据源信息 => 数据源对象  => 创建数据工具对象 => 查询数据
        MetaService metaService = MetaKit.getMetaService(fBean.getName(), fBean.getPlatToken());

        MetaTable mainTable = MetaKit.getMetaTableByAlias(metaService.getTable());

        DbKit dbKit = MetaKit.getDbKit(mainTable.getDbPlatId());
        //System.out.printf("----------------%n countSql:%s%n findSql:%s%n----------------%n", sqls[0], sqls[1]);

        CompletableFuture<Integer> countFuture = CompletableFuture.supplyAsync(() -> dbKit.queryColumn(sqls[0], int.class));
        CompletableFuture<List<Map>> listFuture = CompletableFuture.supplyAsync(() -> dbKit.findList(sqls[1], Map.class));

        return PageBean.by(listFuture.get(), countFuture.get());
    }
}
