package com.dne.ems.repository.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.dne.ems.model.OperationLog;
import com.dne.ems.model.enums.OperationType;
import com.dne.ems.repository.OperationLogRepository;
import com.dne.ems.service.JsonStorageService;
import com.fasterxml.jackson.core.type.TypeReference;

/**
 * 操作日志仓库的JSON实现，使用JSON文件存储操作日志数据。
 *
 * @version 1.0
 * @since 2025-06-20
 */
@Repository
public class JsonOperationLogRepositoryImpl implements OperationLogRepository {

    private static final String OPERATION_LOGS_FILE = "operation_logs.json";
    
    @Autowired
    private JsonStorageService jsonStorageService;

    @Override
    public OperationLog save(OperationLog operationLog) {
        List<OperationLog> logs = new ArrayList<>(findAll());
        
        // 如果是新记录，生成ID
        if (operationLog.getId() == null) {
            long maxId = logs.stream()
                    .mapToLong(OperationLog::getId)
                    .max()
                    .orElse(0L);
            operationLog.setId(maxId + 1);
        } else {
            // 如果是更新，先删除旧记录
            logs.removeIf(log -> log.getId().equals(operationLog.getId()));
        }
        
        logs.add(operationLog);
        jsonStorageService.writeData(OPERATION_LOGS_FILE, logs);
        return operationLog;
    }

    @Override
    public OperationLog findById(Long id) {
        return findAll().stream()
                .filter(log -> log.getId().equals(id))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<OperationLog> findAll() {
        return jsonStorageService.readData(OPERATION_LOGS_FILE, new TypeReference<List<OperationLog>>() {});
    }

    @Override
    public List<OperationLog> findByUserId(Long userId) {
        return findAll().stream()
                .filter(log -> log.getUser() != null && Objects.equals(log.getUser().getId(), userId))
                .collect(Collectors.toList());
    }

    @Override
    public List<OperationLog> findByOperationType(OperationType operationType) {
        return findAll().stream()
                .filter(log -> log.getOperationType() == operationType)
                .collect(Collectors.toList());
    }

    @Override
    public List<OperationLog> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime) {
        return findAll().stream()
                .filter(log -> {
                    LocalDateTime createdAt = log.getCreatedAt();
                    return (startTime == null || !createdAt.isBefore(startTime)) && 
                           (endTime == null || !createdAt.isAfter(endTime));
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<OperationLog> findByConditions(Long userId, OperationType operationType, 
                                              LocalDateTime startTime, LocalDateTime endTime) {
        return findAll().stream()
                .filter(log -> userId == null || 
                        (log.getUser() != null && Objects.equals(log.getUser().getId(), userId)))
                .filter(log -> operationType == null || log.getOperationType() == operationType)
                .filter(log -> {
                    LocalDateTime createdAt = log.getCreatedAt();
                    if (createdAt == null) {
                        return false; // 如果创建时间为空，则不匹配时间范围
                    }
                    return (startTime == null || !createdAt.isBefore(startTime)) && 
                           (endTime == null || !createdAt.isAfter(endTime));
                })
                .collect(Collectors.toList());
    }

    @Override
    public void deleteById(Long id) {
        List<OperationLog> logs = findAll().stream()
                .filter(log -> !log.getId().equals(id))
                .collect(Collectors.toList());
        jsonStorageService.writeData(OPERATION_LOGS_FILE, logs);
    }

    @Override
    public void deleteAll() {
        jsonStorageService.writeData(OPERATION_LOGS_FILE, new ArrayList<>());
    }
} 