package com.younike.system.task;

import com.younike.common.utils.DateUtil;
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;


/**
 * 将过期的团购订单状态由待服务变更为已完成 定时任务
 * @author Dail
 */
@Component("groupOrderExpiredUpdateToFinishedTask")
public class GroupOrderExpiredUpdateToFinishedTask {

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

    @Autowired
    private IOrderService orderService;


    /**
     * 将过期的团购订单状态由待服务变更为已完成
     */
    public void updateOrderStateToFinishedForExpiredGroupOrder(){
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName("将过期的团购订单状态由待服务变更为已完成");
        taskLog.setExecutionTime(LocalDateTime.now());
        try {
            // 查询过期的待服务团购订单列表
            List<Order> orders = orderService.listExpiredGroupOrderOfPendingService(OrderStateEnum.PENDING_SERVICE.getCode());
            // 过期的待服务团购订单状态改为已完成
            List<Order> expiredOrderList = new ArrayList<>();
            for (Order order : orders) {
                Order expiredOrder = new Order();
                expiredOrder.setOrderId(order.getOrderId());
                expiredOrder.setOrderState(OrderStateEnum.FINISHED.getCode());
                expiredOrderList.add(expiredOrder);
            }
            // 更新订单状态为已完成
            if (CollectionUtils.isNotEmpty(expiredOrderList)) {
                orderService.updateOrderState(expiredOrderList);
            }

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