package com.qs.mp.quartz.task;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.TemporalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.channel.domain.ChannelOrder;
import com.qs.mp.common.enums.ChannelOrderStatusEnum;
import com.qs.mp.common.enums.DeliverOrderResourceEnum;
import com.qs.mp.common.enums.DeliverOrderStatusEnum;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.user.domain.UserDeliverOrder;
import com.qs.mp.user.domain.param.UserDeliverOrderCancelParam;
import com.qs.mp.user.service.IUserDeliverOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 用户提货订单任务
 * @author Cup
 * @date 2022/4/20
 */
@Component("userDeliverOrderTask")
public class UserDeliverOrderTask {


    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());

    @Autowired
    private IUserDeliverOrderService userDeliverOrderService;

    private final int PAGE_SIZE = 500;


    /**
     * x天前的待收货订单自动确认收货任务
     */
    public void confirm(Integer day) {
        LogUtil.info(logger, "...用户提货订单自动确认收货任务开始...");
        LocalDateTime now = LocalDateTimeUtil.now();
        LocalDateTime deliveryTime = LocalDateTimeUtil.offset(now, -day, ChronoUnit.DAYS);

        List<UserDeliverOrder> userDeliverOrderList = userDeliverOrderService.list(new LambdaQueryWrapper<UserDeliverOrder>()
                .eq(UserDeliverOrder::getStatus, DeliverOrderStatusEnum.NOT_CONFIRM.getValue())
                .le(UserDeliverOrder::getDeliveryTime, deliveryTime));

        List<UserDeliverOrder> params = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userDeliverOrderList)) {
            for (UserDeliverOrder userDeliverOrder : userDeliverOrderList) {
                UserDeliverOrder param = new UserDeliverOrder();
                param.setOrderId(userDeliverOrder.getOrderId());
                param.setConfirmTime(new Date());
                param.setStatus(DeliverOrderStatusEnum.FINISHED);
                params.add(param);
            }
        }
        userDeliverOrderService.updateBatchById(params);

        LogUtil.info(logger, "...用户提货订单自动确认收货任务结束...");
    }

    /**
     * 订单取消到期任务
     */
    public void cancel() {
        LogUtil.info(logger, "...用户提货未支付订单定时取消任务开始...");
        int total = PAGE_SIZE;
        while (total == PAGE_SIZE) {
            // 捞取30分钟前未支付订单
            List<UserDeliverOrder> userDeliverOrderList = userDeliverOrderService.list(
                new LambdaQueryWrapper<UserDeliverOrder>()
                    .eq(UserDeliverOrder::getStatus, DeliverOrderStatusEnum.NOT_PAY)
                    .lt(UserDeliverOrder::getCreatedTime, DateUtils.addMinutes(DateUtils.getNowDate(), -30))
                    .last("limit " + PAGE_SIZE));
            total = userDeliverOrderList.size();
            for (UserDeliverOrder userDeliverOrder : userDeliverOrderList) {
                try {
                    userDeliverOrderService.cancelOrder(userDeliverOrder.getOrderId());
                } catch (Exception e) {
                    LogUtil.error(logger, e, "定时取消未支付用户提货订单异常。orderId:{0}", userDeliverOrder.getOrderId());
                }
            }
        }
        LogUtil.info(logger, "...用户提货未支付订单定时取消任务结束...");
    }

}
