package com.example.demo.controller;

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.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
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.TaskQueue;
import com.example.demo.service.TaskQueueService;
import com.example.demo.util.JwtUtils;

/**
 * 任务队列API控制器
 */
@RestController
@RequestMapping("/api/task-queue")
public class TaskQueueApiController {

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

    @Autowired
    private TaskQueueService taskQueueService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 获取用户的任务队列（仅待处理任务）
     */
    @GetMapping("/user-tasks")
    public ResponseEntity<Map<String, Object>> getUserTaskQueue(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            List<TaskQueue> taskQueue = taskQueueService.getUserTaskQueue(username);
            long totalCount = taskQueueService.getUserTaskCount(username);

            response.put("success", true);
            response.put("data", taskQueue);
            response.put("total", totalCount);
            response.put("maxTasks", 3); // 每个用户最多3个任务
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户任务队列失败", e);
            response.put("success", false);
            response.put("message", "获取任务队列失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 分页获取用户的所有任务队列（包括所有状态）
     */
    @GetMapping("/all-tasks")
    public ResponseEntity<Map<String, Object>> getUserAllTasks(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            Page<TaskQueue> taskPage = taskQueueService.getUserAllTasks(username, page, size);

            response.put("success", true);
            response.put("data", taskPage.getContent());
            response.put("total", taskPage.getTotalElements());
            response.put("totalPages", taskPage.getTotalPages());
            response.put("currentPage", page);
            response.put("pageSize", size);
            response.put("hasNext", taskPage.hasNext());
            response.put("hasPrevious", taskPage.hasPrevious());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户所有任务失败", e);
            response.put("success", false);
            response.put("message", "获取任务列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 取消队列中的任务
     */
    @PostMapping("/cancel/{taskId}")
    public ResponseEntity<Map<String, Object>> cancelTask(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            boolean cancelled = taskQueueService.cancelTask(taskId, username);
            if (cancelled) {
                response.put("success", true);
                response.put("message", "任务已取消");
            } else {
                response.put("success", false);
                response.put("message", "任务取消失败或任务不存在/无权限");
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("取消任务失败", e);
            response.put("success", false);
            response.put("message", "取消任务失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取任务队列统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getQueueStats(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            List<TaskQueue> taskQueue = taskQueueService.getUserTaskQueue(username);
            long totalCount = taskQueueService.getUserTaskCount(username);

            // 统计各状态的任务数量
            long pendingCount = taskQueue.stream()
                .filter(tq -> tq.getStatus() == TaskQueue.QueueStatus.PENDING)
                .count();
            long processingCount = taskQueue.stream()
                .filter(tq -> tq.getStatus() == TaskQueue.QueueStatus.PROCESSING)
                .count();
            long completedCount = taskQueue.stream()
                .filter(tq -> tq.getStatus() == TaskQueue.QueueStatus.COMPLETED)
                .count();
            long failedCount = taskQueue.stream()
                .filter(tq -> tq.getStatus() == TaskQueue.QueueStatus.FAILED)
                .count();

            Map<String, Object> stats = new HashMap<>();
            stats.put("total", totalCount);
            stats.put("pending", pendingCount);
            stats.put("processing", processingCount);
            stats.put("completed", completedCount);
            stats.put("failed", failedCount);
            stats.put("maxTasks", 3);

            response.put("success", true);
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取队列统计失败", e);
            response.put("success", false);
            response.put("message", "获取统计信息失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 手动触发任务处理（管理员功能）
     */
    @PostMapping("/process-pending")
    public ResponseEntity<Map<String, Object>> processPendingTasks(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 这里可以添加管理员权限检查
            // 暂时允许所有用户触发
            
            taskQueueService.processPendingTasks();
            
            response.put("success", true);
            response.put("message", "待处理任务处理完成");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("手动处理任务失败", e);
            response.put("success", false);
            response.put("message", "处理任务失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 手动触发状态检查（管理员功能）
     */
    @PostMapping("/check-statuses")
    public ResponseEntity<Map<String, Object>> checkTaskStatuses(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 这里可以添加管理员权限检查
            // 暂时允许所有用户触发
            
            taskQueueService.checkTaskStatuses();
            
            response.put("success", true);
            response.put("message", "任务状态检查完成");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("手动检查状态失败", e);
            response.put("success", false);
            response.put("message", "检查状态失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            // 提取实际的token
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            // 验证token并获取用户名
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }

    /**
     * 检查任务是否在队列中（用于前端决定是否需要轮询）
     */
    @GetMapping("/check/{taskId}")
    public ResponseEntity<Map<String, Object>> checkTaskInQueue(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            String username = extractUsernameFromToken(token);
            if (username == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 检查任务是否在队列中
            boolean inQueue = taskQueueService.isTaskInQueue(taskId);
            
            response.put("success", true);
            response.put("inQueue", inQueue);
            response.put("taskId", taskId);
            
            return ResponseEntity.ok(response);

        } catch (Exception e) {
            logger.error("检查任务队列状态失败", e);
            response.put("success", false);
            response.put("message", "检查失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}


