package com.haobang.controller;

import com.common.entity.DeviceCollectHeartbeat;
import com.common.service.ProbeHeartbeatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 探针心跳接收接口
 * 提供给探针端(syslog-serve)调用
 */
@RestController
@RequestMapping("/interlocking/probe")
public class ProbeHeartbeatController {

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

    @Autowired
    private ProbeHeartbeatService probeHeartbeatService;

    @Value("${interlocking.api-key:}")
    private String expectedApiKey;

    /**
     * 接收探针心跳
     * POST /interlocking/probe/heartbeat
     *
     * Headers: X-API-KEY: {api-key}
     * Body: {
     *   "collectId": "probe-001",
     *   "collectName": "测试探针",
     *   "deviceIp": "192.168.1.100",
     *   "appVersion": "1.0.0",
     *   "loadStatus": "{}"
     * }
     */
    @PostMapping("/heartbeat")
    public ResponseEntity<Map<String, Object>> receiveHeartbeat(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey,
            @RequestBody ProbeHeartbeatService.ProbeHeartbeatData heartbeatData) {

        Map<String, Object> result = new HashMap<>();

        // 验证API Key
        if (expectedApiKey != null && !expectedApiKey.isEmpty()
                && !expectedApiKey.equals(apiKey)) {
            result.put("code", 401);
            result.put("message", "API Key验证失败");
            logger.warn("探针心跳请求API Key验证失败");
            return ResponseEntity.status(401).body(result);
        }

        // 验证必填字段
        if (heartbeatData.getCollectId() == null || heartbeatData.getCollectId().isEmpty()) {
            result.put("code", 400);
            result.put("message", "collectId不能为空");
            return ResponseEntity.badRequest().body(result);
        }

        try {
            DeviceCollectHeartbeat heartbeat = probeHeartbeatService.receiveHeartbeat(heartbeatData);

            Map<String, Object> data = new HashMap<>();
            data.put("collectId", heartbeat.getCollectId());
            data.put("status", heartbeat.getStatus());
            data.put("lastHeartbeat", heartbeat.getLastHeartbeat().toString());
            result.put("code", 200);
            result.put("message", "success");
            result.put("data", data);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("处理探针心跳异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "处理心跳失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取所有探针状态
     * GET /interlocking/probe/list
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllProbes(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey) {

        Map<String, Object> result = new HashMap<>();

        if (expectedApiKey != null && !expectedApiKey.isEmpty()
                && !expectedApiKey.equals(apiKey)) {
            result.put("code", 401);
            result.put("message", "API Key验证失败");
            return ResponseEntity.status(401).body(result);
        }

        try {
            List<DeviceCollectHeartbeat> probes = probeHeartbeatService.getAllProbes();

            result.put("code", 200);
            result.put("message", "success");
            result.put("data", probes);
            result.put("total", probes.size());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取探针列表异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "获取探针列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取在线探针列表
     * GET /interlocking/probe/online
     */
    @GetMapping("/online")
    public ResponseEntity<Map<String, Object>> getOnlineProbes(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey) {

        Map<String, Object> result = new HashMap<>();

        if (expectedApiKey != null && !expectedApiKey.isEmpty()
                && !expectedApiKey.equals(apiKey)) {
            result.put("code", 401);
            result.put("message", "API Key验证失败");
            return ResponseEntity.status(401).body(result);
        }

        try {
            List<DeviceCollectHeartbeat> probes = probeHeartbeatService.getOnlineProbes();

            result.put("code", 200);
            result.put("message", "success");
            result.put("data", probes);
            result.put("total", probes.size());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取在线探针列表异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "获取在线探针列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取离线探针列表
     * GET /interlocking/probe/offline
     */
    @GetMapping("/offline")
    public ResponseEntity<Map<String, Object>> getOfflineProbes(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey) {

        Map<String, Object> result = new HashMap<>();

        if (expectedApiKey != null && !expectedApiKey.isEmpty()
                && !expectedApiKey.equals(apiKey)) {
            result.put("code", 401);
            result.put("message", "API Key验证失败");
            return ResponseEntity.status(401).body(result);
        }

        try {
            List<DeviceCollectHeartbeat> probes = probeHeartbeatService.getOfflineProbes();

            result.put("code", 200);
            result.put("message", "success");
            result.put("data", probes);
            result.put("total", probes.size());

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取离线探针列表异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "获取离线探针列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 获取单个探针状态
     * GET /interlocking/probe/{collectId}
     */
    @GetMapping("/{collectId}")
    public ResponseEntity<Map<String, Object>> getProbe(
            @RequestHeader(value = "X-API-KEY", required = false) String apiKey,
            @PathVariable String collectId) {

        Map<String, Object> result = new HashMap<>();

        if (expectedApiKey != null && !expectedApiKey.isEmpty()
                && !expectedApiKey.equals(apiKey)) {
            result.put("code", 401);
            result.put("message", "API Key验证失败");
            return ResponseEntity.status(401).body(result);
        }

        try {
            DeviceCollectHeartbeat probe = probeHeartbeatService.getProbeById(collectId);

            if (probe == null) {
                result.put("code", 404);
                result.put("message", "探针不存在");
                return ResponseEntity.status(404).body(result);
            }

            result.put("code", 200);
            result.put("message", "success");
            result.put("data", probe);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取探针状态异常: {}", e.getMessage(), e);
            result.put("code", 500);
            result.put("message", "获取探针状态失败: " + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }

    /**
     * 健康检查
     * GET /interlocking/probe/health
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "OK");
        result.put("service", "probe-heartbeat-api");
        result.put("timestamp", java.time.LocalDateTime.now().toString());
        return ResponseEntity.ok(result);
    }
}
