package com.youchain.modules.quartz.task;

import com.youchain.basicdata.service.StockService;
import com.youchain.businessdata.domain.Pick;
import com.youchain.businessdata.repository.PickRepository;
import com.youchain.businessdata.service.PickDetailService;
import com.youchain.businessdata.service.PickService;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

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

    @Autowired
    public PickRepository pickRepository;

    @Autowired
    public PickDetailService pickDetailService;

    @Autowired
    public PickService pickService;

    @Autowired
    public StockService stockService;

    /**
     * 定时检测打开和分配中的出库单，分配库存
     */
    public void allocatePick() {
        List<String> statuses = Arrays.asList(BizStatus.OPEN, BizStatus.ASSIGN);
        List<Pick> pickList = pickRepository.findByPickStatus(statuses,false);
        if (pickList.isEmpty()) {
            throw new BadRequestException("无待分配的出库单,分配失败!");
        } else {
            for (Pick pick : pickList) {
                pickDetailService.allocatePick(pick);
            }
        }
    }

    /**
     * 定时检测已分配的出库单，生成《备料》搬运任务
     */
    public void pickAgvTask() {
        /*查询分配完成的出库单*/
        List<String> statuses = Arrays.asList(BizStatus.ALLOCATE);
        List<Pick> pickList = pickRepository.findByPickStatus(statuses,false);
        if (pickList.isEmpty()) {
            throw new BadRequestException("无已分配的出库单,下发任务失败!");
        } else {
            for (Pick pick : pickList) {
                pickService.materialPick(pick);
            }
        }
    }

    public void callJlTask() {
        /*查询拣货完成完成的出库单*/
        List<String> statuses = Arrays.asList(BizStatus.PICK_ALL);
        List<Pick> pickList = pickRepository.findByPickStatus(statuses,true);
        if (pickList.isEmpty()) {
            throw new BadRequestException("无拣货完成的出库单或出库单为未叫料,呼叫货架失败!");
        } else {
            for (Pick pick : pickList) {
                stockService.callJlTask(pick);
            }
        }
    }

}
