/**
 * @ProjectName: 智慧评标-主观分助手
 * @Package: com.zhpb.gdyd_zhpb_zgf.service.impl
 * @ClassName: UserLogServiceImpl
 * @Description: 用户操作日志服务实现类
 * @Author: 
 * @Date: 2025-11-28
 * @Version: 1.0
 * @Copyright: © 2025 智慧评标-主观分助手
 */
package com.zhpb.gdyd_zhpb_zgf.service.impl;

import com.zhpb.gdyd_zhpb_zgf.entity.mysql.UserLog;
import com.zhpb.gdyd_zhpb_zgf.repository.mysql.UserLogRepository;
import com.zhpb.gdyd_zhpb_zgf.service.UserLogService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户操作日志服务实现类
 */
@Service
public class UserLogServiceImpl implements UserLogService {

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

    @Autowired
    private UserLogRepository userLogRepository;

    @Override
    public void logUserOperation(String userId, String userName, String projectId,
                                String operationType, String operationDetail,
                                String relatedId, HttpServletRequest request) {
        try {
            UserLog userLog = new UserLog();
            // 如果 userId 为 null，设置默认值
            userLog.setUserId(userId != null ? userId : "anonymous");
            userLog.setUserName(userName != null ? userName : "未知用户");
            userLog.setProjectId(projectId);
            userLog.setOperationType(operationType);
            userLog.setOperationDetail(operationDetail);
            userLog.setRelatedId(relatedId);
            
            // 获取客户端IP地址
            if (request != null) {
                userLog.setIpAddress(getClientIp(request));
                userLog.setUserAgent(request.getHeader("User-Agent"));
            }

            userLogRepository.save(userLog);
            logger.debug("记录用户操作日志成功: userId={}, operationType={}", userId, operationType);
        } catch (Exception e) {
            logger.warn("记录用户操作日志失败: {}", e.getMessage());
        }
    }

    @Override
    public void logUserOperation(String userId, String userName,
                                String operationType, String operationDetail,
                                HttpServletRequest request) {
        logUserOperation(userId, userName, null, operationType, operationDetail, null, request);
    }

    @Override
    public List<UserLog> getUserLogsByUserId(String userId) {
        return userLogRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }

    @Override
    public List<UserLog> getUserLogsByProjectId(String projectId) {
        return userLogRepository.findByProjectIdOrderByCreateTimeDesc(projectId);
    }

    @Override
    public List<UserLog> getUserLogsByOperationType(String operationType) {
        return userLogRepository.findByOperationTypeOrderByCreateTimeDesc(operationType);
    }

    @Override
    public List<UserLog> getUserLogsByUserIdAndOperationType(String userId, String operationType) {
        return userLogRepository.findByUserIdAndOperationTypeOrderByCreateTimeDesc(userId, operationType);
    }

    @Override
    public Long countUserOperations(String userId) {
        return userLogRepository.countByUserId(userId);
    }

    @Override
    public Long countOperationsByType(String operationType) {
        return userLogRepository.countByOperationType(operationType);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}