package org.nl.acs.device_driver.basedriver.agv.ndcone;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.agv.server.NDCAgvService;
import org.nl.acs.auto.run.OneNDCSocketConnectionAutoRun;
import org.nl.acs.device.domain.Device;
import org.nl.acs.device.service.DeviceService;
import org.nl.acs.device_driver.DeviceDriver;
import org.nl.acs.device_driver.basedriver.agv.utils.AgvActionEnum;
import org.nl.acs.device_driver.basedriver.standard_ordinary_site.StandardOrdinarySiteDeviceDriver;
import org.nl.acs.device_driver.driver.AbstractDeviceDriver;
import org.nl.acs.device_driver.yinfei.hj1.Hj1DeviceDriver;
import org.nl.acs.device_driver.yinfei.hj2.Hj2DeviceDriver;
import org.nl.acs.device_driver.yinfei.ssx.SsxDeviceDriver;
import org.nl.acs.ext.wms.data.feedBackTaskStatus.FeedBackTaskStatusRequest;
import org.nl.acs.ext.wms.service.AcsToWmsService;
import org.nl.acs.ext.wms.service.impl.AcsToWmsServiceImpl;
import org.nl.acs.instruction.domain.Instruction;
import org.nl.acs.instruction.service.InstructionService;
import org.nl.acs.instruction.service.impl.InstructionServiceImpl;
import org.nl.acs.log.LokiLog;
import org.nl.acs.log.LokiLogType;
import org.nl.acs.log.service.DeviceExecuteLogService;
import org.nl.acs.opc.DeviceAppService;
import org.nl.acs.task.service.TaskService;
import org.nl.acs.task.service.dto.TaskDto;
import org.nl.acs.task.service.impl.TaskServiceImpl;
import org.nl.config.SpringContextHolder;
import org.nl.config.thread.ThreadPoolExecutorUtil;
import org.nl.system.service.lucene.LuceneExecuteLogService;
import org.nl.system.service.lucene.dto.LuceneLogDto;
import org.nl.system.service.param.ISysParamService;
import org.nl.system.service.param.impl.SysParamServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * NDC单工位AGV
 */
@Slf4j
@Data
@RequiredArgsConstructor
public class AgvNdcOneDeviceDriver extends AbstractDeviceDriver implements DeviceDriver {
    LuceneExecuteLogService lucene = SpringContextHolder.getBean("luceneExecuteLogServiceImpl");
    ISysParamService paramService = SpringContextHolder.getBean(SysParamServiceImpl.class);
    InstructionService instructionService = SpringContextHolder.getBean(InstructionServiceImpl.class);
    AcsToWmsService acsToWmsService = SpringContextHolder.getBean(AcsToWmsServiceImpl.class);
    TaskService taskService = SpringContextHolder.getBean(TaskServiceImpl.class);
    NDCAgvService ndcAgvService = SpringContextHolder.getBean(NDCAgvService.class);
    DeviceExecuteLogService logServer = SpringContextHolder.getBean(DeviceExecuteLogService.class);
    DeviceAppService deviceAppService = SpringContextHolder.getBean(DeviceAppService.class);
    DeviceService deviceService = SpringContextHolder.getBean(DeviceService.class);
    @Autowired
    LuceneExecuteLogService luceneExecuteLogService = SpringContextHolder.getBean("luceneExecuteLogServiceImpl");
    @Autowired
    TaskService taskserver = SpringContextHolder.getBean(TaskService.class);
    private final static ThreadPoolExecutor EXECUTOR = ThreadPoolExecutorUtil.getPoll();
    int agvaddr = 0;
    int agvaddr_copy = 0;
    int weight = 0;
    String device_code = "";
    int phase = 0;
    boolean flag = false;
    int x = 0; //x坐标
    int y = 0; //y坐标
    int angle = 0; //角度
    int electric_qty = 0; //电量
    int status = 0; //agv状态
    int agv_status = 0; //车辆动作状态
    int is_have = 0; //是否有货
    int error = 0; //车辆故障

    int last_x = 0;
    int last_y = 0;
    int last_angle = 0;
    int last_electric_qty = 0;
    int last_status = 0;
    int last_error = 0;
    int last_is_have = 0;
    int last_agv_status = 0;
    String transportOrder = "";
    boolean isCharge = false;
    String message = null;
    String agv_message = "";

    @LokiLog(type = LokiLogType.ACS_TO_LMS)
    public synchronized void processSocket(int[] arr) throws Exception {
        device_code = this.getDeviceCode();
        byte[] data = null;
        phase = arr[16] * 256 + arr[17];
        // agv任务号
        int index = arr[12] * 256 + arr[13];
        //任务单号和其他状态信息
        int ikey = arr[26] * 256 + arr[27];
        //站点号
        agvaddr = arr[18] * 256 + arr[19];
        //车号
        int carno = arr[20];
        Instruction link_inst = null;
        List<Instruction> insts = null;
        Instruction inst = null;
        boolean link_flag = false;
        Device agv_device = null;
        if (carno != 0) {
            agv_device = deviceAppService.findDeviceByCode(String.valueOf(carno));
        }
        if (ikey != 0) {
            inst = instructionService.findByCodeFromCache(String.valueOf(ikey));
            if (ObjectUtil.isEmpty(inst)) {
                inst = instructionService.findByCode(String.valueOf(ikey));
            }
        }
        if (!ObjectUtil.isEmpty(link_inst)) {
            link_flag = true;
        }
        if (error != 0) {
            //todo 反馈立库AGV故障信息
            sendAgvErrorStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
        }
        Device device = null;
        String old_device_code = null;
        String emptyNum = null;
        String device_code = null;

        if (phase == 0x67) {
            //todo 故障信息
            if (arr[18] * 256 + arr[19] == 0) {

            }
            FeedBackTaskStatusRequest request = new FeedBackTaskStatusRequest();
            request.setDevice_code(this.device_code);
            request.setState("故障");
            acsToWmsService.notify(request);
            data = ndcAgvService.sendAgvOneModeInst(phase, index, 0, 0, 0, 0, 0);
        }
        TaskDto task = new TaskDto();

        if (ObjectUtil.isNotEmpty(inst)) {
            task = taskService.findById(inst.getTask_id());
        }

        Hj1DeviceDriver hj1DeviceDriver;
        Hj2DeviceDriver hj2DeviceDriver;
        SsxDeviceDriver ssxDeviceDriver;
        //分配 车id
        //(不需要WCS反馈)
        if (phase == 0x02) {
            inst.setCarno(String.valueOf(carno));
            instructionService.update(inst);
            transportOrder = inst.getTask_code();
            logServer.deviceExecuteLog(this.device_code, "", "", "agvphase：" + "反馈:" + data);
            //车辆状态归零
            agv_status = 0;
            //到达取货点
            //(需要WCS反馈)
        } else if (phase == 0x03) {
            if (agvaddr == 0) {
                agvaddr = agvaddr_copy;
            }
            if (agvaddr < 1) {
                logServer.deviceExecuteLog(this.device_code, "", "", "agv地址参数有误,phase:" + phase);
                return;
            }
            device_code = deviceService.queryDeviceCodeByAddress(agvaddr);
            if (agvaddr != 0) {
                old_device_code = deviceService.queryDeviceCodeByAddress(agvaddr);
                if (StrUtil.contains(old_device_code, "-")) {
                    String[] point = old_device_code.split("-");
                    device_code = point[0];
                } else if (StrUtil.contains(old_device_code, ".")) {
                    String[] point = old_device_code.split("\\.");
                    device_code = point[0];
                    emptyNum = point[1];
                } else {
                    device_code = old_device_code;
                }
            }

            device = deviceAppService.findDeviceByCode(device_code);
            if (ObjectUtil.isEmpty(device_code)) {
                log.info(agvaddr + "对应设备号为空!");
                logServer.deviceExecuteLog(this.device_code, "", "", agvaddr + "对应设备号为空");
                return;
            }
            //校验agv上报站点编号与指令起始点相同
            if (ObjectUtil.isEmpty(inst)) {
                log.info("未找到编号{}对应的指令", ikey);
                logServer.deviceExecuteLog(this.device_code, "", "", "未找到关联编号对应的指令" + ikey);
                return;
            }
            // "========================================================================请求取货================================================================================="
            agv_status = 1;
            //到达桁架1请求取货
            if (device.getDeviceDriver() instanceof Hj1DeviceDriver) {
                hj1DeviceDriver = (Hj1DeviceDriver) device.getDeviceDriver();
                log.info("agv到达" + device_code + ",取货点,开始写入信号2进行进入申请,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                hj1DeviceDriver.writing(2);
                //反馈WMS请求取货
                //sendAgvTaskStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
                if (hj1DeviceDriver.getMode() != 0) {
                    if (hj1DeviceDriver.getAction() == 2) {
                        log.info("设备" + device_code + "的Action信号已变更为2允许进入,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",agv开始进入取货。");
                        flag = true;
                        data = ndcAgvService.sendAgvOneModeInst(phase, index, 0);
                    } else {
                        log.info("设备" + device_code + "的Action信号未变更为2,不允许进入,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",尝试重新写入信号2进行进入申请");
                        hj1DeviceDriver.writing(2);
                        log.info("设备" + device_code + "已完成信号2写入,当前信号值为：" + "Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                    }
                    hj1DeviceDriver.setMessage("");
                } else {
                    String message = "agv申请进入" + device_code + "，但设备Mode值为0，设备异常，请检查！";
                    agv_message = hj1DeviceDriver.getDevice_code() + message;
                    hj1DeviceDriver.setMessage(message);
                    log.info(message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达桁架2请求取货
            if (device.getDeviceDriver() instanceof Hj2DeviceDriver) {
                hj2DeviceDriver = (Hj2DeviceDriver) device.getDeviceDriver();
                log.info("agv到达" + device_code + ",取货点,开始写入信号7进行进入申请,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                hj2DeviceDriver.writing(7);
                //反馈WMS请求取货
                //sendAgvTaskStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
                if (hj2DeviceDriver.getMode() != 0) {
                    if (hj2DeviceDriver.getAction() == 2) {
                        log.info("设备" + device_code + "的Action信号已变更为2允许进入,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",agv开始进入取货。");
                        flag = true;
                        data = ndcAgvService.sendAgvOneModeInst(phase, index, 0);
                    } else {
                        log.info("设备" + device_code + "的Action信号未变更为2,不允许进入,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",尝试重新写入信号7进行进入申请");
                        hj2DeviceDriver.writing(7);
                        log.info("设备" + device_code + "已完成信号7写入,当前信号值为：" + "Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                    }
                    hj2DeviceDriver.setMessage("");
                } else {
                    String message = "agv申请进入" + device_code + "，但设备Mode值为0，设备异常，请检查！";
                    agv_message = hj2DeviceDriver.getDevice_code() + message;
                    hj2DeviceDriver.setMessage(message);
                    log.info(message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达输送线请求取货
            if (device.getDeviceDriver() instanceof SsxDeviceDriver) {
                ssxDeviceDriver = (SsxDeviceDriver) device.getDeviceDriver();
                //有货，待机，运行取货
                log.info("agv到达取货点" + device_code + ",需满足取货条件：Mode:1,Move:1,Action:1,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction());
                if (ssxDeviceDriver.getMove() == 1 & ssxDeviceDriver.getMode() == 1 & ssxDeviceDriver.getAction() == 1) {
                    log.info("agv到达取货点" + device_code + ",满足取货条件,开始取货,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction());
                    inst.setExecute_status("1");
                    instructionService.update(inst);
                    data = ndcAgvService.sendAgvOneModeInst(phase, index, 0);
                    ssxDeviceDriver.setMessage("");
                    flag = true;
                } else {
                    String message = "";
                    if (ssxDeviceDriver.getAction() != 1) {
                        message += "设备Action不为1,不允许取放货,设备异常,请检查!";
                    } else if (ssxDeviceDriver.getMode() != 1) {
                        message += "设备工作模式不为待机,无法取放货,请检查!";
                    } else if (ssxDeviceDriver.getMove() == 0) {
                        message += "设备光电信号为0,站点无货,请检查!";
                    }
                    ssxDeviceDriver.setMessage(message);
                    agv_message = ssxDeviceDriver.getDevice_code() + message;
                    logServer.deviceExecuteLog(device_code, "", "", message);
                    log.info(device_code + message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达普通站点
            if (device.getDeviceDriver() instanceof StandardOrdinarySiteDeviceDriver) {
                log.info("到达{}取货点开始取货", device_code);
                inst.setExecute_status("1");
                instructionService.update(inst);
                data = ndcAgvService.sendAgvOneModeInst(phase, index, 0);
                flag = true;
            }
            if (flag) {
                // log.info("==================允许AGV取货==================");
                // logServer.deviceExecuteLog(device_code, "", "", "允许AGV取货。");
                //log.info("{},{}", device_code, "允许AGV取货。");
                //  lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, "允许AGV取货。"));
            }
            //到达取货等待点
            //(需要WCS反馈)
        } else if (phase == 0x04) {
            data = getData(data, index, inst, task);
            //取货完毕
            //(需要WCS反馈)
        } else if (phase == 0x05) {
            if (agvaddr == 0) {
                agvaddr = agvaddr_copy;
            }
            if (agvaddr < 1) {
                logServer.deviceExecuteLog(this.device_code, "", "", "agv地址参数有误,phase:" + phase);
                return;
            }
            if (agvaddr != 0) {
                old_device_code = deviceService.queryDeviceCodeByAddress(agvaddr);
                if (StrUtil.contains(old_device_code, "-")) {
                    String[] point = old_device_code.split("-");
                    device_code = point[0];
                } else if (StrUtil.contains(old_device_code, ".")) {
                    String[] point = old_device_code.split("\\.");
                    device_code = point[0];
                    emptyNum = point[1];
                } else {
                    device_code = old_device_code;
                }
            }
            device = deviceAppService.findDeviceByCode(device_code);
            if (ObjectUtil.isEmpty(device_code)) {
                log.info(agvaddr + "对应设备号为空!");
                logServer.deviceExecuteLog(this.device_code, "", "", "对应设备号为空" + device_code);
                return;
            }
            //校验agv上报站点编号与指令起始点相同
            if (ObjectUtil.isEmpty(inst)) {
                log.info("未找到关联编号{}对应的指令", ikey);
                logServer.deviceExecuteLog(this.device_code, "", "", "未找到关联编号对应的指令" + ikey);
                return;
            }
// "========================================================================取货完成================================================================================="
            //反馈车辆动作
            agv_status = 2;
            //到达桁架1取货完成
            if (device.getDeviceDriver() instanceof Hj1DeviceDriver) {
                hj1DeviceDriver = (Hj1DeviceDriver) device.getDeviceDriver();
                if (hj1DeviceDriver.getMode() != 0) {
                    log.info("agv进入" + device_code + ",取货完成,开始写入信号3进行安全交互,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                    hj1DeviceDriver.writing(3);
                    if (hj1DeviceDriver.getMode() == 3) {
                        flag = true;
                        log.info("设备" + device_code + "的Mode信号已变更为3,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",开始写入0清除mode信号。");
                        hj1DeviceDriver.writing(0);
                        data = actionComplete(index, inst, device_code, hj1DeviceDriver.getTo_command(), Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("取货完成")), "取货完成");
                        log.info("设备" + device_code + "已完成信号0写入,当前信号值为：" + "Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",agv开始离开。");
                    } else {
                        log.info("设备" + device_code + "的Mode信号未变更为3,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",尝试重新写入信号3进行安全交互");
                        hj1DeviceDriver.writing(3);
                        log.info("设备" + device_code + "已完成信号3写入,当前信号值为：" + "Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                    }
                    hj1DeviceDriver.setMessage("");
                } else {
                    String message = "agv已取货完成，但设备Mode值为0，设备异常，请检查！";
                    agv_message = hj1DeviceDriver.getDevice_code() + message;
                    hj1DeviceDriver.setMessage(message);
                    log.info(message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达桁架2取货完成
            if (device.getDeviceDriver() instanceof Hj2DeviceDriver) {
                hj2DeviceDriver = (Hj2DeviceDriver) device.getDeviceDriver();
                if (hj2DeviceDriver.getMode() != 0) {
                    log.info("agv进入" + device_code + ",取货完成,开始写入信号3进行安全交互,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                    hj2DeviceDriver.writing(3);
                    if (hj2DeviceDriver.getMode() == 3) {
                        flag = true;
                        log.info("设备" + device_code + "的Mode信号已变更为3,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",开始写入0清除mode信号。");
                        hj2DeviceDriver.writing(0);
                        data = actionComplete(index, inst, device_code, hj2DeviceDriver.getTo_command(), Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("取货完成")), "取货完成");
                        log.info("设备" + device_code + "已完成信号0写入,当前信号值为：" + "Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",agv开始离开。");
                    } else {
                        log.info("设备" + device_code + "的Mode信号未变更为3,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",尝试重新写入信号3进行安全交互");
                        hj2DeviceDriver.writing(3);
                        log.info("设备" + device_code + "已完成信号3写入,当前信号值为：" + "Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                    }
                    hj2DeviceDriver.setMessage("");
                } else {
                    String message = "agv已取货完成，但设备Mode值为0，设备异常，请检查！";
                    agv_message = hj2DeviceDriver.getDevice_code() + message;
                    hj2DeviceDriver.setMessage(message);
                    log.info(message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达输送线取货完成
            if (device.getDeviceDriver() instanceof SsxDeviceDriver) {
                ssxDeviceDriver = (SsxDeviceDriver) device.getDeviceDriver();
                if (ssxDeviceDriver.getMode() != 0) {
                    log.info("agv进入" + device_code + ",取货完成,开始写入信号3进行安全交互,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction());
                    ssxDeviceDriver.writing(3);
                    if (ssxDeviceDriver.getMode() == 3) {
                        flag = true;
                        log.info("设备" + device_code + "的Mode信号已变更为3,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",开始写入0清除mode信号。");
                        ssxDeviceDriver.writing(0);
                        data = actionComplete(index, inst, device_code, ssxDeviceDriver.getTo_command(), Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("取货完成")), "取货完成");
                        log.info("设备" + device_code + "已完成信号0写入,当前信号值为：" + "Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",agv开始离开。");
                    } else {
                        log.info("设备" + device_code + "的Mode信号未变更为3,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",尝试重新写入信号3进行安全交互");
                        ssxDeviceDriver.writing(3);
                        log.info("设备" + device_code + "已完成信号3写入,当前信号值为：" + "Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction());
                    }
                    ssxDeviceDriver.setMessage("");
                } else {
                    String message = "agv取货完成写入信号3安全交互失败，设备允许模式mode值为0，设备异常，请检查！";
                    agv_message = ssxDeviceDriver.getDevice_code() + message;
                    ssxDeviceDriver.setMessage(message);
                    log.info(message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达普通站点取货完成
            if (device.getDeviceDriver() instanceof StandardOrdinarySiteDeviceDriver) {
                data = actionComplete(index, inst, device_code, 0, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("取货完成")), "取货完成");
                log.info("agv进入" + device_code + "取货完成");
                flag = true;
            }
            //到达放货等待点
            //(需要WCS反馈)
        } else if (phase == 0x06) {
            data = getData(data, index, inst, task);
            //到达放货点
            //(需要WCS反馈)
        } else if (phase == 0x07) {
            if (agvaddr == 0) {
                agvaddr = agvaddr_copy;
            }
            if (agvaddr < 1) {
                logServer.deviceExecuteLog(this.device_code, "", "", "agv地址参数有误,phase:" + phase);
                return;
            }
            if (agvaddr != 0) {
                old_device_code = deviceService.queryDeviceCodeByAddress(agvaddr);
                if (StrUtil.contains(old_device_code, "-")) {
                    String[] point = old_device_code.split("-");
                    device_code = point[0];
                } else if (StrUtil.contains(old_device_code, ".")) {
                    String[] point = old_device_code.split("\\.");
                    device_code = point[0];
                    emptyNum = point[1];
                } else {
                    device_code = old_device_code;
                }
            }
            device = deviceAppService.findDeviceByCode(device_code);
            if (ObjectUtil.isEmpty(device_code) && !device_code.equals("0")) {
                log.info(agvaddr + "对应设备号为空!");
                return;
            }
            //校验agv上报站点编号与指令起始点相同
            if (ObjectUtil.isEmpty(inst)) {
                log.info("未找到关联编号{}对应的指令", ikey);
                return;
            }
// "========================================================================请求放货================================================================================="
            agv_status = 3;
            //到达桁架1请求放货
            if (device.getDeviceDriver() instanceof Hj1DeviceDriver) {
                hj1DeviceDriver = (Hj1DeviceDriver) device.getDeviceDriver();
                hj1DeviceDriver.writing(2);
                log.info("agv到达" + device_code + ",放货点,开始写入信号2进行进入申请,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                //反馈WMS请求放货
                //sendAgvTaskStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
                if (hj1DeviceDriver.getMode() != 0 && hj1DeviceDriver.getMove() == 0) {
                    if (hj1DeviceDriver.getAction() == 3) {
                        log.info("设备" + device_code + "的Action信号已变更为3允许进入,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",agv开始进入放货。");
                        flag = true;
                        data = getData(data, index, inst, task);
                    } else {
                        log.info("设备" + device_code + "的Action信号未变更为3,不允许进入,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",尝试重新写入信号2进行进入申请");
                        hj1DeviceDriver.writing(2);
                        log.info("设备" + device_code + "已完成信号2写入,当前信号值为：" + "Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                        //反馈WMS请求放货
                        //sendAgvTaskStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
                    }
                    hj1DeviceDriver.setMessage("");
                } else {
                    String message = "";
                    if (hj1DeviceDriver.getMode() == 0) {
                        message += "设备Mode值为0，设备异常，请检查！";
                    } else {
                        message += "设备光电信号不为0，站点有货，请检查！";
                    }
                    message += "不允许AGV放货。";
                    agv_message = hj1DeviceDriver.getDevice_code() + message;
                    hj1DeviceDriver.setMessage(message);
                    logServer.deviceExecuteLog(device_code, "", "", message);
                    log.info(device_code + message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //到达桁架2请求放货
            if (device.getDeviceDriver() instanceof Hj2DeviceDriver) {
                hj2DeviceDriver = (Hj2DeviceDriver) device.getDeviceDriver();
                hj2DeviceDriver.writing(7);
                log.info("agv到达" + device_code + ",放货点,开始写入信号7进行进入申请,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                //反馈WMS请求放货
                //sendAgvTaskStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
                if (hj2DeviceDriver.getMode() != 0 && hj2DeviceDriver.getMove() == 0) {
                    if (hj2DeviceDriver.getAction() == 3) {
                        log.info("设备" + device_code + "的Action信号已变更为3允许进入,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",agv开始进入放货。");
                        flag = true;
                        data = getData(data, index, inst, task);
                    } else {
                        log.info("设备" + device_code + "的Action信号未变更为3,不允许进入,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",尝试重新写入信号7进行进入申请");
                        hj2DeviceDriver.writing(7);
                        log.info("设备" + device_code + "已完成信号7写入,当前信号值为：" + "Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                        //反馈WMS请求放货
                        //sendAgvTaskStatus(inst, device_code, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("请求取货")));
                    }
                    hj2DeviceDriver.setMessage("");
                } else {
                    String message = "";
                    if (hj2DeviceDriver.getMode() == 0) {
                        message += "设备Mode值为0，设备异常，请检查！";
                    } else {
                        message += "设备光电信号不为0，站点有货，请检查！";
                    }
                    message += "不允许AGV放货。";
                    agv_message = hj2DeviceDriver.getDevice_code() + message;
                    hj2DeviceDriver.setMessage(message);
                    logServer.deviceExecuteLog(device_code, "", "", message);
                    log.info(device_code + message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //输送线到达放货点
            if (device.getDeviceDriver() instanceof SsxDeviceDriver) {
                ssxDeviceDriver = (SsxDeviceDriver) device.getDeviceDriver();
                log.info("agv到达" + device_code + "放货点,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",准备执行放货");
                if (ssxDeviceDriver.getMove() == 0 & ssxDeviceDriver.getMode() == 1 & ssxDeviceDriver.getAction() == 1) {
                    if (inst != null) {
                        inst.setExecute_status("3");
                        instructionService.update(inst);
                    }
                    data = getData(data, index, inst, task);
                    ssxDeviceDriver.setMessage("");
                    flag = true;
                } else {
                    String message = "";
                    message += "放货失败,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",不满足放货条件Mode:1,Move:0,Action:1";
                    ssxDeviceDriver.setMessage(message);
                    agv_message = ssxDeviceDriver.getDevice_code() + message;
                    logServer.deviceExecuteLog(device_code, "", "", message);
                    log.info(message);
                    lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, message));
                }
            }
            //普通站点
            if (device.getDeviceDriver() instanceof StandardOrdinarySiteDeviceDriver) {
                log.info("到达{}放货点", device_code);
                data = ndcAgvService.sendAgvOneModeInst(phase, index, 0);
                flag = true;
            }
            if (flag) {
                // log.info("==================允许AGV放货==================");
                // logServer.deviceExecuteLog(device_code, "", "", "允许AGV放货。");
                // log.info("{},{}", device_code, "允许AGV放货。");
                // lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, "允许AGV放货。"));
            }
            //放货完毕
            //(需要WCS反馈)
        } else if (phase == 0x09) {
            if (agvaddr == 0) {
                agvaddr = agvaddr_copy;
            }
            if (agvaddr < 1) {
                logServer.deviceExecuteLog(this.device_code, "", "", "agv地址参数有误,phase:" + phase);
                return;
            }
            if (agvaddr != 0) {
                old_device_code = deviceService.queryDeviceCodeByAddress(agvaddr);
                if (StrUtil.contains(old_device_code, "-")) {
                    String[] point = old_device_code.split("-");
                    device_code = point[0];
                } else if (StrUtil.contains(old_device_code, ".")) {
                    String[] point = old_device_code.split("\\.");
                    device_code = point[0];
                    emptyNum = point[1];
                } else {
                    device_code = old_device_code;
                }
            }
            device = deviceAppService.findDeviceByCode(device_code);
            if (ObjectUtil.isEmpty(device_code)) {
                log.info(agvaddr + "对应设备号为空!");
                return;
            }

            //校验agv上报站点编号与指令起始点相同
            if (ObjectUtil.isEmpty(inst)) {
                log.info("未找到编号{}对应的指令", ikey);
                return;
            }
            transportOrder = "";
// "========================================================================放货完成================================================================================="
            agv_status = 4;
            //到达桁架1放货完成
            if (device.getDeviceDriver() instanceof Hj1DeviceDriver) {
                hj1DeviceDriver = (Hj1DeviceDriver) device.getDeviceDriver();
                log.info("agv进入" + device_code + ",放货完成,开始写入信号5进行安全交互,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                hj1DeviceDriver.writing(5);
                if (hj1DeviceDriver.getMode() == 4) {
                    log.info("设备" + device_code + "的Mode信号已变更为4,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",开始写入0清除mode信号。");
                    hj1DeviceDriver.writing(0);
                    flag = true;
                    data = actionComplete(index, inst, device_code, hj1DeviceDriver.getTo_command(), Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("放货完成")), "放货完成");
                    log.info("设备" + device_code + "已完成信号0写入,当前信号值为：" + "Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",agv开始离开。");
                } else {
                    log.info("设备" + device_code + "的Mode信号未变更为4,当前信号值为：Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction() + ",尝试重新写入信号5进行安全交互");
                    hj1DeviceDriver.writing(5);
                    log.info("设备" + device_code + "已完成信号5写入,当前信号值为：" + "Mode:" + hj1DeviceDriver.getMode() + ",Move:" + hj1DeviceDriver.getMove() + ",Action:" + hj1DeviceDriver.getAction());
                }
                hj1DeviceDriver.setMessage("");
            }
            //到达桁架2放货完成
            if (device.getDeviceDriver() instanceof Hj2DeviceDriver) {
                hj2DeviceDriver = (Hj2DeviceDriver) device.getDeviceDriver();
                log.info("agv进入" + device_code + ",放货完成,开始写入信号5进行安全交互,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                hj2DeviceDriver.writing(5);
                if (hj2DeviceDriver.getMode() == 4) {
                    log.info("设备" + device_code + "的Mode信号已变更为4,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",开始写入0清除mode信号。");
                    hj2DeviceDriver.writing(0);
                    flag = true;
                    data = actionComplete(index, inst, device_code, hj2DeviceDriver.getTo_command(), Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("放货完成")), "放货完成");
                    log.info("设备" + device_code + "已完成信号0写入,当前信号值为：" + "Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",agv开始离开。");
                } else {
                    log.info("设备" + device_code + "的Mode信号未变更为4,当前信号值为：Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction() + ",尝试重新写入信号5进行安全交互");
                    hj2DeviceDriver.writing(5);
                    log.info("设备" + device_code + "已完成信号5写入,当前信号值为：" + "Mode:" + hj2DeviceDriver.getMode() + ",Move:" + hj2DeviceDriver.getMove() + ",Action:" + hj2DeviceDriver.getAction());
                }
                hj2DeviceDriver.setMessage("");
            }
            //到达输送线放货完成
            if (device.getDeviceDriver() instanceof SsxDeviceDriver) {
                ssxDeviceDriver = (SsxDeviceDriver) device.getDeviceDriver();
                log.info("agv进入" + device_code + ",放货完成,开始写入信号5进行安全交互,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction());
                ssxDeviceDriver.writing(5);
                if (ssxDeviceDriver.getMode() == 4) {
                log.info("设备" + device_code + "的Mode信号已变更为4,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",开始写入0清除mode信号。");
                  ssxDeviceDriver.writing(0);
                flag = true;
                data = actionComplete(index, inst, device_code, ssxDeviceDriver.getTo_command(), Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("放货完成")), "放货完成");
                log.info("设备" + device_code + "已完成信号0写入,当前信号值为：" + "Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",agv开始离开。");
               } else {
                  log.info("设备" + device_code + "的Mode信号未变更为4,当前信号值为：Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction() + ",尝试重新写入信号5进行安全交互");
                  ssxDeviceDriver.writing(5);
                 log.info("设备" + device_code + "已完成信号5写入,当前信号值为：" + "Mode:" + ssxDeviceDriver.getMode() + ",Move:" + ssxDeviceDriver.getMove() + ",Action:" + ssxDeviceDriver.getAction());
               }
                ssxDeviceDriver.setMessage("");
            }
            //agv普通站点放货完成
            if (device.getDeviceDriver() instanceof StandardOrdinarySiteDeviceDriver) {
                log.info("{}放货完成", device_code);
                data = actionComplete(index, inst, device_code, 0, Integer.parseInt(AgvActionEnum.ACTION_STATUS.code("放货完成")), "放货完成");
                flag = true;
            }
            if (flag) {
                //log.info("================允许AGV放货后离开=================");
                //logServer.deviceExecuteLog(device_code, "", "", "允许AGV放货后离开。");
                // log.info("{},{}", device_code, "允许AGV放货后离开。");
                //lucene.deviceExecuteLog(new LuceneLogDto(this.device_code, "允许AGV放货后离开。"));
            }
        }
        //到达位置点
        //(需要WCS反馈)
        else if (phase == 0x64) {//param,agv货位id待定
            //1、根据货位id找到对应三工位设备，赋给agv属性地址对应的满料位设备
            agvaddr = arr[18] * 256 + arr[19];
            agvaddr_copy = agvaddr;
            data = ndcAgvService.sendAgvOneModeInst(phase, index, 0, 0, 0, 0, 0);
            logServer.deviceExecuteLog(this.device_code, "", "", "agvphase:" + phase + "反馈:" + data);
        } else if (phase == 0x50) {//进入交通灯区域
            data = ndcAgvService.sendAgvOneModeInst(phase, index, 0, 0, 0, 0, 0);
            logServer.deviceExecuteLog(this.device_code, "", "", "agvphase:" + phase + "反馈:" + data);
        } else if (phase == 0x51) {//离开交通灯区域
            data = ndcAgvService.sendAgvOneModeInst(phase, index, 0, 0, 0, 0, 0);
            logServer.deviceExecuteLog(this.device_code, "", "", "agvphase:" + phase + "反馈:" + data);
        } else if (phase == 0x70) {
            //x坐标
            x = ikey;
        } else if (phase == 0x71) {
            //y坐标
            y = ikey;
        } else if (phase == 0x72) {
            //车辆角度
            angle = ikey;
        } else if (phase == 0x73) {
            //agv电量
            electric_qty = ikey;
            // 电量不足充电
            //            int electric = Integer.parseInt(paramService.findByCode(AcsConfig.ELECTRIC).getValue());
            //            if (electric_qty > 0 && electric_qty < electric) {
            //                log.info("当前车辆{}电量为{}低于{}，开始判断是否需要充电!", this.device_code, electric_qty, electric);
            //                ndcAgvService.charge(String.valueOf(this.agvaddr));
            //                isCharge = true;
            //            }
        } else if (phase == 0x74) {
            status = ikey;
        } else if (phase == 0x75) {
            is_have = ikey;
        }
        if (!ObjectUtil.isEmpty(data)) {
            logServer.deviceExecuteLog(this.device_code, "", "", "agvphase:" + phase + "反馈:" + data);
            OneNDCSocketConnectionAutoRun.write(data);
        }
    }

    private byte[] actionComplete(int index, Instruction inst, String device_code, int to_command, int status, String action) {
        byte[] data;
        data = ndcAgvService.sendAgvOneModeInst(phase, index, 0);
        sendAgvTaskStatus(inst, device_code, status);
        logServer.deviceExecuteLog(this.device_code, "", "", action);
        return data;
    }


    private void sendAgvErrorStatus(Instruction inst, String device_code, Integer status) {
        if (inst == null) {
            return;
        }
        JSONArray ja = new JSONArray();
        JSONObject jo = new JSONObject();
        jo.put("vehicle_code", inst.getVehicle_code());
        jo.put("status", status);
        jo.put("device_code", this.device_code);
        jo.put("task_code", inst.getTask_code());
        ja.add(jo);
        LuceneLogDto reqlogDto = LuceneLogDto.builder()
                .device_code(device_code)
                .content("请求参数:" + jo)
                .requestparam("请求参数:" + jo)
                .method("sendAgvErrorStatus")
                .build();
        luceneExecuteLogService.deviceExecuteLog(reqlogDto);
        HttpResponse resp = acsToWmsService.feedAgvErrorStatus(ja);
        LuceneLogDto resplogDto = LuceneLogDto.builder()
                .device_code(device_code)
                .content("返回参数:" + resp.body())
                .responseparam("返回参数:" + resp.body())
                .method("feedAgvTaskStatus")
                .status_code(String.valueOf(resp.getStatus()))
                .build();
        luceneExecuteLogService.deviceExecuteLog(resplogDto);
    }


    private void sendAgvTaskStatus(Instruction inst, String device_code, Integer status) {
        CompletableFuture<String> future = new CompletableFuture<>();
        EXECUTOR.submit(() -> {
            try {
                if (inst == null) {
                    return;
                }
                JSONArray ja = new JSONArray();
                JSONObject jo = new JSONObject();
                jo.put("vehicle_code", inst.getVehicle_code());
                jo.put("status", status);
                jo.put("device_code", this.device_code);
                jo.put("task_code", inst.getTask_code());
                ja.add(jo);
                LuceneLogDto reqlogDto = LuceneLogDto.builder()
                        .device_code(device_code)
                        .content("请求参数:" + jo)
                        .requestparam("请求参数:" + jo)
                        .method("feedAgvTaskStatus")
                        .build();
                luceneExecuteLogService.deviceExecuteLog(reqlogDto);
                for (int i = 0; i < 10; i++) {
                    log.info("点位:" + device_code + ",agv开始反馈wcs动作" + AgvActionEnum.ACTION_STATUS.check(String.valueOf(status)) );
                    JSONObject resp = acsToWmsService.feedAgvTaskAction(ja);
                    if ("200".equals(resp.getString("code"))) {
                        JSONObject respjson = JSONObject.parseObject(resp.getString("msg"));
                        inst.setInstruction_status("1");
                        inst.setExecute_status("2");
                        instructionService.update(inst);
                        LuceneLogDto resplogDto = LuceneLogDto.builder()
                                .device_code(device_code)
                                .content("返回参数:" + respjson.getString("message"))
                                .responseparam("返回参数:" + respjson.getString("message"))
                                .method("feedAgvTaskStatus")
                                .status_code(String.valueOf(respjson.getString("code")))
                                .build();
                        luceneExecuteLogService.deviceExecuteLog(resplogDto);
                        log.info("点位:" + device_code + ",agv反馈wcs动作" + AgvActionEnum.ACTION_STATUS.check(String.valueOf(status)) + "成功。");
                        break;
                    } else {
                        log.info("点位:" + device_code + ",agv反馈wcs动作" + AgvActionEnum.ACTION_STATUS.check(String.valueOf(status)) + "失败,服务器响应的失败原因为：" + resp.getString("msg"));
                    }
                }
                future.complete("agv开始反馈wcs动作信息完成");
            } catch (Exception e) {
                future.completeExceptionally(e);
            }
        });
    }

    private byte[] getData(byte[] data, int index, Instruction inst, TaskDto task) {
        data = ndcAgvService.sendAgvOneModeInst(phase, index, 0, 0, 0, 0, 0);
        return data;
    }

}
