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

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

/**
 * 收到订单事件
 * 1. 根据设备的 product_key 和 device_name 找到设备信息。
 * 2. 根据订单号在数据库中找到订单信息。
 * 3. 检查订单的状态为 已付款（预付款） ，则保存订单信息并将订单标记为 已开机 ；否则记录日志
 *
 * @author skyline
 */
@Slf4j
@Component
public class OrderCreateEventHandler implements AwoaraEventHandler<OrderInfoObject> {

    private final WashOrderService washOrderService;

    public OrderCreateEventHandler(WashOrderService washOrderService) {
        this.washOrderService = washOrderService;
    }

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

        OrderInfo orderInfo = message.getPayload().getData().getOrder_info();

        // 获取设备信息 从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 order = washOrderService.lambdaQuery()
                .eq(WashOrder::getOrderId, orderInfo.getOrder_id())
                .eq(WashOrder::getOrderIdLocal, orderInfo.getOrder_id_local())
                .eq(WashOrder::getProductKey, productKey)
                .eq(WashOrder::getDeviceName, deviceName)
                .one();

        if (order != null) {
            washOrderService.lambdaUpdate()
                    .set(WashOrder::getOrderStatus, WashOrder.ORDER_STATUS_开机)
                    .eq(WashOrder::getId, order.getId())
                    .update();
        }
    }

}
