package org.nl.acs.device_driver.basedriver.standard_conveyor_control_with_plcscanner;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.nl.acs.AcsConfig;
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.RouteableDeviceDriver;
import org.nl.acs.device_driver.driver.AbstractOpcDeviceDriver;
import org.nl.acs.device_driver.driver.ExecutableDeviceDriver;
import org.nl.acs.ext.wms.service.AcsToWmsService;
import org.nl.acs.instruction.domain.Instruction;
import org.nl.acs.instruction.service.InstructionService;
import org.nl.acs.monitor.DeviceStageMonitor;
import org.nl.acs.opc.DeviceAppService;
import org.nl.acs.opc.WcsConfig;
import org.nl.acs.route.service.RouteLineService;
import org.nl.acs.route.service.dto.RouteLineDto;
import org.nl.acs.task.domain.Task;
import org.nl.acs.task.service.TaskService;
import org.nl.acs.task.service.dto.TaskDto;
import org.nl.acs.task.service.mapper.TaskMapper;
import org.nl.acs.utils.ConvertUtil;
import org.nl.system.service.param.ISysParamService;
import org.nl.config.SpringContextHolder;
import org.openscada.opc.lib.da.Server;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 输送机控制点-带扫描驱动
 */
@Slf4j
@Data
@RequiredArgsConstructor
public class StandardCoveyorControlWithPlcScannerDeviceDriver extends AbstractOpcDeviceDriver implements DeviceDriver, ExecutableDeviceDriver, RouteableDeviceDriver, DeviceStageMonitor {
    protected ItemProtocol itemProtocol = new ItemProtocol(this);
    @Autowired
    InstructionService instructionService = SpringContextHolder.getBean(InstructionService.class);
    @Autowired
    DeviceService deviceservice = SpringContextHolder.getBean(DeviceService.class);
    @Autowired
    RouteLineService routelineserver = SpringContextHolder.getBean(RouteLineService.class);
    @Autowired
    TaskService taskserver = SpringContextHolder.getBean(TaskService.class);
    @Autowired
    DeviceAppService deviceAppservice = SpringContextHolder.getBean(DeviceAppService.class);
    @Autowired
    RouteLineService routeLineService = SpringContextHolder.getBean(RouteLineService.class);
    @Autowired
    ISysParamService paramService = SpringContextHolder.getBean(ISysParamService.class);
    @Autowired
    AcsToWmsService acsToWmsService = SpringContextHolder.getBean(AcsToWmsService.class);
    ;

    @Autowired
    TaskMapper taskMapper;

    String barcode = null;
    String formatcode = null;

    String container;
    String container_type_desc;
    String last_container_type_desc;
    String last_container;
    //放货准备锁
    String putReadyLock = null;
    //有货标记
    protected boolean has_goods_tag = false;

    int mode = 0;
    int error = 0;
    int move = 0;
    int task = 0;
    int height = 0;
    int action = 0;
    int ioaction = 0;
    int direction = 0;
    int operation_type = 0;
    int last_mode = 0;
    int last_error = 0;
    int last_move = 0;
    int last_task = 0;
    String foramteBarcode = null;
    Boolean isonline = true;
    int hasGoods = 0;
    String message = null;
    Boolean iserror = false;
    String str = null;
    String inst_message;
    boolean hasVehicle = false;
    boolean isReady = false;
    protected int instruction_num = 0;
    protected int instruction_num_truth = 0;
    boolean isFold = false;
    private String assemble_check_tag;

    protected String current_stage_instruction_message;
    protected String last_stage_instruction_message;
    Integer heartbeat_tag;
    private Date instruction_require_time = new Date();
    private Date instruction_finished_time = new Date();
    private Date instruction_apply_time = new Date();
    private int instruction_require_time_out = 3000;
    //请求成功标记
    Boolean requireSucess = false;
    //申请指令成功标记
    Boolean applySucess = false;

    private int instruction_finished_time_out;

    int branchProtocol = 0;
    //备注
    String remark;
    //数量
    String qty;
    //物料
    String material;
    //当前指令
    Instruction inst = null;
    //上次指令
    Instruction last_inst = null;

    //触摸屏手动触发任务
    private Boolean is_has_task = false;

    //申请搬运任务
    private Boolean apply_handling = false;
    //申请物料
    private Boolean apply_material = false;

    //暂定 0就绪 1请求取货 2取货完成 3请求放货 4放货完成 5取货完成离开 6放货完成离开 7请求进入区域 8请求离开区域
    int flag;

    String device_code;


    @Override
    public Device getDevice() {
        return this.device;
    }

    @Override
    public void execute() {
        try {
            device_code = this.getDeviceCode();
            mode = this.itemProtocol.getMode();
            error = this.itemProtocol.getError();
            move = this.itemProtocol.getMove();
            task = this.itemProtocol.getTask();
            action = this.itemProtocol.getAction();
            ioaction = this.itemProtocol.getIoAction();
            height = this.itemProtocol.getHeight();
            operation_type = this.itemProtocol.getOperation_type();
            direction = this.itemProtocol.getDirection();
            hasGoods = this.itemProtocol.getMove();
            barcode = this.itemProtocol.getBarcode();
            if (mode != last_mode) {
                this.setRequireSucess(false);
            }
            if (move != last_move) {
                if (move == 0) {
                    thingToNothing();
                }
            }
            if (error != last_error) {
            }
            if (mode == 2 && move != 0 && task > 0) {
                //inst_message
                inst = instructionService.findByCodeFromCache(String.valueOf(task));
                if (inst != null) {
                    inst_message = "指令号:" + inst.getInstruction_code() + " " + inst.getStart_point_code() + "->" + inst.getNext_point_code() + "  载具号：" + inst.getVehicle_code();
                    if (StrUtil.equals(inst.getInstruction_status(), "0") && StrUtil.equals(this.getDeviceCode(), inst.getStart_device_code())) {
                        inst.setInstruction_status("1");
                        instructionService.update(inst);
                    }
                    if (StrUtil.equals(inst.getInstruction_status(), "1") && StrUtil.equals(this.getDeviceCode(), inst.getNext_device_code())) {
                        finish_instruction();
                    }
                }
            }

            if (!StrUtil.equals(this.getBarcode(), "0")) {
                message = this.getBarcode();
            }
        } catch (Exception var17) {
            return;
        }
        if (!this.itemProtocol.getIsonline()) {
            this.setIsonline(false);
            this.setIserror(true);
            message = "信号量同步异常";
            //未联机
        } else if (mode == 0) {
            this.setIsonline(false);
            this.setIserror(true);
            message = "未联机";
            //有报警
        } else if (error != 0) {
            this.setIsonline(false);
            this.setIserror(true);
            message = "有报警";
            //无报警
        } else {
            this.setIsonline(true);
            this.setIserror(false);
            message = "";
            Instruction instruction = null;
            List toInstructions;
            switch (mode) {
                case 1:
                    log.debug("设备运转模式:等待工作");
                    break;
                case 2:
                    //申请任务
                    if (hasGoods > 0 && !StrUtil.equals("0", barcode) && height > 0 && !requireSucess) {
                        instruction_require(barcode);
                    }
                    if (hasGoods > 0 && !StrUtil.equals("0", barcode) && height > 0 && !applySucess) {
                        instruction_apply(barcode);
                    }
            }
            switch (flag) {
                //取货完成
                case 1:
                    writing(2);
                    break;
                //放货完成
                case 2:
                    writing(3);
                    break;

            }
        }
        last_mode = mode;
        last_error = error;
        last_move = move;
        last_task = task;
    }

    private void forametPlcBarcode(int[] plcbarcode) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < plcbarcode.length; i++) {
            int a = plcbarcode[i];
            sb.append(stringToascii(a));
        }
        foramteBarcode = sb.toString();
    }

    public String stringToascii(int num) {
        String str = "";
        switch (num) {
            case 48:
                str = "0";
                break;
            case 49:
                str = "1";
                break;
            case 50:
                str = "2";
                break;
            case 51:
                str = "3";
                break;
            case 52:
                str = "4";
                break;
            case 53:
                str = "5";
                break;
            case 54:
                str = "6";
                break;
            case 55:
                str = "7";
                break;
            case 56:
                str = "8";
                break;
            case 57:
                str = "9";
                break;
            case 65:
                str = "A";
                break;
            case 66:
                str = "B";
                break;
            case 67:
                str = "C";
                break;
            case 68:
                str = "D";
                break;
            case 69:
                str = "E";
                break;
            case 70:
                str = "F";
                break;
            case 71:
                str = "G";
                break;
            case 72:
                str = "H";
                break;
            case 73:
                str = "I";
                break;
            case 74:
                str = "J";
                break;
            case 75:
                str = "K";
                break;
            case 76:
                str = "L";
                break;
            case 77:
                str = "M";
                break;
            case 78:
                str = "N";
                break;
            case 79:
                str = "O";
                break;
            case 80:
                str = "P";
                break;
            case 81:
                str = "Q";
                break;
            case 82:
                str = "R";
                break;
            case 83:
                str = "S";
                break;
            case 84:
                str = "T";
                break;
            case 85:
                str = "U";
                break;
            case 86:
                str = "V";
                break;
            case 87:
                str = "W";
                break;
            case 88:
                str = "X";
                break;
            case 89:
                str = "Y";
                break;
            case 90:
                str = "Z";
                break;

            case 97:
                str = "a";
                break;
            case 98:
                str = "b";
                break;
            case 99:
                str = "c";
                break;
            case 100:
                str = "d";
                break;
            case 101:
                str = "e";
                break;
            case 102:
                str = "f";
                break;
            case 103:
                str = "g";
                break;
            case 104:
                str = "h";
                break;
            case 105:
                str = "i";
                break;
            case 106:
                str = "j";
                break;
            case 107:
                str = "k";
                break;
            case 108:
                str = "l";
                break;
            case 109:
                str = "m";
                break;
            case 110:
                str = "n";
                break;
            case 111:
                str = "o";
                break;
            case 112:
                str = "p";
                break;
            case 113:
                str = "q";
                break;
            case 114:
                str = "r";
                break;
            case 115:
                str = "s";
                break;
            case 116:
                str = "t";
                break;
            case 117:
                str = "u";
                break;
            case 118:
                str = "v";
                break;
            case 119:
                str = "w";
                break;
            case 120:
                str = "x";
                break;
            case 121:
                str = "y";
                break;
            case 122:
                str = "z";
                break;

            case 40:
                str = "(";
                break;
            case 41:
                str = ")";
                break;
            case 43:
                str = "+";
                break;
            case 45:
                str = "-";
                break;
            case 47:
                str = "/";
                break;
            case 91:
                str = "[";
                break;
            case 93:
                str = "]";
                break;
            case 95:
                str = "_";
                break;
            default:
                str = "";
        }

        return str;
    }

    public boolean exe_error() {
        if (this.error == 0) {
            return true;
        } else {
            log.debug("设备报警");
            return false;
        }
    }

    public synchronized boolean finish_instruction() throws Exception {
        instructionService.finish(inst);
        return true;
    }

    protected void thingToNothing() throws Exception {
        this.setBarcode(null);
        this.setRequireSucess(false);
        this.setApplySucess(false);
        writing(1, 0);
        this.set_last_container(container, container_type_desc);
    }

    public void set_last_container(String barcode, String type_desc) {
        this.setInst_message(null);
        this.setContainer(null);
        this.set_last_container(barcode);
        this.set_last_container_type_desc(type_desc);
    }

    public void set_last_container(String barcode) {
    }

    public void set_last_container_type_desc(String type) {
    }

    public boolean exe_business() {
        return true;
    }

    protected void executing(Instruction instruction) {
        this.executing(1, instruction, "");
    }

    public void executing(int command, Instruction instruction, String appendMessage) {
        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_command;
        String to_target = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_target;
        String to_task = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_task;
        if (appendMessage == null) {
            appendMessage = "";
        }
        if (instruction != null) {
            instruction_num = Integer.parseInt(instruction.getInstruction_code());
        }
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        itemMap.put(to_command, 1);
        itemMap.put(to_task, instruction_num);
        this.control(itemMap);

    }

    public void executing(Server server, Map<String, Object> itemMap) {
        this.control(itemMap);
    }

    public void writing() {

        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_command;
        String to_target = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_target;
        String to_task = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_task;
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        itemMap.put(to_command, 1);
        itemMap.put(to_target, deviceAppservice.findDeviceByCode(inst.getNext_device_code()).getAddress());
        itemMap.put(to_task, inst.getInstruction_code());
        this.control(itemMap);
    }

    public void writing(int command, int target, int task) {

        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_command;
        String to_target = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_target;
        String to_task = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_task;
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        itemMap.put(to_command, command);
        itemMap.put(to_target, target);
        itemMap.put(to_task, task);

        this.control(itemMap);

//        this.control(itemMap);
    }

    public void writing(int command) {
        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_command;
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        itemMap.put(to_command, command);
        this.control(itemMap);
    }

    public void writing(int type, int command) {
        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_command;
        String to_target = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_target;
        String to_task = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + ItemProtocol.item_to_task;
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        if (type == 1) {
            itemMap.put(to_command, command);
        } else if (type == 2) {
            itemMap.put(to_target, command);

        } else if (type == 3) {
            itemMap.put(to_task, command);
        }

        this.control(itemMap);
    }

    public boolean instruction_require(String container_code)  {
        return instruction_require(container_code, WcsConfig.task_container_type_default_desc);
    }

    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean instruction_apply(String container_code) {
        Date date = new Date();
        if (date.getTime() - this.instruction_apply_time.getTime() < (long) this.instruction_require_time_out) {
            log.trace("触发时间因为小于{}毫秒，而被无视", this.instruction_require_time_out);
            return false;
        } else {
            this.instruction_apply_time = date;
            //container_code
            TaskDto task = taskserver.findByContainer(container_code);
            if (!ObjectUtil.isEmpty(task) && StrUtil.equals(task.getTask_status(), "0")) {
                String taskid = task.getTask_id();
                String taskcode = task.getTask_code();
                String vehiclecode = task.getVehicle_code();
                String priority = task.getPriority();
                String start_point_code = task.getStart_point_code();
                String start_device_code = task.getStart_device_code();
                String route_plan_code = task.getRoute_plan_code();
                String next_device_code = "";

                /**
                 * 开始平均分配
                 */
                String this_coevice_code = taskserver.queryAssignedByDevice(device_code, task.getNext_device_code());
                if (StrUtil.isEmpty(this_coevice_code)) {
                    List<RouteLineDto> shortPathsList = routeLineService.getShortPathLines(start_device_code, task.getNext_device_code(), route_plan_code);
                    RouteLineDto routeLineDto = shortPathsList.get(0);

                    String path = routeLineDto.getPath();
                    String type = routeLineDto.getType();
                    String[] str = path.split("->");
                    if (!StrUtil.equals(type, "0")) {
                        return false;
                    }
                    List<String> pathlist = Arrays.asList(str);
                    int index = 0;
                    for (int m = 0; m < pathlist.size(); m++) {
                        if (pathlist.get(m).equals(start_device_code)) {
                            index = m + 1;
                            break;
                        }
                    }
                    next_device_code = pathlist.get(index);
                } else {
                    next_device_code = this_coevice_code;
                }
                //校验路由关系
                List<RouteLineDto> shortPathsList = routeLineService.getShortPathLines(start_device_code, next_device_code, route_plan_code);
                if (ObjectUtils.isEmpty(shortPathsList)) {
                    throw new RuntimeException("路由不通!");
                }

                Device startdevice = deviceAppservice.findDeviceByCode(start_device_code);
                Device nextdevice = deviceAppservice.findDeviceByCode(next_device_code);
                String next_point_code;
                if (StrUtil.equals(deviceAppservice.findDeviceTypeByCode(next_device_code), "storage")) {
                    next_point_code = task.getTo_x() + "-" + task.getTo_y() + "-" + task.getTo_z();
                } else {
                    next_point_code = next_device_code;
                }
                Instruction instdto = new Instruction();
                instdto.setInstruction_id(IdUtil.simpleUUID());
                instdto.setRoute_plan_code(route_plan_code);
                instdto.setRemark(task.getRemark());
                instdto.setMaterial(task.getMaterial());
                instdto.setQuantity(task.getQuantity());
                instdto.setTask_id(taskid);
                instdto.setTask_code(taskcode);
                instdto.setVehicle_code(vehiclecode);
                String now = DateUtil.now();
                instdto.setCreate_time(now);
                instdto.setCreate_by("auto");
                instdto.setStart_device_code(start_device_code);
                instdto.setNext_device_code(next_device_code);
                instdto.setStart_point_code(start_point_code);
                instdto.setNext_point_code(next_point_code);
                instdto.setPriority(priority);
                instdto.setInstruction_status("0");
                instdto.setExecute_device_code(start_point_code);
                try {
                    instructionService.create(instdto);
                } catch (Exception e) {
                    task.setRemark("指令创建失败:" + e);
                    taskserver.updateByCodeFromCache(task);
                    throw new RuntimeException("指令创建失败:" + e);
                }
                //创建指令后修改任务状态
//                WQLObject taskwo = WQLObject.getWQLObject("acs_task");
                task.setTask_status("1");
                task.setRemark(null);
//                JSONObject json = (JSONObject) JSONObject.toJSON(task);
//                taskwo.update(json);

                Task entity = ConvertUtil.convert(task, Task.class);
                taskMapper.updateById(entity);

                applySucess = true;
            } else {
                log.info("未找到载具号{}对应任务", barcode);
            }
        }
        return true;
    }

    /**
     * 请求指令
     *
     * @param container_code
     * @param container_type
     */
    @Transactional(rollbackFor = Exception.class)
    public synchronized boolean instruction_require(String container_code, String container_type) {
        Date date = new Date();
        if (date.getTime() - this.instruction_require_time.getTime() < (long) this.instruction_require_time_out) {
            log.trace("触发时间因为小于{}毫秒，而被无视", this.instruction_require_time_out);
            return false;
        } else {
            this.instruction_require_time = date;
            //container_code
            TaskDto task = taskserver.findByContainer(container_code);
            if (!ObjectUtil.isEmpty(task) && StrUtil.equals(task.getTask_status(), "0")) {
                String taskid = task.getTask_id();
                String taskcode = task.getTask_code();
                String vehiclecode = task.getVehicle_code();
                String priority = task.getPriority();
                String start_point_code = task.getStart_point_code();
                String start_device_code = task.getStart_device_code();
                String route_plan_code = task.getRoute_plan_code();
                String next_device_code = "";

                /**
                 * 开始平均分配
                 */
                String this_coevice_code = taskserver.queryAssignedByDevice(device_code, task.getNext_device_code());
                if (StrUtil.isEmpty(this_coevice_code)) {
                    List<RouteLineDto> shortPathsList = routeLineService.getShortPathLines(start_device_code, task.getNext_device_code(), route_plan_code);
                    RouteLineDto routeLineDto = shortPathsList.get(0);

                    String path = routeLineDto.getPath();
                    String type = routeLineDto.getType();
                    String[] str = path.split("->");
                    if (!StrUtil.equals(type, "0")) {
                        return false;
                    }
                    List<String> pathlist = Arrays.asList(str);
                    int index = 0;
                    for (int m = 0; m < pathlist.size(); m++) {
                        if (pathlist.get(m).equals(start_device_code)) {
                            index = m + 1;
                            break;
                        }
                    }
                    next_device_code = pathlist.get(index);
                } else {
                    next_device_code = this_coevice_code;
                }
                //校验路由关系
                List<RouteLineDto> shortPathsList = routeLineService.getShortPathLines(start_device_code, next_device_code, route_plan_code);
                if (ObjectUtils.isEmpty(shortPathsList)) {
                    throw new RuntimeException("路由不通!");
                }

                Device startdevice = deviceAppservice.findDeviceByCode(start_device_code);
                Device nextdevice = deviceAppservice.findDeviceByCode(next_device_code);
                String next_point_code;
                if (StrUtil.equals(deviceAppservice.findDeviceTypeByCode(next_device_code), "storage")) {
                    next_point_code = task.getTo_x() + "-" + task.getTo_y() + "-" + task.getTo_z();
                } else {
                    next_point_code = next_device_code;
                }
                Instruction instdto = new Instruction();
                instdto.setInstruction_id(IdUtil.simpleUUID());
                instdto.setRoute_plan_code(route_plan_code);
                instdto.setRemark(task.getRemark());
                instdto.setMaterial(task.getMaterial());
                instdto.setQuantity(task.getQuantity());
                instdto.setTask_id(taskid);
                instdto.setTask_code(taskcode);
                instdto.setVehicle_code(vehiclecode);
                String now = DateUtil.now();
                instdto.setCreate_time(now);
                instdto.setCreate_by("auto");
                instdto.setStart_device_code(start_device_code);
                instdto.setNext_device_code(next_device_code);
                instdto.setStart_point_code(start_point_code);
                instdto.setNext_point_code(next_point_code);
                instdto.setPriority(priority);
                instdto.setInstruction_status("0");
                instdto.setExecute_device_code(start_point_code);
                try {
                    instructionService.create(instdto);
                } catch (Exception e) {
                    task.setRemark("指令创建失败:" + e);
                    taskserver.updateByCodeFromCache(task);
                    throw new RuntimeException("指令创建失败:" + e);
                }
                //创建指令后修改任务状态
//                WQLObject taskwo = WQLObject.getWQLObject("acs_task");
                task.setTask_status("1");
                task.setRemark(null);
//                JSONObject json = (JSONObject) JSONObject.toJSON(task);
//                taskwo.update(json);

                Task entity = ConvertUtil.convert(task, Task.class);
                taskMapper.updateById(entity);
                requireSucess = true;
                applySucess = true;
            } else {
                if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                    //String str = acsToWmsService.applyTaskToWms(this.getDeviceCode(), container_code, height, 0);
                    JSONObject jo = JSON.parseObject(str);
                    if (ObjectUtil.isEmpty(jo)) {
                        message = "接口不通";
                    } else {
                        if (jo.getInteger("status") == 200) {
                            requireSucess = true;
                        } else {
                            requireSucess = false;
                        }
                    }

                }
            }
            return true;
        }
    }

    @Override
    public JSONObject getDeviceStatusName() {
        JSONObject jo = new JSONObject();
        String mode = "";
        String action = "";
        String move = "";
        if (this.getMode() == 0) {
            mode = "未联机";
        } else if (this.getMode() == 1) {
            mode = "单机";
        } else if (this.getMode() == 2) {
            mode = "联机";
        } else if (this.getMode() == 3) {
            mode = "运行中";
        }

        if (this.getMove() == 0) {
            move = "无货";
            jo.put("hasGoods", false);
        } else if (this.getMove() == 1) {
            move = "有货";
            jo.put("hasGoods", true);
        } else if (this.getMove() == 2) {
            move = "有托盘有货";
            jo.put("hasGoods", true);
        }
        String requireSucess = "0";
        if (this.requireSucess) {
            requireSucess = "1";
        }
        String applySucess = "0";
        if (this.applySucess) {
            applySucess = "1";
        }
        jo.put("requireSucess", requireSucess);
        jo.put("applySucess", applySucess);
        jo.put("driver_type", "standard_conveyor_control_with_scanner");
        jo.put("is_click", true);
        jo.put("device_name", this.getDevice().getDevice_name());
        jo.put("mode", mode);
        jo.put("move", move);
        jo.put("action", action);
        jo.put("isOnline", this.getIsonline());
        jo.put("error", this.getError());
        jo.put("isError", this.getIserror());
        jo.put("task", this.getTask());
        return jo;
    }

    @Override
    public void setDeviceStatus(JSONObject data) {
        String requestSucess = data.getString("requireSucess");
        if (StrUtil.equals(requestSucess, "0")) {
            this.requireSucess = false;
        } else if (StrUtil.equals(requestSucess, "1")) {
            this.requireSucess = true;
        }
    }


}
