package com.ruoyi.task.order;

import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.ruoyi.bst.order.domain.OrderQuery;
import com.ruoyi.bst.order.domain.OrderVO;
import com.ruoyi.bst.order.domain.dto.OrderEndDTO;
import com.ruoyi.bst.order.domain.enums.OrderReturnType;
import com.ruoyi.bst.order.domain.enums.OrderStatus;
import com.ruoyi.bst.order.mapper.OrderMapper;
import com.ruoyi.bst.order.service.OrderService;
import com.ruoyi.common.utils.collection.CollectionUtils;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class OrderTask implements ApplicationRunner {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 查询所有未支付的订单
        OrderQuery query = new OrderQuery();
        query.setStatusList(OrderStatus.unPayList());
        List<OrderVO> orderList = orderMapper.selectOrderList(query);

        for (OrderVO order : orderList) {
            try {
                orderService.cancelWhenExpired(order);
            } catch (Exception e) {
                log.error("取消订单失败，订单ID：{}", order.getId(), e);
            }
        }
    }

    /**
     * 关闭超过最大可用时间的订单
     */
    public void closeExpireMaxTimeOrder() {
        // 查询超过最大可用时间的订单
        OrderQuery query = new OrderQuery();
        query.setStatusList(OrderStatus.inUse());
        query.setMaxTimeEnd(LocalDateTime.now());
        List<OrderVO> orderList = orderService.selectOrderList(query);

        if (CollectionUtils.isEmptyElement(orderList)) {
            log.info("没有超过最大可用时间的订单");
            return;
        }

        for (OrderVO order : orderList) {
            try {
                OrderEndDTO dto = new OrderEndDTO();
                dto.setReturnType(OrderReturnType.SYSTEM.getCode());
                dto.setOrderId(order.getId());
                dto.setEndReason("超时系统自动结束");
                orderService.endOrder(dto);
            } catch (Exception e) {
                log.error("结束订单失败，订单ID：{}", order.getId(), e);
            }

        }
    }

}
