package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.edu.common.enums.ErrorCode;
import com.lesingle.edu.common.exception.BusinessException;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.entity.OperationLog;
import com.lesingle.edu.mapper.OperationLogMapper;
import com.lesingle.edu.service.OperationLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 操作日志服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog>
    implements OperationLogService {

    @Override
    public Page<OperationLog> getLogPage(Long tenantId, Integer pageNum, Integer pageSize,
                                          String module, String action) {
        log.debug("分页查询日志列表，页码：{}，每页数量：{}，租户 ID：{}", pageNum, pageSize, tenantId);

        int current = pageNum != null && pageNum > 0 ? pageNum : 1;
        int size = pageSize != null && pageSize > 0 ? pageSize : 10;

        Page<OperationLog> page = new Page<>(current, size);
        LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();

        // 租户隔离：只查询当前租户的日志
        wrapper.eq(OperationLog::getTenantId, tenantId);

        if (StringUtils.hasText(module)) {
            wrapper.eq(OperationLog::getModule, module);
        }
        if (StringUtils.hasText(action)) {
            wrapper.like(OperationLog::getAction, action);
        }

        wrapper.orderByDesc(OperationLog::getCreatedAt);

        return this.page(page, wrapper);
    }

    @Override
    public Map<String, Object> getLogStats(Long tenantId) {
        log.debug("查询日志统计，租户 ID：{}", tenantId);

        // 统计日志总数
        Long totalLogs = this.count(
                new LambdaQueryWrapper<OperationLog>()
                        .eq(OperationLog::getTenantId, tenantId)
        );

        // 按模块分组统计
        List<OperationLog> allLogs = this.list(
                new LambdaQueryWrapper<OperationLog>()
                        .eq(OperationLog::getTenantId, tenantId)
                        .select(OperationLog::getModule)
        );

        Map<String, Long> byModuleMap = allLogs.stream()
                .collect(Collectors.groupingBy(
                        OperationLog::getModule,
                        Collectors.counting()
                ));

        // 转换为前端期望的格式：Map<String, Integer>
        Map<String, Integer> byModule = byModuleMap.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().intValue()
                ));

        Map<String, Object> stats = new HashMap<>();
        stats.put("totalLogs", totalLogs);
        stats.put("byModule", byModule);
        stats.put("byOperator", new HashMap<>());

        return stats;
    }

    @Override
    public OperationLog getLogByIdWithTenantCheck(Long id) {
        OperationLog operationLog = this.getById(id);
        if (operationLog == null) {
            throw new BusinessException(ErrorCode.DATA_NOT_FOUND, "日志不存在");
        }

        // 租户隔离验证：验证日志是否属于当前租户
        Long currentTenantId = SecurityUtils.getCurrentTenantId();
        if (!operationLog.getTenantId().equals(currentTenantId)) {
            log.warn("租户隔离验证失败，日志 ID: {}，日志租户 ID: {}，当前租户 ID: {}",
                    id, operationLog.getTenantId(), currentTenantId);
            throw new BusinessException(ErrorCode.FORBIDDEN, "无权访问该日志");
        }

        return operationLog;
    }

}
