package com.evobms.project.bms.controller;

import com.evobms.project.bms.service.MqttService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * MQTT测试控制器
 * 用于测试MQTT消息处理功能
 *
 * @author BMS System
 * @date 2024
 */
@RestController
@RequestMapping("/mqtt/test")
@Api(tags = "MQTT测试")
public class MqttTestController {
    private static final Logger log = LoggerFactory.getLogger(MqttTestController.class);

    @Autowired
    private MqttService mqttService;

    /**
     * 测试handleDeviceData方法
     *
     * @param topic MQTT主题
     * @param payload 消息内容
     * @return 测试结果
     */
    @PostMapping("/handleDeviceData")
    @ApiOperation("测试处理设备数据")
    public Map<String, Object> testHandleDeviceData(
            @RequestParam String topic,
            @RequestParam byte[] payload) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 调用handleDeviceData方法
            mqttService.handleDeviceData(topic, payload);
            log.info("测试处理设备数据，topic={}, payload={}", topic, payload);

            result.put("success", true);
            result.put("message", "消息处理成功");
            result.put("topic", topic);
            result.put("payload", payload);
            // 解析主题获取设备编号（模拟方法内部逻辑）
            String[] topicParts = topic.split("/");
            if (topicParts.length >= 3) {
                String deviceCode = topicParts[1];
                result.put("extractedDeviceCode", deviceCode);
            }
        } catch (Exception e) {
            log.error("测试处理设备数据发生错误: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "消息处理失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
        }

        return result;
    }

    /**
     * 生成测试数据
     * @return 测试用的JSON数据
     */
    @GetMapping("/generateTestData")
    @ApiOperation("生成测试数据")
    public Map<String, Object> generateTestData() {
        Map<String, Object> testData = new HashMap<>();
        testData.put("voltage", 12.5);
        testData.put("current", 2.3);
        testData.put("capacity", 85.6);
        testData.put("temperature", 25.8);
        testData.put("timestamp", System.currentTimeMillis());

        return testData;
    }

   /* *//**
     * 快速测试 - 使用预设的主题和数据
     *
     * @return 测试结果
     *//*
    @PostMapping("/quickTest")
    public Map<String, Object> quickTest() {
        String topic = "evobms/test/data";
        String payload = "{\"voltage\":12.5,\"current\":2.3,\"capacity\":85.6,\"temperature\":25.8}";
        log.info("快速测试触发，topic={}, payload={}", topic, payload);

        return testHandleDeviceData(topic, payload);
    }*/
}
