package com.ruoyi.monitor.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.monitor.domain.AuditLog;
import com.ruoyi.monitor.mapper.AuditLogMapper;
import com.ruoyi.monitor.service.IAuditLogService;

/**
 * 审计日志Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-12-19
 */
@Service
public class AuditLogServiceImpl implements IAuditLogService 
{
    @Autowired
    private AuditLogMapper auditLogMapper;

    /**
     * 查询审计日志
     * 
     * @param logId 审计日志主键
     * @return 审计日志
     */
    @Override
    public AuditLog selectAuditLogByLogId(Long logId)
    {
        return auditLogMapper.selectAuditLogByLogId(logId);
    }

    /**
     * 查询审计日志列表
     * 
     * @param auditLog 审计日志
     * @return 审计日志
     */
    @Override
    public List<AuditLog> selectAuditLogList(AuditLog auditLog)
    {
        return auditLogMapper.selectAuditLogList(auditLog);
    }

    /**
     * 新增审计日志
     * 
     * @param auditLog 审计日志
     * @return 结果
     */
    @Override
    public int insertAuditLog(AuditLog auditLog)
    {
        return auditLogMapper.insertAuditLog(auditLog);
    }

    /**
     * 修改审计日志
     * 
     * @param auditLog 审计日志
     * @return 结果
     */
    @Override
    public int updateAuditLog(AuditLog auditLog)
    {
        return auditLogMapper.updateAuditLog(auditLog);
    }

    /**
     * 批量删除审计日志
     * 
     * @param logIds 需要删除的审计日志主键
     * @return 结果
     */
    @Override
    public int deleteAuditLogByLogIds(Long[] logIds)
    {
        return auditLogMapper.deleteAuditLogByLogIds(logIds);
    }

    /**
     * 删除审计日志信息
     * 
     * @param logId 审计日志主键
     * @return 结果
     */
    @Override
    public int deleteAuditLogByLogId(Long logId)
    {
        return auditLogMapper.deleteAuditLogByLogId(logId);
    }

    /**
     * 记录操作日志
     */
    @Override
    public void recordOperation(String operationType, String operationModule, 
                               String operationDescription, String businessId, 
                               String businessType, String dataBefore, String dataAfter)
    {
        recordOperation(operationType, operationModule, operationDescription, 
                       businessId, businessType, dataBefore, dataAfter, "LOW");
    }

    /**
     * 记录操作日志（带风险等级）
     */
    @Override
    public void recordOperation(String operationType, String operationModule, 
                               String operationDescription, String businessId, 
                               String businessType, String dataBefore, String dataAfter,
                               String riskLevel)
    {
        AuditLog auditLog = new AuditLog();
        auditLog.setOperationType(operationType);
        auditLog.setOperationModule(operationModule);
        auditLog.setOperationDescription(operationDescription);
        auditLog.setBusinessId(businessId);
        auditLog.setBusinessType(businessType);
        auditLog.setDataBefore(dataBefore);
        auditLog.setDataAfter(dataAfter);
        auditLog.setRiskLevel(riskLevel);
        auditLog.setOperationTime(new Date());
        auditLog.setStatus("0"); // 默认正常状态

        // 获取当前用户信息
        try {
            auditLog.setUserId(SecurityUtils.getUserId());
            auditLog.setUserName(SecurityUtils.getUsername());
        } catch (Exception e) {
            // 如果获取用户信息失败，设置为系统用户
            auditLog.setUserId(0L);
            auditLog.setUserName("system");
        }

        // 获取请求信息
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                auditLog.setIpAddress(IpUtils.getIpAddr(request));
                auditLog.setUserAgent(request.getHeader("User-Agent"));
                auditLog.setRequestUri(request.getRequestURI());
                auditLog.setRequestMethod(request.getMethod());
                auditLog.setSessionId(request.getSession().getId());
            }
        } catch (Exception e) {
            // 如果获取请求信息失败，忽略
        }

        auditLogMapper.insertAuditLog(auditLog);
    }

    /**
     * 根据用户ID查询审计日志
     */
    @Override
    public List<AuditLog> selectAuditLogByUserId(Long userId)
    {
        return auditLogMapper.selectAuditLogByUserId(userId);
    }

    /**
     * 根据业务ID和业务类型查询审计日志
     */
    @Override
    public List<AuditLog> selectAuditLogByBusiness(String businessId, String businessType)
    {
        return auditLogMapper.selectAuditLogByBusiness(businessId, businessType);
    }

    /**
     * 根据操作类型查询审计日志
     */
    @Override
    public List<AuditLog> selectAuditLogByOperationType(String operationType)
    {
        return auditLogMapper.selectAuditLogByOperationType(operationType);
    }

    /**
     * 查询审计日志统计信息
     */
    @Override
    public List<Map<String, Object>> selectAuditLogStatistics(Map<String, Object> params)
    {
        return auditLogMapper.selectAuditLogStatistics(params);
    }

    /**
     * 根据风险等级查询审计日志
     */
    @Override
    public List<AuditLog> selectAuditLogByRiskLevel(String riskLevel)
    {
        return auditLogMapper.selectAuditLogByRiskLevel(riskLevel);
    }

    /**
     * 查询指定时间范围内的审计日志
     */
    @Override
    public List<AuditLog> selectAuditLogByTimeRange(Map<String, Object> params)
    {
        return auditLogMapper.selectAuditLogByTimeRange(params);
    }

    /**
     * 清理过期的审计日志
     */
    @Override
    public int cleanExpiredAuditLogs(int retentionDays)
    {
        return auditLogMapper.cleanExpiredAuditLogs(retentionDays);
    }

    /**
     * 分析审计日志，检测异常操作
     */
    @Override
    public List<AuditLog> analyzeAnomalousOperations(Map<String, Object> params)
    {
        // 检测异常操作的逻辑
        AuditLog queryLog = new AuditLog();
        
        // 查找高风险操作
        queryLog.setRiskLevel("HIGH");
        List<AuditLog> highRiskLogs = auditLogMapper.selectAuditLogList(queryLog);
        
        // 查找失败操作
        queryLog.setRiskLevel(null);
        queryLog.setStatus("1");
        List<AuditLog> failedLogs = auditLogMapper.selectAuditLogList(queryLog);
        
        // 合并结果
        highRiskLogs.addAll(failedLogs);
        
        return highRiskLogs;
    }

    /**
     * 生成审计报告
     */
    @Override
    public Map<String, Object> generateAuditReport(Map<String, Object> params)
    {
        Map<String, Object> report = new HashMap<>();
        
        // 获取统计信息
        List<Map<String, Object>> statistics = auditLogMapper.selectAuditLogStatistics(params);
        report.put("statistics", statistics);
        
        // 获取异常操作
        List<AuditLog> anomalousOps = analyzeAnomalousOperations(params);
        report.put("anomalousOperations", anomalousOps);
        
        // 获取高风险操作
        List<AuditLog> highRiskOps = auditLogMapper.selectAuditLogByRiskLevel("HIGH");
        report.put("highRiskOperations", highRiskOps);
        
        // 计算总体指标
        AuditLog totalQuery = new AuditLog();
        List<AuditLog> allLogs = auditLogMapper.selectAuditLogList(totalQuery);
        report.put("totalOperations", allLogs.size());
        
        long errorCount = allLogs.stream().filter(log -> "1".equals(log.getStatus())).count();
        report.put("errorOperations", errorCount);
        
        double errorRate = allLogs.size() > 0 ? (double) errorCount / allLogs.size() * 100 : 0;
        report.put("errorRate", errorRate);
        
        return report;
    }
}