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;


/**
 * 将完成时间超过7天的订单状态由待确认变更为已完成 定时任务
 * @author Dail
 */
@Component("memberOrderStateUpdateToFinishedTask")
public class MemberOrderStateUpdateToFinishedTask {

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

    @Autowired
    private IOrderService orderService;


    /**
     * 将完成时间超过7天的订单状态由待确认变更为已完成
     */
    public void updateOrderStateToFinishedForOverSevenDays(){
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName("将完成时间超过7天的订单状态更新为已完成");
        taskLog.setExecutionTime(LocalDateTime.now());
        try {
            // 查询待确认订单列表
            List<Order> orders = orderService.listMemberOrderOfPendingConfirm(OrderStateEnum.PENDING_CONFIRMED.getCode());
            // 筛选出服务完成时间超过7天的订单
            List<Order> timeoutOrderList = new ArrayList<>();
            for (Order order : orders) {
                LocalDateTime start = DateUtil.dateToLocalDateTime(order.getServiceEndTime());
                LocalDateTime now = LocalDateTime.now();
                Duration duration = Duration.between(start,now);
                long days = duration.toDays();
                if (days > 7) {
                    Order timeoutOrder = new Order();
                    timeoutOrder.setOrderId(order.getOrderId());
                    timeoutOrder.setOrderState(OrderStateEnum.FINISHED.getCode());
                    timeoutOrderList.add(timeoutOrder);
                }
            }
            // 更新订单状态为已完成
            if (CollectionUtils.isNotEmpty(timeoutOrderList)) {
                orderService.updateOrderState(timeoutOrderList);
            }

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