package com.youchain.modules.quartz.task;

import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.service.StockService;
import com.youchain.businessdata.domain.AgvTask;
import com.youchain.businessdata.service.AgvTaskService;
import com.youchain.businessdata.service.KMReService;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.AreaNameDic;
import com.youchain.utils.BaseStatus;
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.List;

/**
 * 成品上线任务
 */
@Slf4j
@Service
public class cpUpTask {

    @Autowired
    public StockService stockService;

    @Autowired
    public AgvTaskService agvTaskService;

    @Autowired
    public KMReService kmReService;

    // 定义异常信息常量
    private static final String NO_EMPTY_SHELVES_ERROR_MSG = "成品入库区和成品入库缓存区都没有空货架，请及时解绑容器!";

    /**
     * 轮询下发成品上线任务
     */
    public void sendAgvCpOffUp() {
        List<AgvTask> agvTaskList = agvTaskService.findOpenByAgvTask(BizStatus.Cp_Off_Up);
        if (agvTaskList.isEmpty()) {
            return;
        }
        // 遍历AGV任务列表
        for (AgvTask agvTask : agvTaskList) {
            processAgvTask(agvTask);
        }
    }

    private List<Stock> getEmptyStockList() {
        List<Stock> emptyStockList = stockService.findByFreeOrUsedStock(AreaNameDic.CPRKQ, BaseStatus.FREE);
        return emptyStockList;
    }

    private void processAgvTask(AgvTask agvTask) {
        if (agvTask.getStockCode() != null && agvTask.getStartSlotCode() != null) {
            //直接下发
            kmReService.sendAgvTask(agvTask, kmReService.sendAgvTaskHjJson(agvTask));
        } else {
            //排队任务 查询成品入库区是否有空车
            List<Stock> stocks = getEmptyStockList();
            if (!stocks.isEmpty()) {
                // 获取第一个空库存
                Stock stock = stocks.get(0);
                // 更新AGV任务的库存代码和起始插槽代码
                updateAgvTask(agvTask, stock);
                kmReService.sendAgvTask(agvTask, kmReService.sendAgvTaskHjJson(agvTask));
            } else {
                // 若没有空货架，抛出异常
                throw new BadRequestException(NO_EMPTY_SHELVES_ERROR_MSG);
            }
        }
    }

    private void updateAgvTask(AgvTask agvTask, Stock stock) {
        // 设置AGV任务的库存代码
        agvTask.setStockCode(stock.getCode());
        // 设置AGV任务的起始插槽代码
        agvTask.setStartSlotCode(stock.getPoint() == null ? null : stock.getPoint().getCode());
        // 更新AGV任务
        agvTaskService.update(agvTask);
    }
}
