package com.inspect.metadata.mqtt.controller;

import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.metadata.eqpbook.domain.BasedataEqpBook;
import com.inspect.metadata.eqpbook.service.IBasedataEqpBookService;
import com.inspect.metadata.mqtt.MQTTUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;

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

@RestController
@RequestMapping("/hr/emergency")
public class HrEmergencyController extends BaseController {
    @Autowired(required = false)
    private MQTTUtils mqttUtils;

    @Autowired
    private IBasedataEqpBookService iBasedataEqpBookService;

    @GetMapping("/list")
    public AjaxResult list() {
        BasedataEqpBook eqpBook = new BasedataEqpBook();
        eqpBook.setAreaName("华软无人机");
        List<BasedataEqpBook> eqpBooks = iBasedataEqpBookService.selectBasedataEqpBookList(eqpBook);
        List<Map<String, String>> list = new ArrayList<>();
        for (BasedataEqpBook book : eqpBooks) {
            Map<String, String> map = new HashMap<>();
            map.put("name", book.getPatrolDeviceName());
            map.put("nestCode", book.getPatrolDeviceCode());
            list.add(map);
        }

        return AjaxResult.success(list);
    }

    // 机巢自检
    @GetMapping("/selfcheck/{nestCode}")
    public AjaxResult selfcheck(@PathVariable String nestCode) {
        try {
            // 2.7.1 机巢控制：自检
            executeMqttCommand(nestCode, "12000", "4", "/thing/service/nest/control");
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("[HR Emergency selfcheck] error :{}", e.getMessage());
            return AjaxResult.error();
        }
    }

    // 机巢紧急锁停
    @GetMapping("/lockdown/{nestCode}")
    public AjaxResult lockdown(@PathVariable String nestCode) {
        try {
            // 2.7.1 机巢控制：急停
            executeMqttCommand(nestCode, "12000", "2", "/thing/service/nest/control");
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("[HR Emergency lockdown] error :{}", e.getMessage());
            return AjaxResult.error();
        }
    }

    @GetMapping("/releaseLockdown/{nestCode}")
    public AjaxResult releaseLockdown(@PathVariable String nestCode) {
        try {
            // 2.7.1 机巢控制：解除急停
            executeMqttCommand(nestCode, "12000", "3", "/thing/service/nest/control");
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("[HR Emergency release lockdown] error :{}", e.getMessage());
            return AjaxResult.error();
        }
    }

    //无人机紧急降落
    @GetMapping("/landing/{nestCode}")
    public AjaxResult landing(@PathVariable String nestCode) {
        try {
            // 2.8.5 无人机控制：一键返航
            executeMqttCommand(nestCode, "22004", "1", "/thing/service/drone/drone_control");
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("[HR Emergency landing] error :{}", e.getMessage());
            return AjaxResult.error();
        }
    }

    private void executeMqttCommand(String nestCode, String code, String command, String topicSuffix) throws InterruptedException {
        // 模拟延迟
        Thread.sleep(2000);
        if (mqttUtils == null) {
            logger.warn("MQTT is disabled, skipping command execution for nestCode: {}", nestCode);
        } else {
            String content = String.format("{\"code\":\"%s\",\"command\":\"%s\"}", code, command);
            mqttUtils.publish(1, "/sys/" + nestCode + topicSuffix, content);
        }
    }
}
