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

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

/**
 * 设备启动事件处理
 *
 * @author skyline
 */
@Slf4j
@Component
public class BootEventHandler implements AwoaraEventHandler<DeviceStateObject> {

    private final WashDeviceService washDeviceService;

    private final WashOrderService washOrderService;

    public BootEventHandler(WashDeviceService washDeviceService, WashOrderService washOrderService) {
        this.washDeviceService = washDeviceService;
        this.washOrderService = washOrderService;
    }

    @Override
    @Transactional
    public void handle(MessageBody<DeviceStateObject> message) {
        log.info(message.toString());
        log.info("BootEventHandler");
        // 获取设备信息 从topic中获取
        log.debug("topic:{}", message.getTopic());
        var topic = message.getTopic().split("/");
        var productKey = topic[1];
        var deviceName = topic[2];
        log.debug("productKey:{},deviceName:{}", productKey, deviceName);

        var device = washDeviceService.lambdaQuery().eq(WashDevice::getProductKey, productKey).eq(WashDevice::getDeviceName, deviceName).one();
        // 更新设备状态
        washDeviceService.lambdaUpdate()
                .set(WashDevice::getState, message.getPayload().getData().getDevice_state().getState())
                .eq(WashDevice::getId, device.getId()).update();

        // 查询设备下的所有未完成的订单，如果有则将这些订单标记成异常结束
        var orderList = washOrderService.lambdaQuery()
                .eq(WashOrder::getProductKey, productKey)
                .eq(WashOrder::getDeviceName, deviceName)
                .eq(WashOrder::getPayStatus, WashOrder.PAY_STATUS_未支付)
                .list();
        // todo 异常订单执行扣费操作
    }
}
