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

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

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

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

        // ================== 状态解析 ==================
        Integer s1 = json.getInteger("switch_1");
        Integer s2 = json.getInteger("switch_2");
        Integer s3 = json.getInteger("switch_3");

        if (s1 == null && s2 == null && s3 == null) {
            log.warn("[SWITCH] 未检测到开关数据 payload={}", payload);
            return;
        }

        // ================== 入库 ==================
        MqttSensorData data = new MqttSensorData();
        data.setDeviceId(device.getId());
        data.setDeptId(device.getDeptId());
        data.setTopic(topic);
        data.setPayload(payload);
        data.setDataJson(payload);
        data.setCreateTime(new Date());
        data.setIsDelete("0");

        dataService.insertMqttSensorData(data);

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

        // ================== Redis去重 ==================
        String statusStr = (s1 != null && s1 == 1) ? "on" : "off";

        boolean changed = deviceStatusService.isStatusChanged(
                device.getId(),
                "switch",
                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", "switch");
            msg.put("deviceId", device.getId());
            msg.put("deviceName", device.getDeviceName());
            msg.put("deptId", device.getDeptId());
            msg.put("deptName", deptName);

            msg.put("switch1", s1);
            msg.put("switch2", s2);
            msg.put("switch3", s3);

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

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

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

        MqttSensorEvent event = new MqttSensorEvent();
        event.setDeviceId(device.getId());
        event.setDeptId(device.getDeptId());
        event.setEventType("switch_change");
        event.setEventDesc("照明开关状态变化");
        event.setLevel("LOW");

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

        eventService.insertMqttSensorEvent(event);

        log.info("[SWITCH] 状态变化 deviceId={}, switch1={}", device.getId(), s1);
    }
}