package org.dromara.app.handler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.app.domain.bo.AppDeviceBo;
import org.dromara.app.mqtt.MqttTopicHandler;
import org.dromara.app.service.IAppDeviceService;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 设备数据上报处理器 — 匹配 /{deviceNo}/publish/power
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DeviceDataHandler implements MqttTopicHandler {

    private static final Pattern PATTERN = Pattern.compile("^/([^/]+)/publish/power$");
    private final IAppDeviceService appDeviceService;

    @Override
    public Pattern topicPattern() {
        return PATTERN;
    }

    @Override
    public void handle(String deviceNo, String payload) {
        try {
            Map<String, Object> dto = JsonUtils.parseObject(payload, Map.class);
            AppDeviceBo appDeviceBo = new AppDeviceBo();
            appDeviceBo.setDeviceNo(deviceNo);
            appDeviceBo.setPowerLevel(dto.get("powerLevel").toString());
            appDeviceBo.setPowerLevelUpdatatime(new Date());
            appDeviceService.updateByBo(appDeviceBo);
            log.info("[MQTT] 设备电量更新 deviceNo={} payload={}", deviceNo, payload);
        } catch (Exception e) {
            log.error("[MQTT] 设备电量更新失败 deviceNo={} payload={}", deviceNo, payload, e);
        }
    }
}
