package com.dcs.framework.config;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.QueryApi;
import com.influxdb.client.WriteApiBlocking;
import com.influxdb.client.domain.WritePrecision;
import com.influxdb.client.write.Point;
import com.influxdb.query.FluxTable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static com.dcs.common.utils.Threads.sleep;

/**
 * InfluxDB配置类
 *
 * @author: wangpx
 * @date: 2025-03-04 13:40
 */
@Component
public class InfluxDBConfig {
    @Value("${dcs.influxdb.url}")
    private String url;

    @Value("${dcs.influxdb.token}")
    private String token;

    @Value("${dcs.influxdb.org}")
    private String org;

    // 使用 Map 存储不同 bucket 的 InfluxDBClient 实例，确保一个 bucket 只创建一个实例
    private static final Map<String, InfluxDBClient> clientPool = new ConcurrentHashMap<>();

    /**
     * 获取指定 bucket 的 InfluxDBClient，如果不存在则创建
     */
    public InfluxDBClient getClient(String bucket) {
        return clientPool.computeIfAbsent(bucket, b -> {
            System.out.println("创建 InfluxDBClient 实例，bucket=" + b);
            return InfluxDBClientFactory.create(url, token.toCharArray(), org, b);
        });
    }

    /**
     * 关闭指定 bucket 的客户端
     */
    public void closeClient(String bucket) {
        InfluxDBClient client = clientPool.remove(bucket);
        if (client != null) {
            client.close();
        }
    }

    /**
     * 关闭所有客户端
     */
    public void closeAllClients() {
        clientPool.values().forEach(InfluxDBClient::close);
        clientPool.clear();
    }

    //        String tokenTest = "Iku7nvYiCTt-WUAR0dkCEt_w8q4kCgOdUrMTE21m4shWC1SMJIU9vPoB1u_8TQ_HJGMEc3Ej_s54JvySaaRt-g==";
    static String tokenTest = "TnFc4ypsHK6ZKxQW9IiOKUPEZQXGJ9lHn4d-V2wJvis1Qk4Xlo7X_AZLUCrFSdSUfUwOeqR5iRfR3rK6Rn5SDg==";
    static String bucketTest = "mybucket";
    static String orgTest = "myorg";
    private static void test1(InfluxDBClient client) {
        List<Point> points = new ArrayList<>();
        WriteApiBlocking writeApi = client.getWriteApiBlocking();
        for (int i = 0; i < 10; i++) {
            Point point = new Point("dcs");
            point.time(System.currentTimeMillis(), WritePrecision.MS);
            point.addTag("equipment_name", "F1 - 搅拌机");
            point.addField("rpm", 110 * (i + 1));
            point.addField("time", 11 * (i + 1));
            points.add(point);
            sleep(1000);
        }
        writeApi.writePoints(points);
    }

    private static void test2(InfluxDBClient client) {
        QueryApi queryApi = client.getQueryApi();
        String fluxQuery = "from(bucket: \"mybucket\")\n" +
                "  |> range(start: -12h)\n" +
                "  |> filter(fn: (r) => r[\"_measurement\"] == \"dcs\")\n" + 
                "  |> filter(fn: (r) => r[\"_field\"] == \"time\" or r[\"_field\"] == \"rpm\")\n" +
                "  |> filter(fn: (r) => r[\"equipment_name\"] == \"F1 - 搅拌机\")";
        List<FluxTable> tables = queryApi.query(fluxQuery);
        System.out.println(tables);
    }

    public static void main(String[] args) {
        InfluxDBClient client = InfluxDBClientFactory.create("http://127.0.0.1:8086", tokenTest.toCharArray(), orgTest, bucketTest);
        test1(client);
    }
}
