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

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

/**
 * 订单状态更新事件
 * <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
    public void handle(MessageBody<OrderInfoObject> message) {
        log.info(message.toString());
        log.info("DeviceStateEventHandler");

        // 获取设备信息 todo 要从topic中获取
        var productKey = "";
        var deviceName = "";

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

        // 更新订单信息
        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, orderInfo.getDetail().toString())
                .eq(WashOrder::getProductKey, productKey)
                .eq(WashOrder::getDeviceName, deviceName)
                .eq(WashOrder::getOrderId, orderInfo.getOrder_id())
                .eq(WashOrder::getOrderIdLocal, orderInfo.getOrder_id_local())
                .update();

    }
}
