package com.youchain.modules.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.youchain.businessdata.domain.AgvTask;
import com.youchain.businessdata.repository.AgvTaskRepository;
import com.youchain.businessdata.service.AgvTaskService;
import com.youchain.utils.BizStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 入库料箱任务
 */
@Slf4j
@Service
public class asnTask {
    @Autowired
    public AgvTaskRepository agvTaskRepository;

    @Autowired
    public AgvTaskService agvTaskService;

    private static final int MAX_TASK_COUNT = 4;
    private static final long TIMEOUT_MS = 2*60*1000; // 2分钟，以毫秒为单位
    private long lastTaskTime = System.currentTimeMillis();

    public void asnTask() {

        //查询待执行已扫描的入库AGV任务
        List<AgvTask> agvTasks = agvTaskRepository.queryByAgvTask(null, BizStatus.OPEN,BizStatus.ASN,1,"PICKER_MOVE");
        if(agvTasks.size()>0){
            if (agvTasks.size() == MAX_TASK_COUNT) {
                log.info("小件入库料箱任务已满足，当前任务数：" + agvTasks.size());
                String resultJson=agvTaskService.sendAgvTaskLXImpl(agvTasks);
                log.info(resultJson);
                lastTaskTime = System.currentTimeMillis();
            } else if (System.currentTimeMillis() - lastTaskTime >=TIMEOUT_MS) {
                if(agvTasks.size()>4){
                    List<AgvTask> newAgvTask = agvTasks.subList(0,4);
                    log.info("2分钟未满足4个小件入库料箱任务，当前任务数：" + newAgvTask.size());
                    String resultJson=agvTaskService.sendAgvTaskLXImpl(newAgvTask);
                    log.info(resultJson);
                }else{
                    log.info("2分钟未满足4个小件入库料箱任务，当前任务数：" + agvTasks.size());
                    String resultJson=agvTaskService.sendAgvTaskLXImpl(agvTasks);
                    log.info(resultJson);
                    lastTaskTime = System.currentTimeMillis();
                }
            }else{
                log.info("小件入库料箱任务未满足条件!");
            }
        }else{
            log.info("无小件入库料箱任务!");
        }




    }
}
