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.BaseStatus;
import com.youchain.utils.BizStatus;
import com.youchain.utils.HttpPostUtil;
import com.youchain.utils.UrlApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 料箱出库任务下发
 */
@Slf4j
@Service
public class pickTask {

    @Autowired
    public AgvTaskService agvTaskService;

    private static final int MAX_TASK_COUNT = 5;

    private static final long TIMEOUT_MS = 2*60*1000;
    private long lastTaskTime = System.currentTimeMillis();

    public void pickTask() {
        // 下发出库任务
        List<AgvTask> agvTaskList = agvTaskService.queryByAgvTask(BizStatus.OPEN,BizStatus.PICK);
        if (agvTaskList.size() > 0) {
            if ((agvTaskList.size() == MAX_TASK_COUNT)) {
                Result(agvTaskService.sendAgvTaskLXImpl(agvTaskList));
                lastTaskTime = System.currentTimeMillis();
            }else if((System.currentTimeMillis() - lastTaskTime >=TIMEOUT_MS) ){
                if(agvTaskList.size()>MAX_TASK_COUNT){
                    List<AgvTask> newAgvTask = agvTaskList.subList(0,MAX_TASK_COUNT);
                    Result(agvTaskService.sendAgvTaskLXImpl(newAgvTask));
                }else{
                    Result(agvTaskService.sendAgvTaskLXImpl(agvTaskList));
                    lastTaskTime = System.currentTimeMillis();
                }
            } else {
                throw new RuntimeException("出库料箱任务未满足条件(不满足五个料箱需等待2分钟)!");
            }
        } else {
            throw new RuntimeException("无出库料箱任务!");
        }


    }

    private void Result(String result) {
        if(result==null ||result.length()==0){
            throw new RuntimeException("任务下发失败!");
        }
    }



}
