/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.businessdata.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.youchain.basicdata.domain.Point;
import com.youchain.basicdata.domain.Stock;
import com.youchain.basicdata.repository.StockRepository;
import com.youchain.basicdata.service.PointService;
import com.youchain.businessdata.domain.*;
import com.youchain.businessdata.repository.InventoryRepository;
import com.youchain.businessdata.repository.PickRepository;
import com.youchain.businessdata.repository.TaskRepository;
import com.youchain.businessdata.service.*;
import com.youchain.exception.BadRequestException;
import com.youchain.modules.quartz.utils.TimeNumberUtils;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.businessdata.repository.AgvTaskRepository;
import com.youchain.businessdata.service.dto.AgvTaskDto;
import com.youchain.businessdata.service.dto.AgvTaskQueryCriteria;
import com.youchain.businessdata.service.mapstruct.AgvTaskMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;


/**
 * @author baobinglin
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-18
 **/
@Service
@RequiredArgsConstructor
@Slf4j
public class AgvTaskServiceImpl implements AgvTaskService {

    private final AgvTaskRepository agvTaskRepository;
    private final AgvTaskMapper agvTaskMapper;
    private final TaskService taskService;
    private final TaskRepository taskRepository;
    private final InventoryService inventoryService;
    private final InventoryLogService inventoryLogService;
    private final InventoryRepository inventoryRepository;
    private final PointService pointService;
    private final AsnDetailService asnDetailService;
    private final StockRepository stockRepository;
    private final PickRepository pickRepository;

    @Override
    public Map<String, Object> queryAll(AgvTaskQueryCriteria criteria, Pageable pageable) {
        Page<AgvTask> page = agvTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(agvTaskMapper::toDto));
    }

    @Override
    public List<AgvTaskDto> queryAll(AgvTaskQueryCriteria criteria) {
        return agvTaskMapper.toDto(agvTaskRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public AgvTaskDto findById(Long id) {
        AgvTask agvTask = agvTaskRepository.findById(id).orElseGet(AgvTask::new);
        ValidationUtil.isNull(agvTask.getId(), "AgvTask", "id", id);
        return agvTaskMapper.toDto(agvTask);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AgvTaskDto create(AgvTask resources) {
        return agvTaskMapper.toDto(agvTaskRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AgvTask resources) {
        AgvTask agvTask = agvTaskRepository.findById(resources.getId()).orElseGet(AgvTask::new);
        ValidationUtil.isNull(agvTask.getId(), "AgvTask", "id", resources.getId());
        agvTask.copy(resources);
        agvTaskRepository.save(agvTask);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            agvTaskRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<AgvTaskDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AgvTaskDto agvTask : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("容器码", agvTask.getStockCode());
            map.put("容器类型", agvTask.getStockTypeCode());
            map.put("起点位置", agvTask.getStartSlotCode());
            map.put("终点位置", agvTask.getEndSlotCode());
            map.put("容器当前位置", agvTask.getSlotCode());
            map.put("任务状态", agvTask.getStatus());
            map.put("任务类型", agvTask.getType());
            map.put("下游任务号", agvTask.getJobId());
            map.put("工作类型", agvTask.getJobType());
            map.put("优先级", agvTask.getJobPriority());
            map.put("强制优先级", agvTask.getJobPriorityType());
            map.put("任务组", agvTask.getJobForce());
            map.put("任务组执行顺序", agvTask.getJobForceAsc());
            map.put("返回报文", agvTask.getJobMessage());
            map.put("变动时间", agvTask.getJobMessageTime());
            map.put("创建时间", agvTask.getCreateTime());
            map.put("开始时间", agvTask.getStartTime());
            map.put("完成时间", agvTask.getEndTime());
            map.put("创建人", agvTask.getCreateBy());
            map.put("修改人", agvTask.getUpdateBy());
            map.put("修改时间", agvTask.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * @param agvTasks
     * @return
     */
    @Override
    public synchronized void sendAgvTaskCCImpl(AgvTask agvTasks) {

        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());

        Map<String, Object> objMap = new LinkedHashMap<>();
        objMap.put("orgId", agvTasks.getId());//库存组织 ID
        objMap.put("requestId", agvTasks.getId());//请求 id
        objMap.put("missionCode", agvTasks.getId());//任务编号
        objMap.put("missionType", agvTasks.getJobType());//货 架 ( 托 盘 ) 移动 RACK_MOVE
        objMap.put("viewBoardType", "");//
        objMap.put("containerCode", agvTasks.getStockCode());//
        objMap.put("robotType", "FORKLIFT");//机器人功能类型
        objMap.put("priority", "1");//数值越小，优先级越高，默认是 1
        JSONArray missionDataArray = new JSONArray();
        JSONObject missionDataObj = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap = new LinkedHashMap<>();
        missionDataMap.put("sequence", 1);//序号
        missionDataMap.put("position", agvTasks.getStartSlotCode());//点位
        String nodeType = "NODE_POINT";
        if (BizStatus.PICK.equals(agvTasks.getType())) {
            nodeType = "NODE_SLOT";
        }
        missionDataMap.put("nodeType", nodeType);//
        missionDataMap.put("stackNumber", 0);
        missionDataMap.put("actionConfirm", false);
        missionDataObj.putAll(missionDataMap);
        missionDataArray.add(missionDataObj);

        JSONObject missionDataObj2 = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap2 = new LinkedHashMap<>();
        missionDataMap2.put("sequence", 2);//序号
        missionDataMap2.put("position", agvTasks.getEndSlotCode());//目标点
        String nodeType2 = "NODE_SLOT";
        if (BizStatus.PICK.equals(agvTasks.getType())) {
            nodeType2 = "NODE_POINT";
        }
        missionDataMap2.put("nodeType", nodeType2);//
        missionDataMap2.put("stackNumber", 0);
        missionDataMap2.put("actionConfirm", false);
        missionDataObj2.putAll(missionDataMap2);
        missionDataArray.add(missionDataObj2);

        objMap.put("missionData", missionDataArray);
        jsonObject.putAll(objMap);

        sendAgvTask(agvTasks, jsonObject.toString());
    }

    @Override
    public synchronized void sendAgvTaskHJImpl(AgvTask agvTasks) {
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());

        Map<String, Object> objMap = new LinkedHashMap<>();
        objMap.put("orgId", agvTasks.getId());//库存组织 ID
        objMap.put("requestId", agvTasks.getId());//请求 id
        objMap.put("missionCode", agvTasks.getId());//任务编号
        objMap.put("missionType", agvTasks.getJobType());//货 架 ( 托 盘 ) 移动 RACK_MOVE
        objMap.put("viewBoardType", "");//IDENTIFY_REQUIRE
        objMap.put("robotType", "LIFT");//机器人功能类型
        objMap.put("priority", "1");//数值越小，优先级越高，默认是 1
        JSONArray missionDataArray = new JSONArray();
        JSONObject missionDataObj = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap = new LinkedHashMap<>();
        missionDataMap.put("sequence", 1);//序号
        missionDataMap.put("containerCode", agvTasks.getStockCode());//容器
        missionDataMap.put("startPosition", agvTasks.getStartSlotCode());//点位
        missionDataMap.put("startPositionType", "NODE_POINT");//
        missionDataMap.put("endPosition", agvTasks.getEndSlotCode());//点位
        missionDataMap.put("endPositionType", "NODE_POINT");//
        missionDataObj.putAll(missionDataMap);
        missionDataArray.add(missionDataObj);

        objMap.put("missionData", missionDataArray);
        jsonObject.putAll(objMap);

        sendAgvTask(agvTasks, jsonObject.toString());
    }

    @Override
    public synchronized String sendAgvTaskLXImpl(List<AgvTask> agvTasks) {
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
        String agvCode = TimeNumberUtils.getXJTaskCode();
        Map<String, Object> objMap = new LinkedHashMap<>();
        objMap.put("orgId", agvCode);//库存组织 ID(或工厂代码，供应商代码)
        objMap.put("requestId", agvCode);//请求 id
        objMap.put("missionCode", agvCode);//任务编号
        objMap.put("missionType", "PICKER_MOVE");//任务类型 ：料箱
        objMap.put("viewBoardType", "");//上视识别类型:
        objMap.put("robotType", "PICKER");//机器人功能类型
        JSONArray robotModels = new JSONArray();
        objMap.put("robotModels", robotModels);//机器人具体型号
        JSONArray robotIds = new JSONArray();
        objMap.put("robotIds", robotIds);//机器人编号
        objMap.put("priority", "1");//数值越小，优先级越高，默认是 1
        objMap.put("templateCode", "");//作业流程模板编号
        objMap.put("lockRobotAfterFinish", false);//是否需要流程结束后机器人保持任务锁定状态
        objMap.put("unlockRobotId", "");//解锁当前小车的在上个任务的锁定状态
        objMap.put("unlockMissionCode", "");//当前小车的上一个任务
        objMap.put("idleNode", "");//作业流程完成后，指定机器人停放区域/点

        JSONArray missionDataArray = new JSONArray();
        for (int i = 0; i < agvTasks.size(); i++) {
            AgvTask agvTask = agvTasks.get(i);
            JSONObject missionDataObj = new JSONObject(new LinkedHashMap<>());
            Map<String, Object> missionDataMap = new LinkedHashMap<>();
            missionDataMap.put("sequence", (i + 1));//序号
            missionDataMap.put("binCode", agvTask.getStockCode());//料箱号
            missionDataMap.put("startPosition", "");//料箱所在的起始点位
            missionDataMap.put("startSlotCode", agvTask.getStartSlotCode());//料箱所在的起始槽位
            missionDataMap.put("takeActionConfirm", false);//取料箱时之前是否需确认
            missionDataMap.put("endPosition", "");//料箱所在的目标点位
            missionDataMap.put("endSlotCode", agvTask.getEndSlotCode());//料箱所在的目标槽位
            missionDataMap.put("putActionConfirm", false);//放料箱时之前是否需要确认
            missionDataObj.putAll(missionDataMap);
            missionDataArray.add(missionDataObj);
        }

        objMap.put("missionData", missionDataArray);
        jsonObject.putAll(objMap);
        System.out.println(jsonObject.toString());
        String resultJson = HttpPostUtil.sendPostReq(UrlApi.submitMission(), jsonObject.toString());
        JSONObject resulObject = JSON.parseObject(resultJson);
        String code = resulObject.getString("code") == null ? "" : resulObject.getString("code");
        if ("0".equals(code)) {
            for (int i = 0; i < agvTasks.size(); i++) {
                AgvTask agvTask = agvTasks.get(i);
                agvTask.setJobForce(agvCode);//任务组
                agvTask.setJobForceAsc((i + 1));
                agvTask.setStatus(BizStatus.ATCALL);
                agvTask.setJobMessage(resultJson);
                agvTask.setReqMessage(jsonObject.toString());
                agvTask.setStartTime(new Timestamp(new Date().getTime()));
                agvTaskRepository.save(agvTask);
            }
        } else {
            for (int i = 0; i < agvTasks.size(); i++) {
                AgvTask agvTask = agvTasks.get(i);
                agvTask.setJobMessage(resultJson);
                agvTask.setReqMessage(jsonObject.toString());
                agvTaskRepository.save(agvTask);
            }
        }
        return resultJson;
    }

    @Override
    public synchronized void sendAgvTaskGTImpl(AgvTask agvTask) {
        JSONObject jsonObject = new JSONObject(new LinkedHashMap<>());
        String agvCode = TimeNumberUtils.getGTTaskCode();
        Map<String, Object> objMap = new LinkedHashMap<>();
        objMap.put("orgId", agvCode);//库存组织 ID(或工厂代码，供应商代码)
        objMap.put("requestId", agvCode);//请求 id
        objMap.put("missionCode", agvCode);//任务编号
        objMap.put("missionType", "ROLLER_MOVE");//任务类型 ：滚筒
        objMap.put("viewBoardType", "");//上视识别类型:
        objMap.put("robotType", "ROLLER");
        objMap.put("priority", "1");
        objMap.put("lockRobotAfterFinish", false);
        JSONArray missionDataArray = new JSONArray();

        JSONObject missionDataObj = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap = new LinkedHashMap<>();
        missionDataMap.put("sequence", 1);//序号
        missionDataMap.put("position", agvTask.getStartSlotCode());//起点
        missionDataMap.put("type", "NODE_POINT");//
        missionDataMap.put("actionType", "ROLLER_RECEIVE");//
        missionDataMap.put("binCode", agvTask.getStockCode());//容器
        missionDataMap.put("rollerLevel", 1);//
        missionDataMap.put("deviceCode", agvTask.getSlotCode());//设备编号
        missionDataMap.put("actionConfirm", true);//
        missionDataMap.put("passStrategy", "AUTO");//
        missionDataObj.putAll(missionDataMap);
        missionDataArray.add(missionDataObj);

        JSONObject missionDataObj2 = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap2 = new LinkedHashMap<>();
        missionDataMap2.put("sequence", 2);//序号
        missionDataMap2.put("position", agvTask.getEndSlotCode());//起点
        missionDataMap2.put("type", "NODE_POINT");//
        missionDataMap2.put("actionType", "");//
        missionDataMap2.put("binCode", agvTask.getStockCode());//容器
        missionDataMap2.put("rollerLevel", 1);//
        missionDataMap2.put("deviceCode", "");//
        missionDataMap2.put("actionConfirm", false);//
        missionDataMap2.put("passStrategy", "MANUAL");//
        missionDataObj2.putAll(missionDataMap2);
        missionDataArray.add(missionDataObj2);

        JSONObject missionDataObj3 = new JSONObject(new LinkedHashMap<>());
        Map<String, Object> missionDataMap3 = new LinkedHashMap<>();
        missionDataMap3.put("sequence", 3);//序号
        missionDataMap3.put("position", agvTask.getStartSlotCode());//起点
        missionDataMap3.put("type", "NODE_POINT");//
        missionDataMap3.put("actionType", "ROLLER_RECEIVE");//
        missionDataMap3.put("binCode", agvTask.getStockCode());//容器
        missionDataMap3.put("rollerLevel", 1);//
        missionDataMap3.put("deviceCode", agvTask.getSlotCode());//
        missionDataMap3.put("actionConfirm", true);//
        missionDataMap3.put("passStrategy", "AUTO");//
        missionDataObj3.putAll(missionDataMap3);
        missionDataArray.add(missionDataObj3);

        objMap.put("missionData", missionDataArray);
        jsonObject.putAll(objMap);

        sendAgvTask(agvTask, jsonObject.toString());//发送任务
    }

    private void sendAgvTask(AgvTask agvTask, String json) {
       /* String resultJson = HttpPostUtil.sendPostReq(UrlApi.submitMission(), json);
        if (StringUtils.isEmpty(resultJson)) {
            throw new BadRequestException("AGV返回信息:下发任务接口调用失败!");
        }
        JSONObject resulObject = JSON.parseObject(resultJson);
        if (resulObject == null) {
            throw new BadRequestException("AGV返回信息:下发任务接口返回为空!");
        }

        String code = resulObject.getString("code");
        String message = resulObject.getString("message");*/
        String code = "0";
        String message = "";
        String resultJson = "";
        if (!"0".equals(code)) {
            throw new BadRequestException("AGV返回信息:" + message);
        } else {
            agvTask.setJobForce(agvTask.getId().toString());//任务组
            agvTask.setJobForceAsc((1));
            agvTask.setStatus(BizStatus.ATCALL);
            agvTask.setJobMessage(resultJson);
            agvTask.setReqMessage(json);
            agvTask.setStartTime(new Timestamp(new Date().getTime()));
            agvTaskRepository.save(agvTask);
        }

    }

    @Override
    public AgvTask toEntity(AgvTaskDto agvTaskDto) {
        return agvTaskMapper.toEntity(agvTaskDto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void agvTaskCallback(AgvTask agvTask, String status, String containerCode) {
        switch (status) {
            case "UP_CONTAINER":
            case "FORK_UP":
                handleUpContainer(agvTask, containerCode);//容器顶升
                break;
            case "FORK_DOWN":
                handleForkDownContainer(agvTask, containerCode);//容器放下
                break;
            case "COMPLETED":
                handleComContainer(agvTask, containerCode);//搬运任务完成
                break;
            case "CANCELED":
                handleCanceledTask(agvTask, containerCode);//容器取消
                break;
            case "RESEND":
                handleResendTask(agvTask);//重新发送
                break;
        }

    }

    @Override
    public void callEmptyStock(String goodType) {
        String srcAreaCode = "小件".equals(goodType) ? AreaNameDic.JLQ : AreaNameDic.JLQ;
        String dstAreaCode = "小件".equals(goodType) ? AreaNameDic.XJFBCQ : AreaNameDic.DJFBCQ;

        List<Stock> emptyStock = stockRepository.findByEnmptyStock(srcAreaCode);
        if (emptyStock.isEmpty()) {
            return;
        }

        Stock stock = emptyStock.get(0);
        Point srcPoint = stock.getPoint();
        Point endPoint = pointService.findByCode(null, BaseStatus.FREE, BaseStatus.BOX, dstAreaCode, null, null);

        if (endPoint == null) {
            return;
        }

        AgvTask agvTask = new AgvTask(BizStatus.CALL_RETURN, stock.getCode(), srcPoint.getCode(), endPoint.getCode(), BizStatus.OPEN, "RACK_MOVE");
        agvTaskRepository.save(agvTask);
        sendAgvTaskHJImpl(agvTask);

        endPoint.setStatus(BaseStatus.USED);
        pointService.update(endPoint);

    }

    private void handleUpContainer(AgvTask agvTask, String containerCode) {
        //顶升释放起点位置状态及容器绑定的起点位置
        Point startPoint = pointService.findByCode(agvTask.getStartSlotCode(), null, null, null, null, null);
        startPoint.setStatus(BaseStatus.FREE);
        pointService.update(startPoint);

        agvTask.setStockCode(containerCode);
        agvTask.setStatus(BizStatus.UP_CONTAINER);
        agvTask.setStartTime(new Timestamp(new Date().getTime()));
        agvTaskRepository.save(agvTask);
    }

    /**
     * 搬运任务完成
     */
    private void handleComContainer(AgvTask agvTask, String containerCode) {
        //任务完成；根据AGV任务的目标点位走对应流程
        Point endPoint = pointService.findByCode(agvTask.getEndSlotCode(), null, null, null, null, null);
        String endAreaName = endPoint.getArea().getCode();
        Stock stock = stockRepository.findByCode(containerCode, null);
        if (stock == null) {
            throw new BadRequestException(containerCode + "容器不存在! 请维护");
        }
        List<Task> taskList = taskService.getAgvTaskList(agvTask.getId());
        switch (endAreaName) {
            case AreaNameDic.XJFBQ:
            case AreaNameDic.DJFBQ:
                handleFbq(taskList, stock, endPoint);//备料完成
                break;
            case AreaNameDic.JLQ:
                handleJl(stock, endPoint, agvTask);//叫料完成
                break;
            case AreaNameDic.XJFBCQ:
            case AreaNameDic.DJFBCQ:
                handleCPXXAndCPRK(endPoint, stock);//叫料返空完成
                break;
            case AreaNameDic.CPXXQ:
            case AreaNameDic.CPRKQ:
                handleCPXXAndCPRK(endPoint, stock);//空货架-成品下线区;满货架-成品入库区
                break;
        }

        agvTask.setStatus(BizStatus.FINISH);
        agvTask.setStockCode(containerCode);
        agvTask.setEndTime(new Timestamp(new Date().getTime()));
        agvTaskRepository.save(agvTask);
    }

    private void handleForkDownContainer(AgvTask agvTask, String containerCode) {
        //任务完成；根据AGV任务的目标点位走对应流程
        Point endPoint = pointService.findByCode(agvTask.getEndSlotCode(), null, null, null, null, null);
        String endAreaName = endPoint.getArea().getCode();
        Stock stock = stockRepository.findByCode(containerCode, null);
        if (stock == null) {
            throw new BadRequestException(containerCode + "容器不存在! 请维护");
        }
        List<Task> taskList = taskService.getAgvTaskList(agvTask.getId());
        switch (endAreaName) {
            case AreaNameDic.XJQ:
            case AreaNameDic.DJQ:
                handleXJDJ(agvTask, taskList, stock);//入库完成
                break;
        }

        agvTask.setStatus(BizStatus.FINISH);
        agvTask.setStockCode(containerCode);
        agvTask.setEndTime(new Timestamp(new Date().getTime()));
        agvTaskRepository.save(agvTask);
    }

    private synchronized void handleResendTask(AgvTask agvTask) {
        List<AgvTask> repeatList = agvTaskRepository.findRepeat(agvTask.getStockCode());
        if (!repeatList.isEmpty()) {
            throw new BadRequestException("任务已重新生成，请勿重复操作! ");
        }
        AgvTask newAgvTask = new AgvTask();
        newAgvTask.setStockCode(agvTask.getStockCode());
        newAgvTask.setStartSlotCode(agvTask.getStartSlotCode());
        newAgvTask.setEndSlotCode(agvTask.getEndSlotCode());
        newAgvTask.setSlotCode(agvTask.getSlotCode());
        newAgvTask.setStatus(BizStatus.OPEN);
        newAgvTask.setType(agvTask.getType());
        newAgvTask.setJobType(agvTask.getJobType());
        newAgvTask.setJobPriority(1);
        newAgvTask.setLineSlotCode(agvTask.getLineSlotCode());
        agvTaskRepository.save(newAgvTask);

        //重新发送任务
        List<Task> taskList = taskService.getAgvTaskList(agvTask.getId());
        for (Task task : taskList) {
            task.setAgvTask(newAgvTask);
            taskRepository.save(task);
        }

        // 根据任务类型发送不同的实现
        switch (agvTask.getJobType()) {
            case "FORKLIFT_MOVE":
                sendAgvTaskCCImpl(newAgvTask);
                break;
            case "RACK_MOVE":
                sendAgvTaskHJImpl(newAgvTask);
                break;
            case "ROLLER_MOVE":
                sendAgvTaskGTImpl(newAgvTask);
                break;
            default:
                throw new BadRequestException("任务类型不支持: " + agvTask.getJobType());
        }


    }


    /**
     * 满车入库
     *
     * @param taskList
     * @param stock
     */
    private void handleXJDJ(AgvTask agvTask, List<Task> taskList, Stock stock) {
        if (BizStatus.ASN.equals(agvTask.getType())) {
            //容器回存储区，新增库存、更新点位状态
            for (Task task : taskList) {
                AsnDetail ad = task.getAsnDetail();
                ad.setReceivedQty(ad.getOrderQty());
                ad.setStatus(BizStatus.RECEIVED);
                ad.setStock(stock);
                asnDetailService.update(ad);

                task.setTaskStatus(BizStatus.FINISH);
                task.setMoveQty(task.getPlanQty());
                task.setSrcStock(stock);
                task.setDstStock(stock);
                taskService.update(task);

                updateInventory(stock, task, ad);
            }
        } else if (BizStatus.FB_RETURN.equals(agvTask.getType())) {
            Point endPoint = pointService.findByCode(agvTask.getEndSlotCode(), null, null, null, null, null);
            List<Inventory> inventoryList = inventoryService.queryInventory(stock);
            for (Inventory inventory : inventoryList) {
                inventory.setPoint(endPoint);
                inventory.setPointCode(endPoint.getCode());
                inventoryRepository.save(inventory);
            }
            stock.setPoint(endPoint);
            stockRepository.save(stock);
        }

    }

    /**
     * 备料
     *
     * @param taskList
     */
    private void handleFbq(List<Task> taskList, Stock stock, Point endPoint) {
        //将托盘的物料移动到备料库位
        stock.setPoint(endPoint);
        stockRepository.save(stock);
        List<Inventory> inventoryList = inventoryService.queryInventory(stock);
        for (Inventory inventory : inventoryList) {
            inventory.setPoint(endPoint);
            inventory.setPointCode(endPoint.getCode());
            inventoryRepository.save(inventory);
        }
        /* 更新Task任务状态*/
        for (Task task : taskList) {
            task.setTaskStatus(BizStatus.ARRIVED);
            taskRepository.save(task);
        }
    }

    /**
     * 满车出库
     *
     * @param stock
     */
    private void handleJl(Stock stock, Point endPoint, AgvTask agvTask) {
        List<Inventory> inventoryList = inventoryService.queryInventory(stock);
        Long[] ids = inventoryList.stream()
                .filter(i -> {
                    String areaCode = i.getPoint().getArea().getCode();
                    return AreaNameDic.XJFBCQ.equals(areaCode) || AreaNameDic.DJFBCQ.equals(areaCode);
                })
                .map(Inventory::getId)
                .toArray(Long[]::new);
        if (ids.length > 0) {
            inventoryService.deleteAll(ids);
        }
        stock.setPoint(endPoint);
        stockRepository.save(stock);
        endPoint.setStatus(BaseStatus.USED);
        pointService.update(endPoint);

        Pick pick = pickRepository.findByPickCode(agvTask.getLineSlotCode());
        if (pick != null) {
            pick.setStatus(BizStatus.CLOSE);
            pickRepository.save(pick);
        }

        //回传MES

    }


    /**
     * 更新库存
     *
     * @param stock
     * @param task
     * @param ad
     */
    private void updateInventory(Stock stock, Task task, AsnDetail ad) {

        Inventory inventory = inventoryService.getInventory(task.getItemKey(), task.getDstPoint(), stock, task.getDept(), BizStatus.RECEIVING_UP);
        inventory.setQuantity(inventory.getQuantity() + task.getPlanQty());
        inventoryService.update(inventory);

        stock.setStatus(BaseStatus.USED);
        stock.setPoint(inventory.getPoint());
        stockRepository.save(stock);

        Point point = inventory.getPoint();
        point.setStatus(BaseStatus.USED);
        pointService.update(point);

        inventoryLogService.storeInventoryLog(BizStatus.RECEIVING_UP, BizStatus.ADD, null, task.getItemKey(), task.getSrcPoint(), task.getDstPoint(), task.getSrcStock(), task.getSrcStock(), 0d, task.getPlanQty(), BizStatus.ASN, ad.getId(), inventory.getId(), ad.getRemark());
    }

    /**
     * 任务取消完成
     *
     * @param agvTask
     * @param containerCode
     */
    private void handleCanceledTask(AgvTask agvTask, String containerCode) {
        //任务取消完成
        Point endPoint = pointService.findByCode(agvTask.getEndSlotCode(), null, null, null, null, null);
        String endAreaName = endPoint.getArea().getCode();
        Stock stock = stockRepository.findByCode(containerCode, null);
        if (stock == null) {
            throw new BadRequestException(containerCode + "容器不存在! 请维护");
        }
        switch (endAreaName) {
            case AreaNameDic.XJQ:
            case AreaNameDic.DJQ:
                handleFBFCCancel(agvTask, endPoint, stock);//入库取消
                break;
        }
        agvTask.setStatus(BizStatus.CANCEL);
        agvTask.setEndTime(new Timestamp(new Date().getTime()));
        agvTaskRepository.save(agvTask);

    }

    private void handleFBFCCancel(AgvTask agvTask, Point endPoint, Stock stock) {
        //回存储区取消任务，不生成库存 入库任务取消即可
        List<Task> taskList = taskService.getAgvTaskList(agvTask.getId());
        for (Task task : taskList) {
            AsnDetail ad = task.getAsnDetail();
            ad.setStatus(BizStatus.CANCEL);
            asnDetailService.update(ad);

            task.setTaskStatus(BizStatus.CANCEL);
            taskService.update(task);
        }
        //起点点位释放
        Point srcPoint = pointService.findByCode(agvTask.getStartSlotCode(), null, null, null, null, null);
        releasePoint(srcPoint);
        stock.setPoint(null);
        stock.setStatus(BaseStatus.FREE);
        stockRepository.save(stock);
        //线边点位释放
        releasePoint(endPoint);
    }

    /**
     * 释放点位
     *
     * @param point
     */
    private void releasePoint(Point point) {
        if (point != null) {
            point.setStatus(BaseStatus.FREE);
            pointService.update(point);
        }
    }

    private void handleCPXXAndCPRK(Point endPoint, Stock stock) {
        stock.setPoint(endPoint);
        stockRepository.save(stock);
    }
}
