package com.shzg.project.worn.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.shzg.common.utils.DateUtils;
import com.shzg.project.worn.domain.MqttSensorCommand;
import com.shzg.project.worn.domain.MqttSensorDevice;
import com.shzg.project.worn.domain.MqttTopicConfig;
import com.shzg.project.worn.sensor.config.MqttPublishClient;
import com.shzg.project.worn.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class MqttSocketServiceImpl implements IMqttSocketService {

    @Autowired
    private MqttPublishClient mqttPublishClient;

    @Autowired
    private IMqttSensorDeviceService deviceService;

    @Autowired
    private IMqttTopicConfigService topicConfigService;

    @Autowired
    private IMqttSensorCommandService commandService;

    @Override
    public void controlSocket(String devEui, boolean on) {

        // ================== 1️⃣ 查设备 ==================
        MqttSensorDevice device = deviceService.selectByDevEui(devEui);
        if (device == null) {
            throw new RuntimeException("设备不存在: " + devEui);
        }

        // ================== 2️⃣ 查Topic配置 ==================
        MqttTopicConfig config = topicConfigService.selectByDeptId(device.getDeptId());
        if (config == null) {
            throw new RuntimeException("未配置MQTT主题，deptId=" + device.getDeptId());
        }

        // ================== 3️⃣ 拼接topic ==================
        String topic = config.getTopicDownPrefix() + "/" + devEui.toLowerCase();

        // ================== 4️⃣ 构造指令 ==================
        String base64 = on ? "CAEA/w==" : "CAAA/w==";

        String requestId = UUID.randomUUID().toString();

        JSONObject json = new JSONObject();
        json.put("confirmed", true);
        json.put("fport", 85);
        json.put("data", base64);
        json.put("requestId", requestId);

        String payload = json.toJSONString();

        // ================== 5️⃣ 写指令记录（发送前） ==================
        MqttSensorCommand cmd = new MqttSensorCommand();
        cmd.setDeviceId(device.getId());
        cmd.setTopic(topic);
        cmd.setCommand(on ? "ON" : "OFF");
        cmd.setPayload(payload);
        cmd.setStatus("0"); // 0=待确认
        cmd.setSendTime(new Date());
        cmd.setIsDelete("0");
        cmd.setCreateTime(DateUtils.getNowDate());

        commandService.insertMqttSensorCommand(cmd);

        // ================== 6️⃣ 发送MQTT ==================
        mqttPublishClient.publish(topic, payload);

        // ================== 7️⃣ 日志 ==================
        System.out.println("[SOCKET] 指令发送 devEui=" + devEui +
                ", status=" + (on ? "ON" : "OFF") +
                ", requestId=" + requestId);
    }
}