package cn.gintone.iotdbUtils;

import cn.gintone.config.IotDbConfig;
import cn.gintone.dto.FileDecLogInfo;
import cn.gintone.dto.WebIllLogInfo;
import cn.gintone.dto.WebLogInfo;
import cn.gintone.dto.WebLogInfoVo;
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 FileIotDbUtil {

    public static void createFileLogInfoTimeseries(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.decFileLog.userId", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.username", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.sysAbbre", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.content", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.privateKey", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.clientIp", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.fileName", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.createTimeseries("root.myDecFileLogInfo.decFileLog.fileId", TSDataType.TEXT, TSEncoding.PLAIN, CompressionType.UNCOMPRESSED);
            sessionPool.close();
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        }
    }
    // 重要文件解密记录记录
    public static void inserOne(IotDbConfig iotDbConfig, FileDecLogInfo fileDecLogInfo) {
        if (null == fileDecLogInfo) {
            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("fileName");
            list5.add("fileId");

            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);
            list6.add(TSDataType.TEXT);

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


    /**
     * 查询总条数
     * @param iotDbConfig
     * @param fileDecLogInfo
     * @return
     */
    public static long countDecFileInfo(IotDbConfig iotDbConfig, FileDecLogInfo fileDecLogInfo) {
        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.decFileLog");
            if ((null != fileDecLogInfo.getEndTime() && 0 != fileDecLogInfo.getEndTime())
                    || (null != fileDecLogInfo.getBeginTime() && 0 != fileDecLogInfo.getBeginTime())) {
                sb.append(" where");
                boolean needAnd = false;
                if (null != fileDecLogInfo.getEndTime() && 0 != fileDecLogInfo.getEndTime() ) {
                    needAnd = true;
                    sb.append(" time <= "+ fileDecLogInfo.getEndTime());
                }
                if (null != fileDecLogInfo.getBeginTime() && 0 != fileDecLogInfo.getBeginTime()) {
                    if (needAnd) {
                        sb.append(" and");
                    }
                    needAnd = true;
                    sb.append(" time >= "+ fileDecLogInfo.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<FileDecLogInfo> selectDecFileInfo(IotDbConfig iotDbConfig, FileDecLogInfo fileDecLogInfo) {
        List<FileDecLogInfo> fileDecLogInfoList = 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 = (fileDecLogInfo.getPageNum() - 1) * fileDecLogInfo.getPageSize();
            int limitNum = fileDecLogInfo.getPageSize();
            StringBuffer sb = new StringBuffer();
            sb.append("select userId, username, sysAbbre, content, privateKey, clientIp, fileName, fileId from root.myDecFileLogInfo.decFileLog");
            if ((null != fileDecLogInfo.getEndTime() && 0 != fileDecLogInfo.getEndTime())
                    || (null != fileDecLogInfo.getBeginTime() && 0 != fileDecLogInfo.getBeginTime())) {
                sb.append(" where");
                boolean needAnd = false;
                if (null != fileDecLogInfo.getEndTime() && 0 != fileDecLogInfo.getEndTime() ) {
                    needAnd = true;
                    sb.append(" time <= "+ fileDecLogInfo.getEndTime());
                }
                if (null != fileDecLogInfo.getBeginTime() && 0 != fileDecLogInfo.getBeginTime()) {
                    if (needAnd) {
                        sb.append(" and");
                    }
                    needAnd = true;
                    sb.append(" time >= "+ fileDecLogInfo.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 fileName = field6.getStringValue();
                Field field7 = fields.get(7);
                String fileId = field7.getStringValue();

                FileDecLogInfo fdlInfo = new FileDecLogInfo();
                fdlInfo.setTimesta(timestamp);
                fdlInfo.setTimestaStr(MyDateUtils.longToString(timestamp));
                fdlInfo.setUserId(userId);
                fdlInfo.setUsername(username);
                fdlInfo.setSysAbbre(sysAbbre);
                fdlInfo.setContent(content);
//                fdlInfo.setPrivateKey(privateKey);
                fdlInfo.setClientIp(clientIp);
                fdlInfo.setFileName(fileName);
                fdlInfo.setFileId(Integer.parseInt(fileId));
                fileDecLogInfoList.add(fdlInfo);
            }

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

        return fileDecLogInfoList;
    }
}
