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.util.Date;

/**
 * 门磁传感器 Handler
 */
@Slf4j
@Component
public class DoorSensorHandler {

    @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) {

        // =========================
        // 1️⃣ 基础校验
        // =========================
        if (device == null) {
            log.error("[DOOR] device为空");
            return;
        }

        if (device.getDeptId() == null) {
            log.error("[DOOR] device未绑定部门，拒绝处理。deviceId={}, deviceName={}",
                    device.getId(), device.getDeviceName());
            return;
        }

        try {
            JSONObject json = JSONObject.parseObject(payload);

            String devEui = json.getString("devEUI");
            Integer doorStatus = json.getInteger("magnet_status");
            Integer tamperStatus = json.getInteger("tamper_status");
            Integer battery = json.getInteger("battery");

            log.info("[DOOR] devEui={}, deptId={}, door={}, tamper={}, battery={}",
                    devEui, device.getDeptId(), doorStatus, tamperStatus, battery);

            // =========================
            // 2️⃣ 数据入库
            // =========================
            MqttSensorData data = new MqttSensorData();
            data.setDeviceId(device.getId());
            data.setDeptId(device.getDeptId());
            data.setTopic(topic);
            data.setPayload(payload);
            data.setCreateTime(new Date());

            if (battery != null) {
                data.setBattery(battery.longValue());
            }

            if (doorStatus != null) {
                data.setDoorStatus(doorStatus);
            }

            dataService.insertMqttSensorData(data);

            // =========================
            // 3️⃣ 状态计算
            // =========================
            String status;

            if (doorStatus != null) {
                status = (doorStatus == 1 ? "open" : "close");
            } else if (tamperStatus != null) {
                status = (tamperStatus == 1 ? "tamper" : "normal");
            } else {
                status = "unknown";
            }

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

            // =========================
            // 5️⃣ 查询部门名称
            // =========================
            String deptName = null;
            SysDept dept = deptService.selectDeptById(device.getDeptId());
            if (dept != null) {
                deptName = dept.getDeptName();
            }

            // =========================
            // 6️⃣ WebSocket推送（周期上报也要推）
            // =========================
            JSONObject ws = new JSONObject();
            ws.put("type", "door");
            ws.put("deviceId", device.getId());
            ws.put("deviceName", device.getDeviceName());
            ws.put("deptId", device.getDeptId());
            ws.put("deptName", deptName);
            ws.put("status", status);
            ws.put("doorStatus", doorStatus);
            ws.put("tamperStatus", tamperStatus);
            ws.put("battery", battery);
            ws.put("time", System.currentTimeMillis());

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

            // =========================
            // 7️⃣ Redis去重
            // =========================
            boolean changed = deviceStatusService.isStatusChanged(
                    device.getId(),
                    "door",
                    status
            );

            if (!changed) {
                return;
            }

            // =========================
            // 8️⃣ 事件处理
            // =========================
            if ("open".equals(status)) {
                saveEvent(device, "door_open", "门已打开");
            } else if ("close".equals(status)) {
                saveEvent(device, "door_close", "门已关闭");
            } else if ("tamper".equals(status)) {
                saveEvent(device, "tamper", "设备被拆除");
            }

        } catch (Exception e) {
            log.error("[DOOR] 处理异常 payload={}", payload, e);
        }
    }

    /**
     * 保存事件
     */
    private void saveEvent(MqttSensorDevice device, String type, String desc) {

        if (device == null || device.getDeptId() == null) {
            log.warn("[DOOR] saveEvent跳过，device或deptId为空");
            return;
        }

        MqttSensorEvent event = new MqttSensorEvent();
        event.setDeviceId(device.getId());
        event.setDeptId(device.getDeptId());
        event.setEventType(type);
        event.setEventDesc(desc);
        event.setLevel("INFO");

        event.setStatus("0");
        event.setIsDelete("0");

        event.setCreateTime(new Date());

        eventService.insertMqttSensorEvent(event);
    }
}
