package cn.gintone.iotdbUtils;

import cn.gintone.config.IotDbConfig;
import cn.gintone.dto.JarDecLogInfo;
import cn.gintone.dto.SpePeoLogInfo;
import org.apache.iotdb.isession.pool.SessionDataSetWrapper;
import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.pool.SessionPool;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.file.metadata.enums.CompressionType;
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.read.common.Field;
import org.apache.tsfile.read.common.RowRecord;

import java.util.ArrayList;
import java.util.List;

public class JarDecLogIotDbUtil {

    public static void createJarDecLogInfoTimeseries(IotDbConfig iotDbConfig) {
        try {
            List<String> nodeUrls = new ArrayList<>();
            nodeUrls.add(iotDbConfig.getIp() + ":" + iotDbConfig.getPort());
            SessionPool sessionPool =
                    new SessionPool.Builder()
                            .nodeUrls(nodeUrls)
                            .user(iotDbConfig.getUsername())
                            .password(iotDbConfig.getPassword())
                            .maxSize(3)
                            .build();


            // 设置数据类型，设置默认编码模式，设置默认压缩模式
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.userId", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.username", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.sysAbbre", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.content", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.privateKey", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.clientIp", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.jarDecLog.type", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.close();
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    // 外部jar解密记录
    public static void inserOne(IotDbConfig iotDbConfig, JarDecLogInfo jarDecLogInfo) {
        if (null == jarDecLogInfo) {
            return;
        }
        try {
            List<String> nodeUrls = new ArrayList<>();
            nodeUrls.add(iotDbConfig.getIp() + ":" + iotDbConfig.getPort());
            SessionPool sessionPool =
                    new SessionPool.Builder()
                            .nodeUrls(nodeUrls)
                            .user(iotDbConfig.getUsername())
                            .password(iotDbConfig.getPassword())
                            .maxSize(3)
                            .build();

            List<String> list5 = new ArrayList<>();
            list5.add("userId");
            list5.add("username");
            list5.add("sysAbbre");
            list5.add("content");
            list5.add("privateKey");
            list5.add("clientIp");
            list5.add("type");

            List<TSDataType> list6 = new ArrayList<>();
            list6.add(TSDataType.TEXT);
            list6.add(TSDataType.TEXT);
            list6.add(TSDataType.TEXT);
            list6.add(TSDataType.TEXT);
            list6.add(TSDataType.TEXT);
            list6.add(TSDataType.TEXT);
            list6.add(TSDataType.TEXT);

            List<Object> values = new ArrayList<>();
            values.add(jarDecLogInfo.getUserId());
            values.add(jarDecLogInfo.getUsername());
            values.add(jarDecLogInfo.getSysAbbre());
            values.add(jarDecLogInfo.getContent());
            values.add(jarDecLogInfo.getPrivateKey());
            values.add(jarDecLogInfo.getClientIp());
            values.add(jarDecLogInfo.getType());
            sessionPool.insertRecord("root.myDecFileLogInfo.jarDecLog", System.currentTimeMillis(), list5, list6, values);
            sessionPool.close();
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询总条数
     * @param iotDbConfig
     * @param jarDecLogInfo
     * @return
     */
    public static long countSpeLogInfo(IotDbConfig iotDbConfig, JarDecLogInfo jarDecLogInfo) {
        long num = 0;
        try {
            List<String> nodeUrls = new ArrayList<>();
            nodeUrls.add(iotDbConfig.getIp() + ":" + iotDbConfig.getPort());
            SessionPool sessionPool =
                    new SessionPool.Builder()
                            .nodeUrls(nodeUrls)
                            .user(iotDbConfig.getUsername())
                            .password(iotDbConfig.getPassword())
                            .maxSize(3)
                            .build();


            StringBuffer sb = new StringBuffer();
            sb.append("select count(userId) from root.myDecFileLogInfo.jarDecLog");
            if ((null != jarDecLogInfo.getEndTime() && 0 != jarDecLogInfo.getEndTime())
                    || (null != jarDecLogInfo.getBeginTime() && 0 != jarDecLogInfo.getBeginTime())) {
                sb.append(" where");
                boolean needAnd = false;
                if (null != jarDecLogInfo.getEndTime() && 0 != jarDecLogInfo.getEndTime() ) {
                    needAnd = true;
                    sb.append(" time <= "+ jarDecLogInfo.getEndTime());
                }
                if (null != jarDecLogInfo.getBeginTime() && 0 != jarDecLogInfo.getBeginTime()) {
                    if (needAnd) {
                        sb.append(" and");
                    }
                    needAnd = true;
                    sb.append(" time >= "+ jarDecLogInfo.getBeginTime());

                }
            }
            String sql = sb.toString();
            System.out.println(sql);
            SessionDataSetWrapper sessionDataSetWrapper = sessionPool.executeQueryStatement(sql);
            List<String> columnNames = sessionDataSetWrapper.getColumnNames();
            System.out.println(columnNames);
            while (sessionDataSetWrapper.hasNext()) {
                RowRecord next = sessionDataSetWrapper.next(); // 取出一行数据
                long timestamp = next.getTimestamp(); // 获取这行的时间戳
                List<Field> fields = next.getFields();
                Field field0 = fields.get(0);
                num = field0.getLongV();
            }

            sessionPool.close();
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }

        return num;
    }

    public static List<JarDecLogInfo> selectJarDecLogInfo(IotDbConfig iotDbConfig, JarDecLogInfo jarDecLogInfo) {
        List<JarDecLogInfo> jarDecLogInfoList = new ArrayList<>();
        try {
            List<String> nodeUrls = new ArrayList<>();
            nodeUrls.add(iotDbConfig.getIp() + ":" + iotDbConfig.getPort());
            SessionPool sessionPool =
                    new SessionPool.Builder()
                            .nodeUrls(nodeUrls)
                            .user(iotDbConfig.getUsername())
                            .password(iotDbConfig.getPassword())
                            .maxSize(3)
                            .build();

            int offsetNum = (jarDecLogInfo.getPageNum() - 1) * jarDecLogInfo.getPageSize();
            int limitNum = jarDecLogInfo.getPageSize();
            StringBuffer sb = new StringBuffer();
            sb.append("select userId, username, sysAbbre, content, privateKey, clientIp, type from root.myDecFileLogInfo.jarDecLog");
            if ((null != jarDecLogInfo.getEndTime() && 0 != jarDecLogInfo.getEndTime())
                    || (null != jarDecLogInfo.getBeginTime() && 0 != jarDecLogInfo.getBeginTime())) {
                sb.append(" where");
                boolean needAnd = false;
                if (null != jarDecLogInfo.getEndTime() && 0 != jarDecLogInfo.getEndTime() ) {
                    needAnd = true;
                    sb.append(" time <= "+ jarDecLogInfo.getEndTime());
                }
                if (null != jarDecLogInfo.getBeginTime() && 0 != jarDecLogInfo.getBeginTime()) {
                    if (needAnd) {
                        sb.append(" and");
                    }
                    needAnd = true;
                    sb.append(" time >= "+ jarDecLogInfo.getBeginTime());

                }
            }
            sb.append(" order by time desc offset " + offsetNum + " limit " + limitNum);
            String sql = sb.toString();
            System.out.println(sql);
            SessionDataSetWrapper sessionDataSetWrapper = sessionPool.executeQueryStatement(sql);
            List<String> columnNames = sessionDataSetWrapper.getColumnNames();
            System.out.println(columnNames);
            while (sessionDataSetWrapper.hasNext()) {
                RowRecord next = sessionDataSetWrapper.next(); // 取出一行数据
                long timestamp = next.getTimestamp(); // 获取这行的时间戳
                List<Field> fields = next.getFields();
                Field field0 = fields.get(0);
                String userId = field0.getStringValue();
                Field field1 = fields.get(1);
                String username = field1.getStringValue();
                Field field2 = fields.get(2);
                String sysAbbre = field2.getStringValue();
                Field field3 = fields.get(3);
                String content = field3.getStringValue();
                Field field4 = fields.get(4);
                String privateKey = field4.getStringValue();
                Field field5 = fields.get(5);
                String clientIp = field5.getStringValue();
                Field field6 = fields.get(6);
                String type = field6.getStringValue();

                JarDecLogInfo jdlInfo = new JarDecLogInfo();
                jdlInfo.setTimesta(timestamp);
                jdlInfo.setTimestaStr(MyDateUtils.longToString(timestamp));
                jdlInfo.setUserId(userId);
                jdlInfo.setUsername(username);
                jdlInfo.setSysAbbre(sysAbbre);
                jdlInfo.setContent(content);
//                splInfo.setPrivateKey(privateKey);
                jdlInfo.setClientIp(clientIp);
                jdlInfo.setType(type);
                jarDecLogInfoList.add(jdlInfo);
            }

            sessionPool.close();
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }

        return jarDecLogInfoList;
    }
}
