package cn.iocoder.yudao.module.order.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.order.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.order.service.order.OrderBusinessService;
import cn.iocoder.yudao.module.order.service.order.OrderQueryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Component
@TenantJob
@Slf4j
public class AirOrderPriceRefreshJob implements JobHandler {
    @Resource
    private OrderBusinessService orderBusinessService;
    @Resource
    private OrderQueryService orderQueryService;

    @Override
    public String execute(String param) {
        List<Integer> transportIdList = null;
        if (StringUtils.isNotBlank(param)) {
            transportIdList = Arrays.stream(param.split(StrUtil.COMMA)).filter(s -> StringUtils.equalsAny(s, "1", "2", "3", "4")).map(Integer::parseInt).collect(Collectors.toList());
            if (transportIdList == null || transportIdList.size() == 0){
                log.error("参数错误：{},此参数应为正确的运输方式id值", param);
            }
        } else {
            // 默认只查询专线空运订单
            transportIdList = new ArrayList<>();
            transportIdList.add(3);
        }
        // 获取空运需要每日定时刷新价格的订单列表(待入仓、入仓中、已入仓-待出空运订单)
        List<OrderDO> orderDOList = orderQueryService.getAirRefreshOrderPrice(transportIdList);
        if (CollectionUtil.isNotEmpty(orderDOList)) {
            log.info("开始刷新空运订单价格...");
            int num = 0;
            for (OrderDO orderDO : orderDOList) {
//                if (orderDO.getStatus() == 2 || orderDO.getStatus() == 3 || (orderDO.getStatus() == 5 && orderDO.getAirShipment() == 1)) {
                if (orderDO.getStatus() == 2 || orderDO.getStatus() == 3 || orderDO.getStatus() == 5) {
                    orderBusinessService.airOrderPriceRefresh(orderDO);
                    num++;
                }
            }
            log.info("刷新空运订单价格结束...共刷新{}单待出空运订单价格", num);
        }
        return "";
    }


}
