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 SmartSocketHandler {

    @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("[SOCKET] device为空");
            return;
        }

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

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

        // ================== 状态解析 ==================
        Integer status = json.getInteger("device_status");
        if (status == null) {
            status = json.getInteger("socket_status");
        }

        if (status == null) {
            log.warn("[SOCKET] 未包含 device_status/socket_status");
            return;
        }

        // ================== 状态转换 ==================
        Integer switchStatus;
        if (status == 17 || status == 1) {
            switchStatus = 1;
        } else if (status == 16 || status == 0) {
            switchStatus = 0;
        } else {
            log.warn("[SOCKET] 未识别状态 status={}, payload={}", status, payload);
            return;
        }

        // ================== 入库（有效数据） ==================
        MqttSensorData data = new MqttSensorData();
        data.setDeviceId(device.getId());
        data.setDeptId(device.getDeptId());
        data.setTopic(topic);
        data.setPayload(payload);
        data.setDataJson(payload);
        data.setSwitchStatus(switchStatus);
        data.setCreateTime(new Date());
        data.setIsDelete("0");

        dataService.insertMqttSensorData(data);

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

        // ================== 状态字符串 ==================
        String statusStr = (switchStatus == 1 ? "on" : "off");

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

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

        // ================== WebSocket推送 ==================
        try {
            JSONObject msg = new JSONObject();
            msg.put("type", "socket");
            msg.put("deviceId", device.getId());
            msg.put("deviceName", device.getDeviceName());
            msg.put("deptId", device.getDeptId());
            msg.put("deptName", deptName);
            msg.put("status", switchStatus);
            msg.put("statusDesc", switchStatus == 1 ? "通电" : "断电");
            msg.put("time", System.currentTimeMillis());

            sessionManager.sendToDept(device.getDeptId(), msg.toJSONString());
        } catch (Exception e) {
            log.error("[SOCKET] WebSocket推送失败", e);
        }

        // ================== 事件记录 =================
        if (!changed) {
            return;
        }

        MqttSensorEvent event = new MqttSensorEvent();
        event.setDeviceId(device.getId());
        event.setDeptId(device.getDeptId());
        event.setEventType(switchStatus == 1 ? "socket_on" : "socket_off");
        event.setEventDesc(switchStatus == 1 ? "插座开启（通电）" : "插座关闭（断电）");
        event.setLevel("LOW");

        event.setStatus("0");
        event.setIsDelete("0");
        event.setCreateTime(new Date());

        eventService.insertMqttSensorEvent(event);

        log.info("[SOCKET] 状态变化 deviceId={}, {} -> {}",
                device.getId(),
                status,
                switchStatus);
    }
}