package cn.iocoder.yudao.module.order.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.apollo.core.event.OrderCouponUpdateEvent;
import cn.iocoder.yudao.framework.apollo.core.event.OrderOperateLogEvent;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.order.enums.OrderStatusEnum;
import cn.iocoder.yudao.module.order.service.order.OrderService;
import cn.iocoder.yudao.module.product.vo.productPrice.ClearancePriceEvent;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 订单优惠更新监听
 *
 * @author zhengYi
 */
@Component("OrderCouponUpdateListener")
@AllArgsConstructor
public class OrderCouponUpdateListener {

    private final OrderService orderService;

    /**
     * 在优惠发布前已入仓的订单，如果入仓时间在优惠有效期内，则执行自动更新任务
     *
     * @param event 订单优惠更新参数
     */
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT, classes = OrderCouponUpdateEvent.class)
    @Async
    public void orderCouponUpdateEvent(OrderCouponUpdateEvent event) {
        List<OrderDO> orderDOList = orderService.selectList(new LambdaQueryWrapper<OrderDO>().eq(OrderDO::getStatus, OrderStatusEnum.IN_WAREHOUSE.getValue()).between(OrderDO::getRucangTime, event.getStartTime(), new Date()));
        if (CollectionUtil.isNotEmpty(orderDOList)){
            String msg = String.format("优惠活动【%s/%s】发布更新订单价格", event.getTitleZh(), event.getTitleEn());
            for (OrderDO orderDO : orderDOList) {
               orderService.orderCouponUpdate(orderDO, msg);
            }
        }
    }
}
