package com.kym.service.awoara.event.handle;

import com.kym.entity.WashDevice;
import com.kym.entity.awoara.DeviceStateObject;
import com.kym.entity.awoara.MessageBody;
import com.kym.service.WashDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备状态更新事件事件处理
 *
 * @author skyline
 */
@Slf4j
@Component
public class DeviceStateEventHandler implements AwoaraEventHandler<DeviceStateObject> {

    private final WashDeviceService washDeviceService;

    public DeviceStateEventHandler(WashDeviceService washDeviceService) {
        this.washDeviceService = washDeviceService;
    }

    @Override
    @Transactional
    public void handle(MessageBody<DeviceStateObject> message) {
        log.info(message.toString());
        log.info("DeviceStateEventHandler");

        // 获取设备信息 从topic中获取
        log.debug("topic:{}", message.getTopic());
        var topic = message.getTopic().split("/");
        var productKey = topic[1];
        var deviceName = topic[2];
        var deviceState = message.getPayload().getData().getDevice_state();

        // 状态更新逻辑
        washDeviceService.lambdaUpdate()
                .set(WashDevice::getUptimeMs, deviceState.getUptime_ms())
                .set(WashDevice::getState, deviceState.getState())
                .set(WashDevice::getFsmState, deviceState.getFsm_state())
                .set(WashDevice::getHasWater, deviceState.getHas_water())
                .set(WashDevice::getHasFoam, deviceState.getHas_foam())
                .set(WashDevice::getTemperatureChip, deviceState.getTemperature_chip())
                .eq(WashDevice::getProductKey, productKey)
                .eq(WashDevice::getDeviceName, deviceName)
                .update();
    }
}
