package com.example.demo.controller;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.UserErrorLog;
import com.example.demo.model.UserErrorLog.ErrorType;
import com.example.demo.service.UserErrorLogService;

/**
 * 用户错误日志API控制器
 * 提供错误日志的查询和管理接口
 */
@RestController
@RequestMapping("/api/admin/error-logs")
public class UserErrorLogController {

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

    @Autowired
    private UserErrorLogService userErrorLogService;

    /**
     * 获取错误日志列表（分页）
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getErrorLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Page<UserErrorLog> errors = userErrorLogService.getAllErrors(page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", errors.getContent());
            response.put("totalElements", errors.getTotalElements());
            response.put("totalPages", errors.getTotalPages());
            response.put("currentPage", page);
            response.put("pageSize", size);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取错误日志列表失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取错误日志失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取用户的错误日志
     */
    @GetMapping("/user/{username}")
    public ResponseEntity<Map<String, Object>> getUserErrorLogs(
            @PathVariable String username,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            Page<UserErrorLog> errors = userErrorLogService.getUserErrors(username, page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", errors.getContent());
            response.put("totalElements", errors.getTotalElements());
            response.put("totalPages", errors.getTotalPages());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取用户错误日志失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取错误日志失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 按错误类型查询
     */
    @GetMapping("/type/{errorType}")
    public ResponseEntity<Map<String, Object>> getErrorsByType(
            @PathVariable String errorType,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        try {
            ErrorType type = ErrorType.valueOf(errorType.toUpperCase());
            Page<UserErrorLog> errors = userErrorLogService.getErrorsByType(type, page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", errors.getContent());
            response.put("totalElements", errors.getTotalElements());
            response.put("totalPages", errors.getTotalPages());
            
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(Map.of(
                "success", false,
                "message", "无效的错误类型: " + errorType
            ));
        } catch (Exception e) {
            logger.error("按类型查询错误日志失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "查询失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取最近的错误
     */
    @GetMapping("/recent")
    public ResponseEntity<Map<String, Object>> getRecentErrors(
            @RequestParam(defaultValue = "10") int limit) {
        try {
            List<UserErrorLog> errors = userErrorLogService.getRecentErrors(limit);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", errors
            ));
        } catch (Exception e) {
            logger.error("获取最近错误失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "获取失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 按任务ID查询错误
     */
    @GetMapping("/task/{taskId}")
    public ResponseEntity<Map<String, Object>> getErrorsByTaskId(@PathVariable String taskId) {
        try {
            List<UserErrorLog> errors = userErrorLogService.getErrorsByTaskId(taskId);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", errors
            ));
        } catch (Exception e) {
            logger.error("按任务ID查询错误失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "查询失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 按日期范围查询
     */
    @GetMapping("/date-range")
    public ResponseEntity<Map<String, Object>> getErrorsByDateRange(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        try {
            List<UserErrorLog> errors = userErrorLogService.getErrorsByDateRange(startDate, endDate);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", errors,
                "count", errors.size()
            ));
        } catch (Exception e) {
            logger.error("按日期范围查询错误失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "查询失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取错误统计
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getErrorStatistics(
            @RequestParam(defaultValue = "7") int days) {
        try {
            Map<String, Object> stats = userErrorLogService.getErrorStatistics(days);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", stats,
                "period", days + " days"
            ));
        } catch (Exception e) {
            logger.error("获取错误统计失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "统计失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取用户错误统计
     */
    @GetMapping("/statistics/user/{username}")
    public ResponseEntity<Map<String, Object>> getUserErrorStatistics(@PathVariable String username) {
        try {
            Map<String, Object> stats = userErrorLogService.getUserErrorStatistics(username);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "data", stats
            ));
        } catch (Exception e) {
            logger.error("获取用户错误统计失败: {}", e.getMessage());
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "统计失败: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取所有错误类型
     */
    @GetMapping("/types")
    public ResponseEntity<Map<String, Object>> getErrorTypes() {
        Map<String, String> types = new HashMap<>();
        for (ErrorType type : ErrorType.values()) {
            types.put(type.name(), type.getDescription());
        }
        
        return ResponseEntity.ok(Map.of(
            "success", true,
            "data", types
        ));
    }

}
