package com.shkj.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shkj.common.constant.RedisConstant;
import com.shkj.common.core.domain.AjaxResult;
import com.shkj.common.core.domain.Result;
import com.shkj.common.enums.HttpStatus;
import com.shkj.common.utils.DateUtils;
import com.shkj.plc.sdk.device.PLCReadAndWrite;
import com.shkj.plc.sdk.device.PlcOperate;
import com.shkj.system.service.ISysParameterService;
import com.shkj.wms.bo.*;
import com.shkj.wms.constants.ParameterConstants;
import com.shkj.wms.domain.*;
import com.shkj.wms.enums.TaskStatusEnum;
import com.shkj.wms.enums.TaskTypeEnum;
import com.shkj.wms.mapper.BaseLocationMapper;
import com.shkj.wms.mapper.BaseLocationPlcMapper;
import com.shkj.wms.mapper.BasePointDeviceMapper;
import com.shkj.wms.mapper.BusinDataTaskMapper;
import com.shkj.wms.plc.PlcInit;
import com.shkj.wms.service.*;
import com.shkj.wms.third.rcs.RCSUtil;
import com.shkj.wms.third.rcs.dto.RcsCreateTaskDto;
import com.shkj.wms.third.rcs.dto.RcsIdList;
import com.shkj.wms.third.rcs.enums.RCSTaskTypeEnum;
import com.shkj.wms.utils.JsonUtil;
import com.shkj.wms.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 区域资料Service业务层处理
 *
 * @author lch
 * @date 2022-05-13
 */
@Slf4j
@Service
public class StackServiceImpl implements IStackService {

    @Resource
    RedisTemplate redisTemplate;
    @Resource
    BaseLocationPlcMapper baseLocationPlcMapper;
    @Resource
    IWcsPlcPropertyService iWcsPlcPropertyService;
    @Resource
    IWcsPlcConnectService iWcsPlcConnectService;
    @Resource
    IBusinDataTaskService iBusinDataTaskService;
    @Resource
    ISysParameterService sysParameterService;
    @Resource
    RCSUtil rcsUtil;
    @Resource
    IBasePunchRecordService iBasePunchRecordService;
    @Resource
    IBusinDataTaskGoodsService iBusinDataTaskGoodsService;
    @Resource
    IBaseLocationService iBaseLocationService;
    @Resource
    ISysParameterService isysParameterService;
    @Resource
    IPutInOutStorageService iPutInOutStorageService;
    @Resource
    IBusinEnptyContainerService iBusinEnptyContainerService;
    @Resource
    BaseLocationMapper baseLocationMapper;
    @Resource
    IBasePointService iBasePointService;
    @Resource
    BasePointDeviceMapper basePointDeviceMapper;

    @Resource
    BusinDataTaskMapper businDataTaskMapper;

    @Resource
    PlcInit plcInit;
    @Override
    public AjaxResult move(PackerMoveVo packerMoveVo) {
        log.info("PackerMoveVo++++++++++++++>>" + packerMoveVo.toString());

        //获取堆垛机
        BasePointDeviceQueryBo pointQueryBo = new BasePointDeviceQueryBo();
        pointQueryBo.setDevType("1");
        pointQueryBo.setTunnel(packerMoveVo.getStackNum());
        BaseDevicePlcVo baseDevicePlcVo = baseLocationPlcMapper.selectBaseDevicePlc(pointQueryBo);
        Long stkPlcId = baseDevicePlcVo.getPlcId();
        String plcIp = baseDevicePlcVo.getPlcIp();

        PlcOperate stkOperate = plcInit.getPlcOperateByIp(plcIp);

        List<WcsPlcProperty> propertyList = iWcsPlcPropertyService.getWcsPlcPropertyByPlcId(stkPlcId);
        String plcTaskId ="";
        String plcToRow ="";
        String plcToColumn ="";
        String plcToLayer ="";
        String plcFromRow ="";
        String plcFromColumn ="";
        String plcFromLayer ="";
        String Overonaddress="";
        String plcml="";
        WcsPlcConnect plcConnect = iWcsPlcConnectService.getById(stkPlcId);
        //堆垛机是否空闲
        String readNullPoint="";
        for (WcsPlcProperty stkProperty : propertyList) {
            //获取要堆垛机要写入的点位
            if (stkProperty.getPointType().equals("101")) {
                plcTaskId = stkProperty.getAddress();
            }else if (stkProperty.getPointType().equals("108")){
                plcToRow = stkProperty.getAddress();
            }else if (stkProperty.getPointType().equals("109")){
                plcToColumn =stkProperty.getAddress();
            }else if (stkProperty.getPointType().equals("110")){
                plcToLayer=stkProperty.getAddress();
            }else if (stkProperty.getPointType().equals("104")){
                plcFromRow=stkProperty.getAddress();
            }else if(stkProperty.getPointType().equals("105")){
                plcFromColumn=stkProperty.getAddress();
            }else if(stkProperty.getPointType().equals("106")){
                plcFromLayer=stkProperty.getAddress();
            }else if(stkProperty.getPointType().equals("102")){
                plcml=stkProperty.getAddress();
            }else if (stkProperty.getPointType().equals("12")){
                readNullPoint=stkProperty.getAddress();
            }else if(stkProperty.getPointType().equals("4")){
                Overonaddress= stkProperty.getAddress();
            }
        }

        //创建新的货位调整任务
        String taskCode = "T_" + DateUtils.dateTimeNow();
        String transId = com.shkj.common.utils.uuid.UUID.randomUUID().toString();
        BusinDataTask businDataTask =new BusinDataTask();
        businDataTask.setTaskCode(taskCode);
        businDataTask.setPlcId(stkPlcId);
        businDataTask.setTaskStatus(TaskStatusEnum.wait_callback.getValue());
        businDataTask.setTaskType(TaskTypeEnum.seat_adjustment.getValue());
        businDataTask.setCreateTime(DateUtils.getNowDate());
        businDataTask.setBatch(DateUtils.getDate());
        businDataTask.setTransId(transId);
        businDataTask.setFromRow(packerMoveVo.getFromRow().toString());
        businDataTask.setFromColumn(packerMoveVo.getFromColumn().toString());
        businDataTask.setFromLayer(packerMoveVo.getFromLayer().toString());
        businDataTask.setToRow(packerMoveVo.getToRow().toString());
        businDataTask.setToColumn(packerMoveVo.getToColumn().toString());
        businDataTask.setToLayer(packerMoveVo.getToLayer().toString());

        iBusinDataTaskService.insertBusinTask(businDataTask);

        //根据连接的plcId获取属性
        PLCReadAndWrite plcReadAndWriteD = new PLCReadAndWrite();
        Map<String, Object> pointDMap = plcReadAndWriteD.readPlcData(stkOperate, plcConnect.getPointTables());
        if (pointDMap.containsKey(readNullPoint)&&Boolean.valueOf(pointDMap.get(readNullPoint).toString())&&pointDMap.get(Overonaddress).equals("0")) {
            //给堆垛机写命令
            Map<String, Object> allMap = new HashMap<>(1);
            Map<String, Object> plcTaskIdMap = new HashMap<>(1);
            plcTaskIdMap.put("INTEGER", businDataTask.getId());
            allMap.put(plcTaskId, plcTaskIdMap);
            Map<String, Object> plcFromRowMap = new HashMap<>(1);
            plcFromRowMap.put("SHORT", packerMoveVo.getFromRow());
            allMap.put(plcFromRow, plcFromRowMap);
            Map<String, Object> plcFromColumnMap = new HashMap<>(1);
            plcFromColumnMap.put("SHORT", packerMoveVo.getFromColumn());
            allMap.put(plcFromColumn, plcFromColumnMap);
            Map<String, Object> plcFromLayerMap = new HashMap<>(1);
            plcFromLayerMap.put("SHORT", packerMoveVo.getFromLayer());
            allMap.put(plcFromLayer, plcFromLayerMap);
            Map<String, Object> plcToRowMap = new HashMap<>(1);
            plcToRowMap.put("SHORT", packerMoveVo.getToRow());
            allMap.put(plcToRow, plcToRowMap);
            Map<String, Object> plcToColumnMap = new HashMap<>(1);
            plcToColumnMap.put("SHORT", packerMoveVo.getToColumn());
            allMap.put(plcToColumn, plcToColumnMap);
            Map<String, Object> plcToLayerMap = new HashMap<>(1);
            plcToLayerMap.put("SHORT", packerMoveVo.getToLayer());
            allMap.put(plcToLayer, plcToLayerMap);
            Map<String, Object> plcMLMap = new HashMap<>(1);
            plcMLMap.put("Short", 4);
            allMap.put(plcml, plcMLMap);

            PLCReadAndWrite plcReadAndWrite = new PLCReadAndWrite();
            if (plcReadAndWrite.execWrite(stkOperate, JsonUtil.toJSONString(allMap))) {
                StringBuilder a = new StringBuilder();
                StringBuilder b = new StringBuilder();
                a.append(packerMoveVo.getFromRow()+"-");
                a.append(packerMoveVo.getFromColumn()+"-");
                a.append(packerMoveVo.getFromLayer());

                b.append(packerMoveVo.getToRow()+"-");
                b.append(packerMoveVo.getToColumn()+"-");
                b.append(packerMoveVo.getToLayer());
                //请求成功，记录已下发
                log.info("库位调整下发成功！开始货位为："+a+" 结束货位为："+b);
            }
        }
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult punchingOperation(int planStatus) {
        try {

            String toPointNoOne = null;
            String toPointNoTwo = null;

            // 获取冲孔机取货点位并验证是否到达
            BasePointDeviceQueryBo pointQueryBo = new BasePointDeviceQueryBo();
            pointQueryBo = new BasePointDeviceQueryBo();
            pointQueryBo.setGroupNo(sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.punching_group));
//            pointQueryBo.setDevCode(iBasePunchService.selectBasePunchRecord(new BasePunch()).getId());
            // TODO 规划冲孔机 获取ID
            pointQueryBo.setDevCode(2L);

            List<BasePointDeviceVo> basePointDeviceVos = baseLocationPlcMapper.selectBasePointByGroupno(pointQueryBo);
            if (basePointDeviceVos.size() > 0) {
                for (BasePointDeviceVo basePointDeviceVo: basePointDeviceVos) {
                    if(basePointDeviceVo.getPointNo().contains("KW12")){
                        toPointNoTwo = basePointDeviceVo.getPointNo();
                    }else{
                        toPointNoOne = basePointDeviceVo.getPointNo();
                    }
                }
            }

            RcsCreateTaskDto dto = new RcsCreateTaskDto();
            List<RcsIdList> idList = new ArrayList<>();

            RcsIdList startId = new RcsIdList();
            RcsIdList endId = new RcsIdList();

            switch (planStatus){
                case 1:
                    // 给固定的agv下发任务去冲孔放货位置
                    //获取当前在冲孔取货口的任务相关信息
                    if(ObjectUtils.isEmpty(redisTemplate.opsForValue().get(RedisConstant.startPunchingTaskId))){
                        break;
                    }
                    // 将redis 中的值转成字符串
                    String startPunchingTaskId = redisTemplate.opsForValue().get(RedisConstant.startPunchingTaskId).toString();
                    String[] idArr = startPunchingTaskId.split("_");

                    //呼叫agv
                    int  agvTaskType = Integer.valueOf(RCSTaskTypeEnum.TO_B_PUT.getValue());

                    dto.setMapId(1);
                    dto.setTaskType(agvTaskType);
                    dto.setRobotId(idArr[1]);

                    startId.setId(toPointNoOne);
                    idList.add(startId);
                    endId.setId(toPointNoTwo);
                    idList.add(endId);
                    dto.setTargets(idList);
                    dto.setTaskId(startPunchingTaskId);

                    log.info("冲孔取货完成！开始下发AGV去放货点位的任务；AGV任务ID为："+startPunchingTaskId);
                    Result<Boolean> booleanResult =  rcsUtil.rcsCreateTask(dto);
                    if (booleanResult.getCode()== HttpStatus.SUCCESS.getCode()){
                        //修改冲孔中
                        BasePunchRecord basePunchRecord = iBasePunchRecordService.getOne(new LambdaQueryWrapper<BasePunchRecord>()
                                .eq(BasePunchRecord::getTaskCode,Long.valueOf(idArr[0]))
                                .last("limit 1"));
                        basePunchRecord.setIsState("1");
                        iBasePunchRecordService.updateById(basePunchRecord);
                        log.info("冲孔取货完成！已下发AGV去放货点位的任务；AGV任务ID为："+startPunchingTaskId);
                        redisTemplate.opsForValue().set(idArr[1],toPointNoTwo);
                    }
                    redisTemplate.delete(RedisConstant.startPunchingTaskId);
                    return AjaxResult.success("冲孔取货成功");
                case 2:
                    //获取当前在冲孔放货口的任务相关信息
                    if(ObjectUtils.isEmpty(redisTemplate.opsForValue().get(RedisConstant.endPunchingTaskId))){
                        break;
                    }
                    // 将redis 中的值转成字符串
                    String endPunchingTaskId = redisTemplate.opsForValue().get(RedisConstant.endPunchingTaskId).toString();
                    String[] endIdArr = endPunchingTaskId.split("_");



                    BasePointDeviceVo basePointDeviceVo = new BasePointDeviceVo();
                    //立库输送线接驳点-入
                    String toLocation = "";
                    BusinTaskExeBo exeBo = new BusinTaskExeBo();
                    Long plcId = null;
                    Long stkPlcId=null;


                    List<BusinDataTaskGoodsVo> businDataTaskGoodsVos = iBusinDataTaskGoodsService.selectBusinTaskGoodsByTaskCode(Long.valueOf(endIdArr[0]));
                    if(ObjectUtils.isEmpty(businDataTaskGoodsVos)){
                        break;
                    }
                    BusinDataTaskGoodsVo goodsVo = businDataTaskGoodsVos.get(0);
                    String vehicheModel = goodsVo.getVehicheModel();
                    String color =goodsVo.getColor();
                    String goodsNo = goodsVo.getGoodsNo();
                    String startPoint = toPointNoTwo;

                    //根据派生分配库位
                    // TODO: 2024/6/28 zjx
                   // Result<BaseLocationVo> locationVoResult = iBaseLocationService.assignEmptyLocation(vehicheModel,color, DateUtils.getDate(),businDataTaskGoodsVos);
                    Result<BaseLocationVo> locationVoResult = iBaseLocationService.assignEmptyLocationByStock( goodsNo, vehicheModel,DateUtils.getDate(),businDataTaskGoodsVos);
                    String agvno=null;

                    BaseLocationVo locationVo = locationVoResult.getData();
                    String tunnel = locationVo.getTunnel();
                    Long locationId = locationVo.getId();
                    for (BusinDataTaskGoodsVo businDataTaskGoodsVo : businDataTaskGoodsVos) {
                        businDataTaskGoodsVo.setLocationId(locationId);
                    }

                    int agvTaskType1 = RCSTaskTypeEnum.TO_B_AND_PUT.getValue();

                    //获取下料点点位
                    String taskCode = "T_" + DateUtils.dateTimeNow();
                    String transId = com.shkj.common.utils.uuid.UUID.randomUUID().toString();
                    BusinDataTask businDataTask =new BusinDataTask();
                    businDataTask.setTaskCode(taskCode);
                    businDataTask.setTaskStatus(TaskStatusEnum.wait_put.getValue());
                    businDataTask.setCreateTime(DateUtils.getNowDate());
                    businDataTask.setBatch(DateUtils.getDate());
                    businDataTask.setTransId(transId);
                    businDataTask.setAgvNo(endIdArr[1]);
                    businDataTask.setContainerId(Long.valueOf(endIdArr[2]));
                    businDataTask.setTaskType("18");
                    businDataTask.setIsDown(agvTaskType1+"");

                    //回填任务的入行高列
                    businDataTask.setToColumn(locationVo.getLocationColumn());
                    businDataTask.setToLayer(locationVo.getLayer());
                    businDataTask.setToRow(locationVo.getLocationRow());
                    businDataTask.setTunnel(tunnel);
                    //获取货位对应的巷道及巷道对应的设备信息
                    pointQueryBo = new BasePointDeviceQueryBo();
                    pointQueryBo.setTunnel(tunnel);
                    pointQueryBo.setDirection("0");
                    basePointDeviceVo = basePointDeviceMapper.selectBasePointByGroupno(pointQueryBo);

                    if (basePointDeviceVo != null) {
                        toLocation = basePointDeviceVo.getPointNo();
                        //输送线PLCID
                        plcId = Long.valueOf(isysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.LK_plc_id));
                    }

                    businDataTask.setTaskPath(toLocation);
                    iBusinDataTaskService.insertBusinDataTask(businDataTask);

                    Long taskId =businDataTask.getId();

                    //获取巷道对应的堆垛机信息
                    pointQueryBo.setDevType("1");
                    BaseDevicePlcVo baseDevicePlcVo = baseLocationPlcMapper.selectBaseDevicePlc(pointQueryBo);
                    stkPlcId = baseDevicePlcVo.getPlcId();

                    exeBo.setTaskCode(taskId);
                    exeBo.setBusinDataTaskGoodsVo(businDataTaskGoodsVos);
                    exeBo.setContainerId(Long.valueOf(endIdArr[2]));
                    exeBo.setBaseLocationVo(locationVo);
                    exeBo.setTransNo("1");
                    exeBo.setTransQual("1");

                    List<String> points = new ArrayList<>();
                    points.add(startPoint);


                    points.add(toLocation);
                    Map<String,String> snPointMap = new HashMap<>(3);
                    snPointMap.put("1",startPoint);
                    snPointMap.put("2",toLocation);

                    BusinDataTaskVo businDataTaskVo = iBusinDataTaskService.selectBusinDataTask(new BusinTaskQueryBo().setId(taskId)).get(0);

                    businDataTaskVo.setPoints(JsonUtil.toJSONString(snPointMap));
                    businDataTaskVo.setIsDown(String.valueOf(agvTaskType1));

                    log.info("冲孔放货完成！开始下发AGV去入库的任务；AGV任务ID为："+taskId);

                    dto = new RcsCreateTaskDto();
                    idList = new ArrayList<>();

                    startId = new RcsIdList();
                    endId = new RcsIdList();

                    dto.setMapId(1);
                    dto.setTaskType(agvTaskType1);
                    dto.setRobotId(endIdArr[1]);
                    // TODO 添加POINTS

                    startId.setId(startPoint);
                    idList.add(startId);
                    endId.setId(toLocation);
                    idList.add(endId);
                    dto.setTargets(idList);
                    dto.setTaskId(taskId+"");

                    //呼叫AGV
                    Result<Boolean> booleanResult1 =  rcsUtil.rcsCreateTask(dto);
                    //呼叫AGV成功
                    if (booleanResult1.getCode()== HttpStatus.SUCCESS.getCode()) {
                        businDataTaskVo.setTaskPath(toLocation);
                        businDataTaskVo.setTaskStatus(TaskStatusEnum.wait_callback.getValue());
                        //生成入库单
                        Result<String> stringResult = iPutInOutStorageService.exeTaskPutinStorage(exeBo);
                        //生成入库单成功
                        if (stringResult.getCode() == HttpStatus.SUCCESS.getCode()) {
                            businDataTaskVo.setTransId(stringResult.getData());
                        } else {
                            businDataTaskVo.setTaskStatus(TaskStatusEnum.err.getValue());
                            businDataTaskVo.setExceptionMsg("生成入库单失败");
                        }
                        //修改冲孔完成
                        BasePunchRecord basePunchRecord = iBasePunchRecordService.getOne(new LambdaQueryWrapper<BasePunchRecord>()
                                .eq(BasePunchRecord::getTaskCode,Long.valueOf(endIdArr[0]))
                                .last("limit 1"));
                        basePunchRecord.setIsState("2");
                        iBasePunchRecordService.updateById(basePunchRecord);
                        redisTemplate.delete(endIdArr[1]);
                        log.info("冲孔放货完成！已下发AGV去入库的任务；AGV任务ID为："+taskId);
                    }else {
                        if (redisTemplate.opsForValue().get(RedisConstant.redisAgvTaskerror+taskId)==null){
                            redisTemplate.opsForValue().set(RedisConstant.redisAgvTaskerror+taskId,0);
                        }
                        Long a=Long.valueOf(String.valueOf(redisTemplate.opsForValue().get(RedisConstant.redisAgvTaskerror+taskId)));
                        businDataTaskVo.setTaskStatus(TaskStatusEnum.err.getValue());
                        businDataTaskVo.setExceptionMsg(booleanResult1.getMsg());
                        if (a<3L){
                            long l = a + 1;
                            redisTemplate.opsForValue().set(RedisConstant.redisAgvTaskerror+taskId,l);
                        }else {
                            businDataTaskVo.setTaskStatus("-2");
                        }
                    }
                    //立库输送线PLCID
                    businDataTaskVo.setDpsNoOne(plcId);
                    //巷道堆垛机PLCID
                    businDataTaskVo.setDpsNoTwo(stkPlcId);
                    iBusinDataTaskService.updateById(BeanUtil.toBean(businDataTaskVo, BusinDataTask.class));

                    redisTemplate.delete(RedisConstant.endPunchingTaskId);

                    return AjaxResult.success("冲孔放货成功");
                case 3:

                    //获取当前在冲孔放货口的任务相关信息
                    if(ObjectUtils.isEmpty(redisTemplate.opsForValue().get(RedisConstant.endPunchingTaskId))){
                        break;
                    }
                    // 将redis 中的值转成字符串
                    String endPunchingTaskId0 = redisTemplate.opsForValue().get(RedisConstant.endPunchingTaskId).toString();
                    String[] endIdArr0 = endPunchingTaskId0.split("_");

                    Long stkPlcId1 = 0L;
                    Boolean NUMBER=true;
                    //维修异常 呼叫AGV
                    //获取起始点位
                    String startPoint1 = toPointNoTwo;
                    //查询维修地点是否有空闲
//                    String tepairGroup = sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.tepair_group);
//
//                    pointQueryBo = new BasePointDeviceQueryBo();
//                    pointQueryBo.setGroupNo(tepairGroup);
//                    BasePointDeviceVo basePointDeviceVo1 = new BasePointDeviceVo();
//                    List<BasePointDeviceVo> basePointDeviceVos1 = baseLocationPlcMapper.selectBasePointByGroupno(pointQueryBo);
                    List<String> points1 = new ArrayList<>();
                    points1.add(startPoint1);
                    points1.add("KW29");
                    Map<String, String> snPointMap1 = new HashMap<>(3);
                    snPointMap1.put("1",startPoint1);
                    snPointMap1.put("2","KW29");
//                    BaseLocationVo locationVo1 = null;
//                    BusinTaskExeBo exeBo1 = new BusinTaskExeBo();

                    int agvTaskType2 = RCSTaskTypeEnum.TO_B_PUT.getValue();

                    //获取下料点点位
                    String taskCode1 = "T_" + DateUtils.dateTimeNow();
                    String transId1 = com.shkj.common.utils.uuid.UUID.randomUUID().toString();
                    BusinDataTask businDataTask1 =new BusinDataTask();
                    businDataTask1.setTaskCode(taskCode1);
                    businDataTask1.setTaskStatus(TaskStatusEnum.wait_callback.getValue());
                    businDataTask1.setCreateTime(DateUtils.getNowDate());
                    businDataTask1.setBatch(DateUtils.getDate());
                    businDataTask1.setTransId(transId1);
                    businDataTask1.setAgvNo(endIdArr0[1]);
                    businDataTask1.setContainerId(Long.valueOf(endIdArr0[2]));
                    businDataTask1.setTaskType(TaskTypeEnum.punching_delivery.getValue());
                    businDataTask1.setIsDown(agvTaskType2+"");

                    iBusinDataTaskService.insertBusinDataTask(businDataTask1);

                    Long taskId1 =businDataTask1.getId();

                    //BusinDataTaskVo businDataTaskVo1 = iBusinDataTaskService.selectBusinDataTask(new BusinTaskQueryBo().setId(taskId1)).get(0);
                    BusinDataTask businDataTaskVo1 = businDataTaskMapper.selectById(taskId1);

                    //无空闲区 分配异常区库位
//                    if (basePointDeviceVos1.size() ==0) {
//                        NUMBER = false;
//                        //异常区ID
//                        Long abnormalArea =Long.valueOf(sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.abnormal_area));
//                        List<BaseLocationVo> baseLocationVos = baseLocationMapper.getLocationByAreaId(abnormalArea);
//                        if (baseLocationVos.size() > 0) {
//                            locationVo = baseLocationVos.get(0);
//                        }
//                        businDataTaskVo1.setToColumn(locationVo1.getLocationColumn());
//                        businDataTaskVo1.setToLayer(locationVo1.getLayer());
//                        businDataTaskVo1.setToRow(locationVo1.getLocationRow());
//                        //获取货位及巷道；
//                        String tunnel1 = locationVo1.getTunnel();
//                        businDataTaskVo1.setTunnel(tunnel1);
//                        pointQueryBo=new BasePointDeviceQueryBo();
//                        pointQueryBo.setTunnel(tunnel1);
//                        pointQueryBo.setDirection("0");
//                        basePointDeviceVos1 = baseLocationPlcMapper.selectBasePointByGroupno(pointQueryBo);
//                        if (basePointDeviceVos1.size() > 0) {
//                            basePointDeviceVo1 = basePointDeviceVos1.get(0);
//                            basePointDeviceVo1.setPlcId(Long.valueOf(isysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.LK_plc_id)));
//                        }
//                        //获取巷道对应的堆垛机信息
//                        pointQueryBo.setDevType("1");
//                        baseDevicePlcVo = baseLocationPlcMapper.selectBaseDevicePlc(pointQueryBo);
//                        stkPlcId1 = baseDevicePlcVo.getPlcId();
//                        businDataTaskGoodsVos = iBusinDataTaskGoodsService.selectBusinTaskGoodsByTaskCode(businDataTaskVo1.getId());
//                        exeBo1.setTaskCode(taskId1);
//                        exeBo1.setBusinDataTaskGoodsVo(businDataTaskGoodsVos);
//                        exeBo1.setContainerId(Long.valueOf(endIdArr0[2]));
//                        exeBo1.setBaseLocationVo(locationVo1);
//                        exeBo1.setTransNo("1");
//                        exeBo1.setTransQual("1");
//                    }else {
//                        basePointDeviceVo1 = basePointDeviceVos1.get(0);
//                    }
//
//                    plcId =basePointDeviceVo1.getPlcId();
//                    String toPointNo = basePointDeviceVo1.getPointNo();

//                    if(toPointNo.contains("P_Lane")){
//                        // TODO 人车分流相关  需要修改对应的任务类型为 33   需要添加在RCS地图上添加对应的点位 abnormal_wait_point
//                        String abnormalWaitPintGroup = sysParameterService.selectConfigByKey(ParameterConstants.ParameterSystem.abnormalWaitPint);
//                        BasePointDeviceQueryBo abnormalWaitPintBo = new BasePointDeviceQueryBo();
//                        abnormalWaitPintBo.setGroupNo(abnormalWaitPintGroup);
//                        BasePointDeviceVo abnormalWaitPintDeviceVo = basePointDeviceMapper.selectBasePointByGroupno(abnormalWaitPintBo);
//                        points1.add(abnormalWaitPintDeviceVo.getPointNo());
//                        points1.add(abnormalWaitPintDeviceVo.getPointNo());
//                        snPointMap1.put("2",abnormalWaitPintDeviceVo.getPointNo());
//                        snPointMap1.put("3",abnormalWaitPintDeviceVo.getPointNo());
//                        snPointMap1.put("4",toPointNo);
//
//                        //TODO 需要RCS 对应 的任务类型。 负载 等待 放行 放下
//                        agvTaskType2 = RCSTaskTypeEnum.A__wait_B_GOODS_MOVE.getValue();
//                    }else{
//                        snPointMap1.put("2",toPointNo);
//                    }
//
//                    points1.add(toPointNo);

                    businDataTaskVo1.setPoints(JsonUtil.toJSONString(snPointMap1));
                    businDataTaskVo1.setIsDown(String.valueOf(agvTaskType2));

                    log.info("冲孔放货完成！开始下发AGV去小组装的任务；AGV任务ID为："+taskId1);

                    //呼叫AGV
                    AGVMoveBo moveBo = new AGVMoveBo();
                    moveBo.setTaskId(taskId1);
                    moveBo.setTaskType(agvTaskType2);
                    moveBo.setPoints(points1);
                    moveBo.setRobotId(endIdArr0[1]);
                    Result<Boolean> booleanResult2 = rcsUtil.moveByAGV(moveBo);

                    //呼叫AGV成功
                    if (booleanResult2.getCode() == HttpStatus.SUCCESS.getCode()) {
                        businDataTaskVo1.setTaskStatus(TaskStatusEnum.wait_callback.getValue());
                        businDataTaskVo1.setTaskPath("KW29");
                        //把占用的点位改为已占用
//                        if (NUMBER) {
//                            BasePoint basePoint = iBasePointService.getById(basePointDeviceVo1.getPointId());
//                            basePoint.setIsOccupy("1");
//                            iBasePointService.updateById(basePoint);
//                        }
//                        //更改货位状态为4已分配
//                        if (ObjectUtils.isNotEmpty(locationVo1)){
//                            BaseLocation baseLocation = iBaseLocationService.getById(locationVo1.getId());
//                            baseLocation.setLocationStatus("4");
//                            iBaseLocationService.updateById(baseLocation);
//                            //生成入库单成功
//                        }
//                        if(!NUMBER) {
//                            Result<String> stringResult = iPutInOutStorageService.exeTaskPutinStorage(exeBo1);
//
//                            if (stringResult.getCode() == HttpStatus.SUCCESS.getCode()) {
//                                businDataTaskVo1.setTransId(stringResult.getData());
//                            } else {
//                                businDataTaskVo1.setTaskStatus(TaskStatusEnum.err.getValue());
//                                businDataTaskVo1.setExceptionMsg("生成入库单失败");
//                            }
//                        }

                        //修改冲孔完成
                        BasePunchRecord basePunchRecord = iBasePunchRecordService.getOne(new LambdaQueryWrapper<BasePunchRecord>()
                                .eq(BasePunchRecord::getTaskCode,Long.valueOf(endIdArr0[0]))
                                .last("limit 1"));
                        basePunchRecord.setIsState("2");
                        iBasePunchRecordService.updateById(basePunchRecord);

                        redisTemplate.delete(RedisConstant.endPunchingTaskId);
                        redisTemplate.delete(endIdArr0[1]);
                        //log.info("冲孔放货完成！已下发AGV去异常区的任务；AGV任务ID为："+taskId1);

                    }
//                    else{
//                        if (redisTemplate.opsForValue().get(RedisConstant.redisAgvTaskerror+taskId1)==null){
//                            redisTemplate.opsForValue().set(RedisConstant.redisAgvTaskerror+taskId1,0);
//                        }
//                        Long a=Long.valueOf((String)redisTemplate.opsForValue().get(RedisConstant.redisAgvTaskerror+taskId1));
//                        businDataTaskVo1.setTaskStatus(TaskStatusEnum.err.getValue());
//                        businDataTaskVo1.setExceptionMsg(booleanResult2.getMsg());
//                        if (a<3L){
//                            long l = a + 1;
//                            redisTemplate.opsForValue().set(RedisConstant.redisAgvTaskerror+taskId1,l);
//                        }else {
//                            businDataTaskVo1.setTaskStatus("-2");
//                        }
//                    }

                    //businDataTaskVo1.setDpsNoOne(plcId);
                    businDataTaskVo1.setDpsNoTwo(stkPlcId1);

                    iBusinDataTaskService.saveOrUpdate(businDataTaskVo1);

                    return AjaxResult.success("冲孔去小组装放货成功");
                case 4:
                    //调用空治具流向接口
                    //获取当前在冲孔放货口的任务相关信息
                    if(ObjectUtils.isEmpty(redisTemplate.opsForValue().get(RedisConstant.endPunchingTaskId))){
                        break;
                    }
                    // 将redis 中的值转成字符串
                    String endPunchingTaskId1 = redisTemplate.opsForValue().get(RedisConstant.endPunchingTaskId).toString();
                    String[] endIdArr1 = endPunchingTaskId1.split("_");

                    iBusinEnptyContainerService.emptyContainerFlowDir(toPointNoTwo, Long.valueOf(endIdArr1[2]), endIdArr1[1],null);
                    //修改冲孔完成
                    BasePunchRecord basePunchRecord = iBasePunchRecordService.getOne(new LambdaQueryWrapper<BasePunchRecord>()
                            .eq(BasePunchRecord::getTaskCode,Long.valueOf(endIdArr1[0]))
                            .last("limit 1"));
                    basePunchRecord.setIsState("2");
                    iBasePunchRecordService.updateById(basePunchRecord);

                    redisTemplate.delete(RedisConstant.endPunchingTaskId);
                    redisTemplate.delete(endIdArr1[1]);
                    log.info("冲孔放货完成！已下发AGV空治具返回");
                    return AjaxResult.success("空治具返回成功");
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("操作失败");
        }
        return AjaxResult.error("操作失败");
    }
}
