package com.shzg.project.worn.sensor.mqtt.handler;

import com.alibaba.fastjson2.JSONObject;
import com.shzg.project.system.domain.SysDept;
import com.shzg.project.system.service.ISysDeptService;
import com.shzg.project.worn.domain.MqttSensorData;
import com.shzg.project.worn.domain.MqttSensorDevice;
import com.shzg.project.worn.domain.MqttSensorEvent;
import com.shzg.project.worn.service.IDeviceStatusService;
import com.shzg.project.worn.service.IMqttSensorDataService;
import com.shzg.project.worn.service.IMqttSensorEventService;
import com.shzg.project.worn.unit.DeviceStatusUtil;
import com.shzg.project.worn.websocket.manager.WebSocketSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 烟雾传感器 Handler
 */
@Slf4j
@Component
public class SmokeSensorHandler {

    @Autowired
    private IMqttSensorDataService dataService;

    @Autowired
    private IMqttSensorEventService eventService;

    @Autowired
    private WebSocketSessionManager sessionManager;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IDeviceStatusService deviceStatusService;

    @Autowired
    private DeviceStatusUtil deviceStatusUtil;

    public void handle(MqttSensorDevice device, String topic, String payload) {

        if (device == null) {
            log.error("[SMOKE] device为空");
            return;
        }

        if (device.getDeptId() == null) {
            log.error("[SMOKE] device未绑定deptId！");
            return;
        }

        JSONObject json;
        try {
            json = JSONObject.parseObject(payload);
        } catch (Exception e) {
            log.error("[SMOKE] JSON解析失败 payload={}", payload, e);
            return;
        }

        // ================== topic解析 ==================
        String project = null;
        String warehouse = null;
        try {
            String[] arr = topic.split("/");
            if (arr.length >= 3) {
                project = arr[1];
                warehouse = arr[2];
            }
        } catch (Exception e) {
            log.warn("[SMOKE] topic解析失败 topic={}", topic);
        }

        // ================== 业务字段 ==================
        String event = json.getString("event");
        Integer battery = json.getInteger("battery");
        Integer concentration = json.getInteger("concentration");
        Integer temperature = json.getInteger("temperature");

        // ================== 查询 deptName ==================
        String deptName = null;
        SysDept dept = deptService.selectDeptById(device.getDeptId());
        if (dept != null) {
            deptName = dept.getDeptName();
        }

        // ================== 数据入库 ==================
        MqttSensorData data = new MqttSensorData();
        data.setDeviceId(device.getId());
        data.setDeptId(device.getDeptId());

        data.setTopic(topic);
        data.setProject(project);
        data.setWarehouse(warehouse);

        data.setPayload(payload);
        data.setDataJson(json.toJSONString());

        data.setBattery(battery == null ? null : battery.longValue());
        data.setConcentration(concentration == null ? null : concentration.longValue());
        data.setTemperature(temperature == null ? null : new BigDecimal(temperature));

        data.setCreateTime(new Date());
        data.setIsDelete("0");

        dataService.insertMqttSensorData(data);

        // ================== 恢复在线 ==================
        deviceStatusUtil.handleOnline(device);

        // ================== 状态判断 ==================
        String newStatus;
        String eventType;
        String desc;
        String level;

        if ("silent".equals(event)) {
            newStatus = "silent";
            eventType = "silent";
            desc = "烟雾已消音";
            level = "LOW";
        } else if ("alarm".equals(event) || (concentration != null && concentration > 0)) {
            newStatus = "alarm";
            eventType = "alarm";
            desc = "烟雾报警";
            level = "HIGH";
        } else if ("removed".equals(event)) {
            newStatus = "removed";
            eventType = "removed";
            desc = "设备被拆除";
            level = "MEDIUM";
        } else if ("low_battery".equals(event)) {
            newStatus = "low_battery";
            eventType = "low_battery";
            desc = "电量低";
            level = "LOW";
        } else {
            newStatus = "normal";
            eventType = "recovery";
            desc = "烟雾恢复正常";
            level = "LOW";
        }

        // ================== Redis去重 ==================
        boolean changed = deviceStatusService.isStatusChanged(
                device.getId(),
                "smoke",
                newStatus
        );

        // ================== WebSocket推送 ==================
        pushWebSocket(device, deptName, event, battery, concentration, temperature, newStatus);

        if (!changed) {
            return;
        }

        // ================== 事件入库 ==================
        insertEvent(device, eventType, desc, level);

        // ================== 联动控制 ==================
        if ("alarm".equals(newStatus)) {
            log.warn("[SMOKE] 触发联动（烟雾报警）deviceId={}", device.getId());

            // socketService.openFan(device.getDeptId());

        }

        log.info("[SMOKE] 状态变化 deviceId={}, status={}, eventType={}",
                device.getId(), newStatus, eventType);
    }

    private void pushWebSocket(MqttSensorDevice device,
                               String deptName,
                               String event,
                               Integer battery,
                               Integer concentration,
                               Integer temperature,
                               String status) {

        try {
            JSONObject msg = new JSONObject();

            msg.put("type", "smoke");
            msg.put("deviceId", device.getId());
            msg.put("deviceName", device.getDeviceName());
            msg.put("deptId", device.getDeptId());
            msg.put("deptName", deptName);

            msg.put("event", event);
            msg.put("status", status);
            msg.put("battery", battery);
            msg.put("concentration", concentration);
            msg.put("temperature", temperature);

            msg.put("time", System.currentTimeMillis());

            sessionManager.sendToDept(device.getDeptId(), msg.toJSONString());

        } catch (Exception e) {
            log.error("[SMOKE] WebSocket推送失败", e);
        }
    }

    private void insertEvent(MqttSensorDevice device,
                             String type,
                             String desc,
                             String level) {

        MqttSensorEvent event = new MqttSensorEvent();
        event.setDeviceId(device.getId());
        event.setDeptId(device.getDeptId());

        event.setEventType(type);
        event.setEventDesc(desc);
        event.setLevel(level);
        event.setStatus("0");
        event.setIsDelete("0");
        event.setCreateTime(new Date());

        eventService.insertMqttSensorEvent(event);
    }
}