package com.common.service;

 import com.influx.InfluxDBClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;
 import java.util.ArrayList;
 import org.springframework.util.CollectionUtils;
 import java.util.Collections;
 import java.util.HashMap;

@Slf4j
@Service
public class InfluxSyslogService {

    //@Autowired
    //private InfluxDBClient influxDBClient;
    // 初始化 InfluxDB 客户端
    //@Autowired
    private final com.influx.InfluxDBClient influxDBClient  = new InfluxDBClient();

    private static final DateTimeFormatter TABLE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter INPUT_DATE_FORMATTER = DateTimeFormatter.ISO_DATE_TIME;

    /**
     * 接口1：按时间范围查询（最长一天）
     */
    public List<Map<String, Object>> queryByTimeRange(String startTime, String endTime) {
        try {
            Instant start = parseInstant(startTime);
            Instant end = parseInstant(endTime);

            validateTimeRange(start, end);

            // 生成需要查询的表名（处理跨天情况）
            List<String> measurementNames = generateMeasurementNames(start, end);
            List<Map<String, Object>> allResults = new ArrayList<>();

            for (String measurement : measurementNames) {
                List<Map<String, Object>> results = influxDBClient.queryByTimeRange(measurement, start, end);
                allResults.addAll(results);
            }

            log.info("按时间范围查询成功，查询表: {}, 返回记录数: {}", measurementNames, allResults.size());
            return allResults;

        } catch (Exception e) {
            log.error("按时间范围查询失败: {}", e.getMessage());
            throw new RuntimeException("查询失败: " + e.getMessage(), e);
        }
    }

    /**
     * 接口2：按UUID查询详细日志
     */
    public List<Map<String, Object>> queryByUuid(String uuid) {
        try {
            // 从UUID中提取日期部分
            String datePart = extractDateFromUuid(uuid);
            String measurement = "syslog_security_" + datePart;

            List<Map<String, Object>> results = influxDBClient.queryByUuid(measurement, uuid);

            log.info("按UUID查询成功，表: {}, UUID: {}, 返回记录数: {}", measurement, uuid, results.size());
            return results;

        } catch (Exception e) {
            log.error("按UUID查询失败: {}", e.getMessage());
            throw new RuntimeException("查询失败: " + e.getMessage(), e);
        }
    }



    /**
     * 接口3：按设备ID和时间范围查询
     */
    public List<Map<String, Object>> queryByDeviceIdAndTime(String deviceId, String startTime, String endTime) {
        try {
            Instant start = parseInstant(startTime);
            Instant end = parseInstant(endTime);

            validateTimeRange(start, end);

            List<String> measurementNames = generateMeasurementNames(start, end);
            List<Map<String, Object>> allResults = new ArrayList<>();

            for (String measurement : measurementNames) {
                List<Map<String, Object>> results = influxDBClient.queryByDeviceIdAndTime(measurement, deviceId, start, end);
                allResults.addAll(results);
            }

            log.info("按设备ID查询成功，设备: {}, 返回记录数: {}", deviceId, allResults.size());
            return allResults;

        } catch (Exception e) {
            log.error("按设备ID查询失败: {}", e.getMessage());
            throw new RuntimeException("查询失败: " + e.getMessage(), e);
        }
    }

    /**
     * 接口4：模糊查询message内容
     */
    public List<Map<String, Object>> queryByMessageContent(String startTime, String endTime, String keyword) {
        try {
            Instant start = parseInstant(startTime);
            Instant end = parseInstant(endTime);

            validateTimeRange(start, end);
            validateKeyword(keyword);

            List<String> measurementNames = generateMeasurementNames(start, end);
            List<Map<String, Object>> allResults = new ArrayList<>();

            for (String measurement : measurementNames) {
                List<Map<String, Object>> results = influxDBClient.queryByMessageContent(measurement, start, end, keyword);
                allResults.addAll(results);
            }

            log.info("模糊查询成功，关键字: {}, 返回记录数: {}", keyword, allResults.size());
            return allResults;

        } catch (Exception e) {
            log.error("模糊查询失败: {}", e.getMessage());
            throw new RuntimeException("查询失败: " + e.getMessage(), e);
        }
    }
    public Map<String, List<Map<String, Object>>> queryByUuids(List<String> uuids) {
        if (CollectionUtils.isEmpty(uuids)) {
            return Collections.emptyMap();
        }
        Map<String, List<Map<String, Object>>> resultMap = new HashMap<>();
        for (String uuid : uuids) {
            // 查询单个UUID的日志
            List<Map<String, Object>> logList = queryByUuid(uuid);
            resultMap.put(uuid, logList);
        }
        return resultMap;
    }
    /**
     * 从UUID中提取日期部分
     */
    private String extractDateFromUuid(String uuid) {
        if (uuid == null || uuid.length() < 8) {
            throw new IllegalArgumentException("UUID格式不正确，无法提取日期");
        }
        return uuid.substring(0, 8);
    }

    /**
     * 解析时间字符串为Instant
     */
    private Instant parseInstant(String timeString) {
        try {
            return Instant.parse(timeString);
        } catch (Exception e) {
            throw new IllegalArgumentException("时间格式不正确，请使用ISO格式，例如: 2023-11-20T00:00:00Z");
        }
    }

    /**
     * 验证时间范围（最长一天）
     */
    private void validateTimeRange(Instant start, Instant end) {
        long hours = ChronoUnit.HOURS.between(start, end);
        if (hours > 24) {
            throw new IllegalArgumentException("查询时间范围不能超过24小时");
        }
        if (start.isAfter(end)) {
            throw new IllegalArgumentException("开始时间不能晚于结束时间");
        }
    }

    /**
     * 验证搜索关键字
     */
    private void validateKeyword(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            throw new IllegalArgumentException("搜索关键字不能为空");
        }
        if (keyword.length() > 32) {
            throw new IllegalArgumentException("搜索关键字长度不能超过32个字符");
        }
    }

    /**
     * 生成需要查询的表名列表（处理跨天情况）
     */
    private List<String> generateMeasurementNames(Instant start, Instant end) {
        List<String> measurements = new ArrayList<>();

        LocalDateTime startDate = LocalDateTime.ofInstant(start, ZoneId.of("UTC"));
        LocalDateTime endDate = LocalDateTime.ofInstant(end, ZoneId.of("UTC"));

        LocalDateTime currentDate = startDate;
        while (!currentDate.toLocalDate().isAfter(endDate.toLocalDate())) {
            String dateStr = currentDate.format(TABLE_DATE_FORMATTER);
            measurements.add("syslog_security_" + dateStr);
            currentDate = currentDate.plusDays(1);
        }

        return measurements;
    }
}