package cn.reghao.tnb.file.app.zjob.task;

import cn.reghao.tnb.content.api.iface.MallService;
import cn.reghao.tnb.file.app.zorder.db.OrderMapper;
import cn.reghao.tnb.file.app.zorder.model.constant.OrderStatus;
import cn.reghao.tnb.file.app.zorder.model.po.Order;
import lombok.extern.slf4j.Slf4j;

/**
 * @author reghao
 * @date 2024-12-04 13:35:31
 */
@Slf4j
public class OrderTask implements Runnable {
    private final long orderId;
    private final MallService mallService;
    private final OrderMapper orderMapper;

    public OrderTask(MallService mallService, OrderMapper orderMapper, long orderId) {
        this.mallService = mallService;
        this.orderMapper = orderMapper;
        this.orderId = orderId;
    }

    @Override
    public void run() {
        try {
            orderTimeout(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void orderTimeout(long orderId) {
        Order order = orderMapper.findByOrderId(orderId);
        if (order != null && order.getStatus() == OrderStatus.toPay.getCode()) {
            long productId = order.getProductId();
            int amount = order.getAmount();
            orderMapper.updateOrderStatus(orderId, OrderStatus.cancelled.getCode());
            mallService.updateCancelOrder(productId, amount);
            log.info("cancel order");
        }
    }
}
