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

import com.kym.entity.WashOrder;
import com.kym.entity.awoara.MessageBody;
import com.kym.entity.awoara.OrderInfoObject;
import com.kym.service.OrderSettlementService;
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 OrderCloseEventHandler implements AwoaraEventHandler<OrderInfoObject> {

    private final WashOrderService washOrderService;
    private final OrderSettlementService orderSettlementService;

    public OrderCloseEventHandler(WashOrderService washOrderService,
                                  OrderSettlementService orderSettlementService) {
        this.washOrderService = washOrderService;
        this.orderSettlementService = orderSettlementService;
    }

    @Override
    @Transactional
    public void handle(MessageBody<OrderInfoObject> message) {
        log.info("收到订单关闭事件");

        var orderInfo = message.getPayload().getData().getOrder_info();
        log.info("订单：{}，结算信息：{}", orderInfo.getOrder_id(), orderInfo);

        var washOrder = washOrderService.lambdaQuery().eq(WashOrder::getOrderId, orderInfo.getOrder_id()).one();
        if (washOrder == null) {
            log.error("订单不存在，订单号：{}", orderInfo.getOrder_id());
            return;
        }
        if (Integer.valueOf(WashOrder.PAY_STATUS_已支付).equals(washOrder.getPayStatus())) {
            log.warn("订单：{}，已结算，跳过重复关闭事件", orderInfo.getOrder_id());
            return;
        }

        orderSettlementService.settleOrder(washOrder, orderInfo);
    }
}
