package com.yushu.web.core.config;

import com.yushu.common.utils.ErrorLogUtils;
import com.yushu.system.domain.SysErrorLog;
import com.yushu.system.service.ISysErrorLogService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * 错误日志配置
 * 初始化错误记录器
 * 
 * @author yushu
 */
@Configuration
public class ErrorLogConfig {
    
    @Autowired
    private ISysErrorLogService errorLogService;

    @PostConstruct
    public void init() {
        // 设置错误记录器
        ErrorLogUtils.setErrorRecorder(this::recordError);
    }

    /**
     * 记录错误到数据库
     */
    private void recordError(Map<String, Object> errorInfo) {
        SysErrorLog errorLog = new SysErrorLog();
        
        errorLog.setErrorType((String) errorInfo.get("errorType"));
        errorLog.setErrorLevel((String) errorInfo.get("errorLevel"));
        errorLog.setErrorMessage((String) errorInfo.get("errorMessage"));
        errorLog.setErrorDetail((String) errorInfo.get("errorDetail"));
        
        errorLog.setRequestUrl((String) errorInfo.get("requestUrl"));
        errorLog.setRequestMethod((String) errorInfo.get("requestMethod"));
        errorLog.setRequestParams((String) errorInfo.get("requestParams"));
        errorLog.setRequestIp((String) errorInfo.get("requestIp"));
        errorLog.setUserAgent((String) errorInfo.get("userAgent"));
        
        errorLog.setUserName((String) errorInfo.get("userName"));
        Object userId = errorInfo.get("userId");
        if (userId != null) {
            errorLog.setUserId((Long) userId);
        }
        
        errorLog.setSourceClass((String) errorInfo.get("sourceClass"));
        errorLog.setSourceMethod((String) errorInfo.get("sourceMethod"));
        Object sourceLine = errorInfo.get("sourceLine");
        if (sourceLine != null) {
            errorLog.setSourceLine((Integer) sourceLine);
        }
        
        // 异步记录
        errorLogService.recordError(errorLog);
    }
}
