package org.springblade.modules.quartz.task;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.ParamCache;
import org.springblade.common.constant.CacheBizConstant;
import org.springblade.common.enums.OrderStateEnum;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.service.impl.OrderServiceImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Component("timedTask")
public class TimedTask {

    @Lazy
    @Resource
    private OrderServiceImpl orderService;

    /**
     * 修改订单状态
     */
    @Transactional
    public void updateOrderStatus() {
        try {
            int expirationTime = Integer.parseInt(ParamCache.getValueDefault(CacheBizConstant.ORDER_AFTER_SALES_DAYS, "3"));
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.add(Calendar.DAY_OF_MONTH, -expirationTime);
            Date time = c.getTime();
            int page = 1;
            int size = 10;
            while (true) {
                Page<Order> orderPage = orderService.getOrderByExpirationTime(new Page(page, size), time);
                List<Order> orders = orderPage.getRecords();
                if (orders.size() <= 0) {
                    return;
                }
                log.info("订单状态变更任务开始，orders size:[{}]", orders.size());
                for (Order order : orders) {
                    log.info("订单[{}]超过售后期，强制更新为已完成状态", order.getOrderNo());
                    order.setOrderState(OrderStateEnum.COMPLETED.getValue());
                }
                orderService.saveOrUpdateBatch(orders);
                page++;
            }
        } catch (Exception e) {
            log.error("订单状态变更异常" + e.getMessage(), e);
            throw e;
        }
    }


}
