package com.agri.web.controller.mqtt;

import com.agri.common.annotation.Log;
import com.agri.common.core.domain.AjaxResult;
import com.agri.common.enums.BusinessType;
import com.agri.framework.manager.AgriStatusManager;
import com.agri.framework.manager.MqttAutoOffManager;
import com.agri.framework.manager.MqttClientManager;
import com.agri.framework.manager.MqttSubscriptionManager;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * MQTT订阅管理接口
 */
@RestController
@RequestMapping("/api/mqtt")
public class MqttController {

    private static final Logger log = LoggerFactory.getLogger(MqttController.class);

    @Resource
    private MqttSubscriptionManager mqttSubscriptionManager;
    @Resource
    private MqttClientManager mqttClientManager;

    @Autowired
    private MqttAutoOffManager mqttAutoOffManager;

    @Autowired
    private AgriStatusManager agriStatusManager;

    /**
     * 单个订阅
     */
    @PostMapping("/single")
    @Log(title = "订阅主题", businessType = BusinessType.INSERT)
    public String subscribe(@RequestParam String clientId, @RequestParam String deviceId) {
        try {
            mqttSubscriptionManager.subscribeDevice(clientId, deviceId);
            return "订阅成功";
        } catch (IllegalArgumentException e) {
            log.error("MQTT单个订阅失败：{}", e.getMessage());
            return "订阅失败：" + e.getMessage();
        } catch (Exception e) {
            log.error("MQTT单个订阅异常", e);
            return "订阅失败：系统异常";
        }
    }

    /**
     * 单个取消
     */
    @DeleteMapping("/single")
    public String unsubscribe(@RequestParam String clientId, @RequestParam String deviceId) {
        try {
            mqttSubscriptionManager.unsubscribeDevice(clientId, deviceId);
            return "取消订阅成功";
        } catch (IllegalArgumentException e) {
            log.error("MQTT单个取消订阅失败：{}", e.getMessage());
            return "取消订阅失败：" + e.getMessage();
        } catch (Exception e) {
            log.error("MQTT单个取消订阅异常", e);
            return "取消订阅失败：系统异常";
        }
    }

    /**
     * 批量取消当前用户的所有设备订阅
     */
    @PostMapping("/batchSubscribe")
    @Log(title = "批量订阅主题", businessType = BusinessType.INSERT)
    public AjaxResult subscribeAll(@RequestParam String clientId) {
        try {
            // 返回前端需要取消的MQTT主题列表
            return AjaxResult.success(mqttSubscriptionManager.subscribeAllDeviceByUserId(clientId));
        } catch (IllegalArgumentException e) {
            log.error("MQTT批量订阅失败：{}", e.getMessage());
            // 异常时返回空列表，避免前端解析失败
            return AjaxResult.error("MQTT批量订阅失败",0);
        } catch (Exception e) {
            log.error("MQTT批量订阅异常", e);
            return AjaxResult.error("MQTT批量订阅异常",0);
        }
    }

    /**
     * 批量取消当前用户的所有设备订阅
     */
    @DeleteMapping("/batchUnsubscribe")
    @Log(title = "批量取消订阅主题", businessType = BusinessType.DELETE)
    public List<String> unsubscribeAll(@RequestParam String clientId) {
        try {
            // 返回前端需要取消的MQTT主题列表
            return mqttSubscriptionManager.unsubscribeAllDevice(clientId);
        } catch (IllegalArgumentException e) {
            log.error("MQTT批量取消订阅失败：{}", e.getMessage());
            // 异常时返回空列表，避免前端解析失败
            return Lists.newArrayList();
        } catch (Exception e) {
            log.error("MQTT批量取消订阅异常", e);
            return Lists.newArrayList();
        }
    }
    /**
     * 手动触发MQTT重连
     * 场景：配置修正后，手动恢复连接（无需重启服务）
     */
    @GetMapping("/reconnect")
    @Log(title = "手动触发MQTT重连", businessType = BusinessType.OTHER)
    public String manualReconnect() {
        try {
            return mqttClientManager.manualReconnect();
        } catch (Exception e) {
            log.error("MQTT手动重连异常", e);
            return "手动重连失败：" + e.getMessage();
        }
    }

    /**
     * 查询当前MQTT连接状态
     * 便于排查连接问题
     */
    @GetMapping("/status")
    public AjaxResult getMqttStatus() {
        try {
            return AjaxResult.success(mqttClientManager.getMqttStatus());
        } catch (Exception e) {
            log.error("查询MQTT连接状态异常", e);
            return AjaxResult.error("查询状态失败：" + e.getMessage());
        }
    }

    /**
     * 2️⃣ 查询某个设备是否存在自动关任务
     */
    @GetMapping("/device/{deviceId}")
    public AjaxResult device(@PathVariable String deviceId) {
        boolean hasTask = mqttAutoOffManager.hasAutoOffTask(deviceId);
        return AjaxResult.success(hasTask);
    }


    @PostMapping("/getAgriStatus")
    public void getAgriStatus(@RequestBody List<String> imeiList) {

        if (imeiList.isEmpty()) {
            log.info("大棚表无数据，结束推送");
            return;
        }
        agriStatusManager.asyncBatchPushMqtt(agriStatusManager.batchCheckDeviceOnline(imeiList));
    }
}