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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

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

        MqttSensorDevice device = deviceService.selectByDevEui(devEui);

        if (device == null) {
            throw new RuntimeException("设备不存在: " + devEui);
        }

        String deviceType = device.getDeviceType();

        if (deviceType == null || !deviceType.toLowerCase().contains("socket")) {
            throw new RuntimeException("该接口仅支持智能插座设备");
        }

        MqttTopicConfig config = topicConfigService.selectByDeptId(device.getDeptId());

        if (config == null) {
            throw new RuntimeException("未配置MQTT主题");
        }

        String topic = config.getTopicDownPrefix() + "/" + devEui.toLowerCase();
        String requestId = UUID.randomUUID().toString();

        // 插座指令
        String base64 = on ? "CAEA/w==" : "CAAA/w==";

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

        String payload = json.toJSONString();

        // 记录
        MqttSensorCommand cmd = new MqttSensorCommand();
        cmd.setDeviceId(device.getId());
        cmd.setTopic(topic);
        cmd.setCommand(on ? "ON" : "OFF");
        cmd.setPayload(payload);
        cmd.setStatus("0");
        cmd.setSendTime(new Date());
        cmd.setIsDelete("0");
        cmd.setCreateTime(DateUtils.getNowDate());

        commandService.insertMqttSensorCommand(cmd);

        mqttPublishClient.publish(topic, payload);

        log.info("[SOCKET] devEui={}, status={}", devEui, on ? "ON" : "OFF");
    }

    /**
     * ================== 开关控制 ==================
     */
    @Override
    public void controlSwitch(String devEui, int channel, boolean on) {

        MqttSensorDevice device = deviceService.selectByDevEui(devEui);

        if (device == null) {
            throw new RuntimeException("设备不存在: " + devEui);
        }

        String deviceType = device.getDeviceType();

        if (deviceType == null || !deviceType.toLowerCase().contains("switch")) {
            throw new RuntimeException("该设备不是智能开关");
        }

        MqttTopicConfig config = topicConfigService.selectByDeptId(device.getDeptId());

        if (config == null) {
            throw new RuntimeException("未配置MQTT主题");
        }

        String topic = config.getTopicDownPrefix() + "/" + devEui.toLowerCase();
        String requestId = UUID.randomUUID().toString();

        // ⭐ 核心：多路控制
        int controlBit = (1 << (channel - 1));
        int valueBit = on ? controlBit : 0;
        int byte1 = (controlBit << 4) | valueBit;

        String hex = String.format("08%02XFF", byte1);
        String base64 = Base64.getEncoder().encodeToString(hexStringToBytes(hex));

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

        String payload = json.toJSONString();

        // 记录
        MqttSensorCommand cmd = new MqttSensorCommand();
        cmd.setDeviceId(device.getId());
        cmd.setTopic(topic);
        cmd.setCommand("SWITCH_" + channel + "_" + (on ? "ON" : "OFF"));
        cmd.setPayload(payload);
        cmd.setStatus("0");
        cmd.setSendTime(new Date());
        cmd.setIsDelete("0");
        cmd.setCreateTime(DateUtils.getNowDate());

        commandService.insertMqttSensorCommand(cmd);

        mqttPublishClient.publish(topic, payload);

        log.info("[SWITCH] devEui={}, channel={}, status={}",
                devEui, channel, on ? "ON" : "OFF");
    }

    /**
     * hex转byte[]
     */
    private byte[] hexStringToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) (
                    (Character.digit(hex.charAt(i), 16) << 4)
                            + Character.digit(hex.charAt(i + 1), 16)
            );
        }
        return data;
    }
}