/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.service.impl
 * @ClassName: SysLogServiceImpl
 * @Description: 系统日志服务实现类，异步保存日志到数据库
 * @Author: 张志锋
 * @Date: 2025-10-31
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.service.impl;

import com.zhpb.gdyd_zhpb_zgf.entity.mysql.SysLog;
import com.zhpb.gdyd_zhpb_zgf.repository.mysql.SysLogRepository;
import com.zhpb.gdyd_zhpb_zgf.service.SysLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 系统日志服务实现类
 */
@Service
public class SysLogServiceImpl implements SysLogService {

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

    @Autowired
    private SysLogRepository sysLogRepository;

    @Value("${spring.application.name:gdyd_zhpb_zgf}")
    private String applicationName;

    @Override
    @Async
    @Transactional
    public void log(String logLevel, String loggerName, String logContent, String fullMessage, String exceptionStack) {
        try {
            SysLog sysLog = new SysLog();
            sysLog.setLogLevel(logLevel != null ? logLevel.toUpperCase() : "INFO");
            sysLog.setLoggerName(loggerName);
            sysLog.setLogContent(logContent != null ? logContent : "");
            sysLog.setFullMessage(fullMessage);
            sysLog.setExceptionStack(exceptionStack);
            sysLog.setThreadName(Thread.currentThread().getName());
            sysLog.setCreateTime(LocalDateTime.now());
            sysLog.setApplicationName(applicationName);

            sysLogRepository.save(sysLog);
        } catch (Exception e) {
            // 记录日志失败时，避免无限循环，只输出到标准错误
            System.err.println("保存系统日志失败: " + e.getMessage());
            logger.error("保存系统日志失败", e);
        }
    }
}

