package com.common.service;


import com.common.entity.AppLogEntity;
import com.common.mapper.AppLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ApplogService {

    @Autowired
    private AppLogMapper appLogMapper;

    /**
     * 保存日志到数据库（去重）
     */
    @Transactional
    public void saveAppLogWithDeduplication(AppLogEntity appLog) {
        // 检查是否已存在
        boolean exists = appLogMapper.existsByEsIdAndIndex(appLog.getEsId(), appLog.getEsIndex());

        if (!exists) {
            appLog.setCreatedAt(LocalDateTime.now());
            appLog.setUpdatedAt(LocalDateTime.now());
            appLogMapper.insert(appLog);
            log.info("保存日志到数据库, ES ID: {}", appLog.getEsId());
        } else {
            log.debug("日志已存在，跳过保存, ES ID: {}", appLog.getEsId());
        }
    }

    /**
     * 批量保存日志到数据库（去重）
     */
    @Transactional
    public int batchSaveAppLogsWithDeduplication(List<AppLogEntity> appLogs) {
        if (appLogs == null || appLogs.isEmpty()) {
            return 0;
        }

        // 过滤已存在的记录
        List<AppLogEntity> newLogs = appLogs.stream()
                .filter(log -> !appLogMapper.existsByEsIdAndIndex(log.getEsId(), log.getEsIndex()))
                .peek(log -> {
                    log.setCreatedAt(LocalDateTime.now());
                    log.setUpdatedAt(LocalDateTime.now());
                }).collect(Collectors.toList());


        if (!newLogs.isEmpty()) {
            appLogMapper.batchInsert(newLogs);
            log.info("批量保存 {} 条日志到数据库，跳过 {} 条重复数据",
                    newLogs.size(), appLogs.size() - newLogs.size());
        } else {
            log.info("所有 {} 条日志均已存在，跳过保存", appLogs.size());
        }

        return newLogs.size();
    }
}