package net.tccn.base.dbq;

import net.tccn.base.Kv;
import net.tccn.base.MetaKit;
import net.tccn.base.PageBean;
import net.tccn.base.dbq.fbean.FBean;
import net.tccn.base.dbq.jdbc.api.DbKit;
import net.tccn.base.dbq.parser.ParseMysql;
import net.tccn.meta.MService;
import net.tccn.meta.MTable;

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

/**
 * Db 调度层
 */
public class DbExecutors {
    private final static ParseMysql PARSER = new ParseMysql();

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

        //当前的业务 => 获取主表 信息 => 数据源信息 => 数据源对象  => 创建数据工具对象 => 查询数据
        MService metaService = MetaKit.getMetaService(fBean.getName(), fBean.getPlattoken());
        MTable mainTable = MetaKit.getMetaTableByAlias(metaService.getTablealias());
        DbKit dbKit = MetaKit.getDbKit(mainTable.getDbid(), mainTable.getCatalog());
        System.out.printf("----------------%n countSql:%s%n findSql:%s%n----------------%n", sqls[0], sqls[1]);

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

        List<Map> rows = listFuture.get();
        Integer total = countFuture.get();

        rows.forEach(m -> {
            m.forEach((k, v) -> {
                /*if ("[B".equals(v.getClass().getName())) {
                    try {
                        //System.out.println(k + " : " + new String((byte[]) v, "UTF-8"));
                        m.put(k, new String((byte[]) v, "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }*/
                // 避免前端 解析丢失精度
                if (v instanceof Long && (Long) v > 9007199254740991L) {
                    m.put(k, Kv.toAs(v, String.class));
                }
            });
        });
        return PageBean.by(rows, total);
    }

    /*public static void del(String name, Map data, String token) {
        MService metaService = MetaKit.getMetaService(name, token);
        MTable mainTable = MetaKit.getMetaTableByAlias(metaService.getTablealias());
        DbKit dbKit = MetaKit.getDbKit(mainTable.getDbid(), mainTable.getCatalog());

        String delSql = PARSER.parseDel(name, data, token);
        dbKit.exetute(delSql);
    }*/

    public static void save(String name, Map data, String token) {
        MTable mainTable = MetaKit.getMainTable(name, token);
        DbKit dbKit = MetaKit.getDbKit(mainTable.getDbid(), mainTable.getCatalog());

        String sql = PARSER.parseSave(name, data, token);
        dbKit.exetute(sql);
    }
}
