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

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

/**
 * 设备启动事件处理
 *
 * @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
    public void handle(MessageBody<DeviceStateObject> message) {
        log.info(message.toString());
        log.info("DeviceStateEventHandler");
        // 获取设备信息 todo 要从topic中获取
        var topic = message.getTopic().split("/");
        var productKey = topic[1];
        var deviceName = topic[2];

        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 异常订单执行扣费操作
    }
}
