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

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

/**
 * 订单状态更新事件
 * <p>
 * 1、⽤来让服务器知道订单的当前状态,以下两个条件只要满⾜其中⼀个就上传⼀次。
 * 2、订单的应收⾦额和上次上传的应收⾦额差额⼤于等于1元则上传⼀次。
 * 3、如果⾦额不变，每隔3分钟上传⼀次。
 * <p>
 * 1. 根据设备的 product_key 和 device_name 找到设备信息。
 * 2. 根据订单号在数据库中找到订单信息。
 * 3. 检查订单的状态为 已付款 或 已开机 并且消费金额大于等于当前记录的消费金额，则保存订单信息
 * 并将订单标记为 已更新 ；否则记录日志。
 *
 * @author skyline
 */
@Slf4j
@Component
public class OrderUpdateEventHandler implements AwoaraEventHandler<OrderInfoObject> {

    private final WashOrderService washOrderService;

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

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

        var topic = message.getTopic().split("/");
        var productKey = topic[1];
        var deviceName = topic[2];

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

        washOrderService.lambdaUpdate()
                .set(WashOrder::getOpenType, orderInfo.getOpen_type())
                .set(WashOrder::getCloseType, orderInfo.getClose_type())
                .set(WashOrder::getMemberDiscount, orderInfo.getMember_discount())
                .set(WashOrder::getPrepayMoney, orderInfo.getPrepay_money())
                .set(WashOrder::getAmount, orderInfo.getAmount())
                .set(WashOrder::getAmountReceivable, orderInfo.getAmount_receivable())
                .set(WashOrder::getAmountReceived, orderInfo.getAmount_received())
                .set(WashOrder::getDiscountMoney, orderInfo.getDiscount_money())
                .set(WashOrder::getOperationRemainTime, orderInfo.getOperation_remain_time())
                .set(WashOrder::getIdleRemainTime, orderInfo.getIdle_remain_time())
                .set(WashOrder::getDetail, JSON.toJSONString(orderInfo.getDetail()))
                .eq(WashOrder::getOrderId, orderInfo.getOrder_id())
                .eq(WashOrder::getProductKey, productKey)
                .eq(WashOrder::getDeviceName, deviceName)
                .update();

    }
}
