package com.cpop.mall.framework.task;

import com.cpop.core.service.RedisService;
import com.cpop.core.utils.SpringUtils;
import com.cpop.mall.business.entity.Order;
import com.cpop.mall.business.entity.OrderDetail;
import com.cpop.mall.business.service.OrderDetailService;
import com.cpop.mall.business.service.OrderService;
import com.cpop.mall.framework.constant.MallRedisConstant;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Map;
import java.util.stream.Collectors;

import static com.cpop.mall.business.entity.table.OrderDetailTableDef.ORDER_DETAIL;
import static com.cpop.mall.business.entity.table.OrderTableDef.ORDER;

/**
 * @author DB
 * @createTime 2023/11/03 14:56
 * @description 订单超时未支付任务
 */
public class OrderOverTimeUnPayTask implements Job {

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        //获取工单id
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        String orderId = jobDataMap.getString("orderId");
        OrderService orderService = SpringUtils.getBean(OrderService.class);
        Order order = orderService.getById(orderId);
        //订单存在并且订单仍然是未支付，修改订单为超时
        if (null != order && order.getOrderStatus() == 0) {
            orderService.updateChain().set(ORDER.ORDER_STATUS, 6).set(ORDER.PREVIOUS_STATUS, 0).where(ORDER.ID.eq(orderId)).update();
            //redis库存回滚
            RedisService redisService = SpringUtils.getBean(RedisService.class);
            Map<String, Integer> orderReturnMap = SpringUtils.getBean(OrderDetailService.class).queryChain()
                    .where(ORDER_DETAIL.ORDER_ID.eq(orderId))
                    .list()
                    .stream().collect(Collectors.toMap(OrderDetail::getProductRecordId, OrderDetail::getNumber));
            orderReturnMap.forEach((key, value) -> {
                redisService.longIncrement(MallRedisConstant.STOCK_RECORD_NUM + key, value.longValue());
            });
        }
    }
}
