package com.common.service;



import com.common.entity.AppLog;
import com.common.service.AppLogRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Collections;
@Slf4j
@Service
public class ElasticsearchService {

    @Autowired
    private AppLogRepository appLogRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    private static final DateTimeFormatter INDEX_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 保存日志到ES
     */
    public void saveAppLog(AppLog appLog) {
        try {
            // 设置索引名为当天的日期
            String indexName = "applog-" + LocalDate.now().format(INDEX_FORMATTER);
            appLog.setIndex(indexName);

            // 检查索引是否存在，不存在则创建
            IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
            if (!indexOps.exists()) {
                indexOps.create();
                Document mapping = indexOps.createMapping(AppLog.class);
                indexOps.putMapping(mapping);
                log.info("创建ES索引: {}", indexName);
            }

            // 保存数据
            appLogRepository.save(appLog);
            log.info("成功保存日志到ES, ID: {}, Index: {}", appLog.getId(), indexName);

        } catch (Exception e) {
            log.error("保存日志到ES失败", e);
            throw new RuntimeException("保存ES日志失败", e);
        }
    }

    /**
     * 批量保存日志
     */
    public void saveAppLogs(List<AppLog> appLogs) {
        try {
            String indexName = "applog-" + LocalDate.now().format(INDEX_FORMATTER);

            // 设置所有日志的索引
            appLogs.forEach(log -> log.setIndex(indexName));

            // 检查索引是否存在，不存在则创建
            IndexOperations indexOps = elasticsearchRestTemplate.indexOps(IndexCoordinates.of(indexName));
            if (!indexOps.exists()) {
                indexOps.create();
                Document mapping = indexOps.createMapping(AppLog.class);
                indexOps.putMapping(mapping);
                log.info("创建ES索引: {}", indexName);
            }

            appLogRepository.saveAll(appLogs);
            log.info("批量保存 {} 条日志到ES索引: {}", appLogs.size(), indexName);

        } catch (Exception e) {
            log.error("批量保存日志到ES失败", e);
            throw new RuntimeException("批量保存ES日志失败", e);
        }
    }

    /**
     * 根据日期获取索引中的日志
     */
    public List<AppLog> getLogsByDate(LocalDate date) {
        String indexName = "applog-" + date.format(INDEX_FORMATTER);
        IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);

        try {
            // 检查索引是否存在
            IndexOperations indexOps = elasticsearchRestTemplate.indexOps(indexCoordinates);
            if (!indexOps.exists()) {
                log.info("索引 {} 不存在", indexName);
                return Collections.emptyList();
            }

            // 使用ElasticsearchRestTemplate查询指定索引
            return elasticsearchRestTemplate.search(
                    org.springframework.data.elasticsearch.core.query.Query.findAll(),
                    AppLog.class,
                    indexCoordinates
            ).get().map(result -> {
                AppLog appLog = result.getContent();
                appLog.setIndex(indexName); // 设置索引名称
                appLog.setScore(result.getScore()); // 设置评分
                return appLog;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.warn("查询ES索引 {} 失败", indexName, e);
            return Collections.emptyList();
        }
    }

    /**
     * 根据ID检查日志是否存在
     */
    public boolean existsById(String id, LocalDate date) {
        String indexName = "applog-" + date.format(INDEX_FORMATTER);
        IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);

        try {
            //return elasticsearchRestTemplate.exists(id, AppLog.class, indexCoordinates);
            return elasticsearchRestTemplate.exists(id,  indexCoordinates);
        } catch (Exception e) {
            log.warn("检查日志存在性失败, ID: {}, Index: {}", id, indexName);
            return false;
        }
    }

    /**
     * 根据索引名称获取日志
     */
    public List<AppLog> getLogsByIndex(String indexName) {
        IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);

        try {
            // 检查索引是否存在
            IndexOperations indexOps = elasticsearchRestTemplate.indexOps(indexCoordinates);
            if (!indexOps.exists()) {
                log.info("索引 {} 不存在", indexName);
                return Collections.emptyList();
            }

            return elasticsearchRestTemplate.search(
                    org.springframework.data.elasticsearch.core.query.Query.findAll(),
                    AppLog.class,
                    indexCoordinates
            ).get().map(result -> {
                AppLog appLog = result.getContent();
                appLog.setIndex(indexName);
                appLog.setScore(result.getScore());
                return appLog;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            log.warn("查询ES索引 {} 失败", indexName, e);
            return Collections.emptyList();
        }
    }
}