package com.ruoyi.jarvis.task;

import com.ruoyi.jarvis.config.JarvisGoofishProperties;
import com.ruoyi.jarvis.domain.ErpOpenConfig;
import com.ruoyi.jarvis.service.IErpGoofishOrderService;
import com.ruoyi.jarvis.service.IErpOpenConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

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

/**
 * 闲管家 ERP：定时拉单与运单同步/自动发货
 */
@Component
public class GoofishScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(GoofishScheduledTasks.class);

    @Resource
    private IErpOpenConfigService erpOpenConfigService;

    @Resource
    private IErpGoofishOrderService erpGoofishOrderService;

    @Resource
    private JarvisGoofishProperties goofishProperties;

    @Scheduled(cron = "${jarvis.goofish-order.pull-cron:0 * * * * ?}")
    public void scheduledPull() {
        List<ErpOpenConfig> cfgs = erpOpenConfigService.selectEnabledOrderBySort();
        if (cfgs == null || cfgs.isEmpty()) {
            return;
        }
        int hours = goofishProperties.getPullLookbackHours();
        int n = 0;
        for (ErpOpenConfig c : cfgs) {
            try {
                n += erpGoofishOrderService.pullOrdersForAppKey(c.getAppKey(), hours);
            } catch (Exception e) {
                log.warn("定时拉单失败 appKey={} {}", c.getAppKey(), e.getMessage());
            }
        }
        if (n > 0) {
            log.info("闲管家定时拉单本轮处理约 {} 条子订单项", n);
            try {
                int synced = erpGoofishOrderService.syncWaybillAndTryShipBatch(goofishProperties.getAutoShipBatchSize());
                if (synced > 0) {
                    log.info("拉单后轮询：运单同步/自动发货扫描处理 {} 条", synced);
                }
            } catch (Exception syncEx) {
                log.warn("拉单后轮询运单同步/发货扫描异常 {}", syncEx.getMessage());
            }
        }
    }

    @Scheduled(cron = "${jarvis.goofish-order.auto-ship-cron:0 2/10 * * * ?}")
    public void scheduledWaybillAndShip() {
        try {
            int k = erpGoofishOrderService.syncWaybillAndTryShipBatch(goofishProperties.getAutoShipBatchSize());
            if (k > 0) {
                log.info("闲管家运单同步与发货扫描处理 {} 条", k);
            }
        } catch (Exception e) {
            log.warn("闲管家自动发货扫描异常 {}", e.getMessage());
        }
    }
}
