package com.youchain.modules.quartz.task;

import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.service.PointService;
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 cpLineTask {

    @Autowired
    public StockService stockService;

    @Autowired
    private PointService pointService;

    @Autowired
    public AgvTaskService agvTaskService;

    @Autowired
    public KMReService kmReService;

    // 定义异常信息常量
    private static final String NO_EMPTY_SHELVES_ERROR_MSG = "成品入库区和成品入库缓存区都没有空闲点位，请及时处理!";

    public void sendAgvCpOffLine() {
        // 获取处于特定业务状态的AGV任务列表
        List<AgvTask> agvTaskList = agvTaskService.findOpenByAgvTask(BizStatus.Cp_Off_Line);
        // 如果任务列表为空，直接返回，避免不必要的处理
        if (agvTaskList.isEmpty()) {
            return;
        }
        // 遍历AGV任务列表
        for (AgvTask agvTask : agvTaskList) {
            processAgvTask(agvTask);
        }
    }

    private void processAgvTask(AgvTask agvTask) {
        if (agvTask.getEndSlotCode() != null) {
            kmReService.sendAgvTask(agvTask, kmReService.sendAgvTaskHjJson(agvTask));
        } else {
            // 查找可用的结束点
            Point endPoint = findAvailableEndPoint();
            if (endPoint != null) {
                updateAgvTaskWithEndPoint(agvTask, endPoint);
                kmReService.sendAgvTask(agvTask, kmReService.sendAgvTaskHjJson(agvTask));
            } else {
                // 若未找到可用结束点，抛出异常
                throw new BadRequestException(NO_EMPTY_SHELVES_ERROR_MSG);
            }
        }
    }

    private void updateAgvTaskWithEndPoint(AgvTask agvTask, Point endPoint) {
        // 设置任务的结束插槽代码
        agvTask.setEndSlotCode(endPoint.getCode());
        // 更新AGV任务信息
        agvTaskService.update(agvTask);
    }

    /**
     * 查找可用的终点点位，优先从成品入库区查找，若没有则从成品下线缓存区查找
     *
     * @return 可用的终点点位，如果没有则返回null
     */
    private Point findAvailableEndPoint() {
        List<Point> endPointList = pointService.queryPoints(null, BaseStatus.FREE, BaseStatus.BOX, AreaNameDic.CPRKQ);
        return endPointList.isEmpty() ? null : endPointList.get(0);
    }


}
