package com.younike.system.task;

import com.younike.system.domain.Order;
import com.younike.system.domain.TaskLog;
import com.younike.system.enums.OrderStateEnum;
import com.younike.system.service.IOrderService;
import com.younike.system.service.ITaskLogService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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


/**
 * 未支付订单取消任务
 * (已经通过延迟队列实现)
 */
@Deprecated
@Component("orderStateCancelTask")
public class OrderStateCancelTask {

    /**
     * 任务日志
     */
    @Autowired
    private ITaskLogService taskLogService;

    @Autowired
    private IOrderService orderService;


    /**
     *  未支付订单取消任务
     *
     * 超时15分钟未支付订单需取消
     */
    public void updateOrderStateForOverFifteenMinutes(){
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName("超时15分钟未支付订单取消任务");
        taskLog.setExecutionTime(LocalDateTime.now());
        try {
            // 查询未支付订单列表
            List<Order> orders = orderService.listMemberOrderOfPendingPayment("000");
            // 筛选出超时15分钟未支付的订单
            List<Order> timeoutOrderList = new ArrayList<>();
            for (Order order : orders) {
                LocalDateTime start = order.getCreateTime();
                LocalDateTime now = LocalDateTime.now();
                Duration duration = Duration.between(start,now);
                long minutes = duration.toMinutes();
                if (minutes > 15) {
                    Order timeoutOrder = new Order();
                    timeoutOrder.setOrderId(order.getOrderId());
                    timeoutOrder.setOrderState(OrderStateEnum.CANCELED.getCode());
                    timeoutOrderList.add(order);
                }
            }
            // 更新订单状态为已取消
            if (CollectionUtils.isNotEmpty(timeoutOrderList)) {
                orderService.updateOrderState(timeoutOrderList);
            }

            taskLog.setTaskResult(1);
        } catch (Exception e) {
            taskLog.setTaskResult(0);
            taskLog.setErrorLog(e.getMessage());
        } finally {
            taskLogService.insertTaskLog(taskLog);
        }
    }
}
