package cn.iocoder.yudao.module.pms.hik;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/hikvision")
@RequiredArgsConstructor
public class HikIsapiController {
    
    private final HikIsapiService hikIsapiService;
    private final AlarmEventService alarmEventService;
    
    /**
     * 接收超脑告警回调（JSON格式）
     */
    @PostMapping("/alarm/callback")
    @PermitAll
    public ResponseEntity<Map<String, Object>> handleAlarmCallback(
            @RequestBody String jsonPayload) {
        log.info("接收到告警回调请求: {}", jsonPayload);
        try {
            // 处理告警
            hikIsapiService.handleAlarmCallback(jsonPayload);
            Map<String, Object> response = ImmutableMap.of(
                "code", 0,
                "message", "success",
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("处理告警回调失败", e);
            Map<String, Object> response = ImmutableMap.of(
                "code", -1,
                "message", e.getMessage(),
                "timestamp", System.currentTimeMillis()
            );
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 订阅事件通知
     */
    @PostMapping("/subscribe/{deviceId}")
    //@ApiOperation("订阅设备事件通知")
    public ResponseEntity<Map<String, Object>> subscribeEvents(
            @PathVariable String deviceId) {
        
        try {
            String result = hikIsapiService.subscribeEvents(deviceId);
            
            Map<String, Object> response = ImmutableMap.of(
                "code", 0,
                "message", "订阅成功",
                "data", result,
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            log.error("订阅失败", e);
            
            Map<String, Object> response = ImmutableMap.of(
                "code", -1,
                "message", "订阅失败: " + e.getMessage(),
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 取消订阅
     */
    @PostMapping("/unsubscribe/{deviceId}")
    //@ApiOperation("取消订阅设备事件")
    public ResponseEntity<Map<String, Object>> unsubscribeEvents(
            @PathVariable String deviceId) {
        
        try {
            String result = hikIsapiService.unsubscribeEvents(deviceId);
            
            Map<String, Object> response = ImmutableMap.of(
                "code", 0,
                "message", "取消订阅成功",
                "data", result,
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            log.error("取消订阅失败", e);
            
            Map<String, Object> response = ImmutableMap.of(
                "code", -1,
                "message", "取消订阅失败: " + e.getMessage(),
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取设备信息
     */
    @GetMapping("/device/{deviceId}/info")
    //@ApiOperation("获取设备信息")
    public ResponseEntity<Map<String, Object>> getDeviceInfo(
            @PathVariable String deviceId) {
        
        try {
            String result = hikIsapiService.getDeviceInfo(deviceId);
            
            Map<String, Object> response = ImmutableMap.of(
                "code", 0,
                "message", "获取成功",
                "data", result,
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(response);
            
        } catch (IOException e) {
            log.error("获取设备信息失败", e);
            
            Map<String, Object> response = ImmutableMap.of(
                "code", -1,
                "message", "获取失败: " + e.getMessage(),
                "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 查询告警事件
     */
    @GetMapping("/alarms")
    //@ApiOperation("查询告警事件")
    public ResponseEntity<Map<String, Object>> getAlarms(
            @RequestParam(required = false) String deviceId,
            @RequestParam(required = false) String eventType,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {
        
        // TODO: 从数据库查询
        Map<String, Object> response = ImmutableMap.of(
            "code", 0,
            "message", "查询成功",
            "data", ImmutableList.of(),
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 接收图片回调
     */
    @PostMapping("/image/callback")
    //@ApiOperation("接收图片回调")
    public ResponseEntity<Map<String, Object>> handleImageCallback(
            @RequestBody Map<String, Object> imageData) {
        
        log.info("接收到图片回调: {}", imageData);
        
        // TODO: 保存图片到本地或云存储
        
        Map<String, Object> response = ImmutableMap.of(
            "code", 0,
            "message", "success",
            "timestamp", System.currentTimeMillis()
        );
        
        return ResponseEntity.ok(response);
    }
}