package com.muyu.carData.config.lotdbconfig;

import org.apache.iotdb.rpc.IoTDBConnectionException;
import org.apache.iotdb.rpc.StatementExecutionException;
import org.apache.iotdb.session.Session;
import org.apache.iotdb.session.SessionDataSet;
import org.apache.iotdb.session.pool.SessionPool;
import org.apache.iotdb.tsfile.read.common.Field;
import org.apache.iotdb.tsfile.read.common.RowRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

/**
 * @Author：张腾
 * @Package：com.muyu.carData.lotdbconfig
 * @Project：cloud-server-8
 * @name：IotDBSessionConfig
 * @Date：2024/9/27 12:25
 * IotDB线程池
 */
@Component
@Configuration
public class IotDBSessionConfig {

    private static Logger logger = LoggerFactory.getLogger(IotDBSessionConfig.class);

    /**
     * 用户名
     */
    @Value("${spring.iotdb.username}")
    private String username;

    /**
     * 密码
     */
    @Value("${spring.iotdb.password}")
    private String password;

    /**
     * ip地址
     */
    @Value("${spring.iotdb.ip}")
    private String ip;

    /**
     * 端口号
     */
    @Value("${spring.iotdb.port}")
    private Integer port;

    /**
     * 最大连接数
     */
    @Value("${spring.iotdb.maxSize}")
    private Integer maxSize;


    /**
     * 默认每次查询的条数
     */
    @Value("${spring.iotdb.fetchSize}")
    private int fetchSize;


    @Bean
    public Session iotSession(){
        Session session = new Session(ip, port, username, password);
        try {
            session.open();
        } catch (IoTDBConnectionException e) {
            logger.error(String.valueOf(e.getCause()));
        }
        return session;
    }


    /**
     * 添加操作
     * @param deviceId
     * @param time 时间戳
     * @param measurements
     * @param values 值
     */
    public void execute(String deviceId,long time,List<String> measurements,List<String> values){
        if (CollectionUtils.isEmpty(measurements) && !CollectionUtils.isEmpty(values)){
            try {
                iotSession().insertAlignedRecord(deviceId,time,measurements,values);
            } catch (IoTDBConnectionException e) {
                throw new RuntimeException(e);
            } catch (StatementExecutionException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 查询操作
     * @param sql
     * @return
     */
    public List<HashMap<String,Object>> executeQuery(String sql){
        logger.info("sql:{}",sql);
        List<HashMap<String,Object>> list = new ArrayList<>();

        try {
            SessionDataSet sessionDataSet = iotSession().executeQueryStatement(sql);
            int fetchSize = sessionDataSet.getFetchSize();
            List<String> columnNames = sessionDataSet.getColumnNames();
            logger.info("columnNames:{}",columnNames);
            List<String> columnTypes = sessionDataSet.getColumnTypes();
            logger.info("columnTypes:{}",columnTypes);
            if (fetchSize > 0){
                while (sessionDataSet.hasNext()){
                    HashMap<String, Object> map = new HashMap<>();
                    RowRecord next = sessionDataSet.next();
                    List<Field> fields = next.getFields();
                    for (int i = 0; i < fields.size(); i++) {
                        Field field = fields.get(i);
                        String key = field.getStringValue();
                        Object value = field.getObjectValue(field.getDataType());
                        map.put(key,value);
                    }
                    list.add(map);
                }

                sessionDataSet.closeOperationHandle();
            }
        } catch (StatementExecutionException e) {
            throw new RuntimeException(e);
        } catch (IoTDBConnectionException e) {
            throw new RuntimeException(e);
        }

        return list;
    }








}
