package com.hys.app.controller.erp.use.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hys.app.mapper.erp.OrderReturnMapper;
import com.hys.app.model.erp.dos.OrderDO;
import com.hys.app.model.erp.dos.OrderReturnDO;
import com.hys.app.model.erp.enums.ReturnOrderStatusEnum;
import com.hys.app.model.erp.enums.SaleOrderStatusEnum;
import com.hys.app.service.erp.OrderManager;
import com.hys.app.service.erp.OrderReturnManager;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Component
@AllArgsConstructor
public class OrderReturnTask {

    private OrderReturnMapper orderReturnMapper;
    private OrderReturnManager orderReturnManager;
    private OrderManager orderManager;

    @Scheduled(cron = "0 0 1 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void executeTask() {
        //找到所有15天未关闭的售后订单
        List<OrderReturnDO> list = orderReturnMapper.getAllNotClosedReturn();
        list.forEach(item -> item.setStatus(ReturnOrderStatusEnum.SALE_AFTER_END));
        if (orderReturnManager.updateBatchById(list)) {
            //找到所有售后单的订单
            List<Long> collect = list.stream().map(OrderReturnDO::getOrderId).collect(Collectors.toList());
            //如果这个订单下面的所有售后订单都做完了，把订单的状态从售后中改成售后完成
            for (Long id : collect) {
                List<OrderReturnDO> orderReturnDOS = orderReturnMapper.selectList(new LambdaQueryWrapper<OrderReturnDO>()
                        .eq(OrderReturnDO::getOrderId, id)
                        .eq(OrderReturnDO::getStatus, ReturnOrderStatusEnum.SALE_AFTER_ING));
                if (CollUtil.isEmpty(orderReturnDOS)) {
                    OrderDO aDo = orderManager.getById(id);
                    if (SaleOrderStatusEnum.SALE_AFTER_ING.equals(aDo.getStatus())) {
                        aDo.setStatus(SaleOrderStatusEnum.SALE_AFTER_END);
                        orderManager.updateById(aDo);
                    }
                }
            }
        }
    }
}