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

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.ScannerDeviceDriver;
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.log.service.DeviceExecuteLogService;
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.service.TaskService;
import org.nl.acs.task.service.dto.TaskDto;
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 java.util.*;

/**
 * 输送机控制点-带扫描驱动
 */
@Slf4j
@Data
@RequiredArgsConstructor
public class StandardCoveyorControlWithScannerDeviceDriver 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
    DeviceExecuteLogService logServer = SpringContextHolder.getBean("deviceExecuteLogServiceImpl");
    String container;

    protected String barcode = null;
    protected String formatcode = null;

    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;
    //当前指令
    Instruction inst = null;
    int heartbeat = 0;
    int mode = 0;
    int move = 0;
    int action = 0;
    int error = 0;
    int task = 0;
    String plcbarcode = null;
    String last_plcbarcode = null;
    int plcbarcode_length = 0;
    int last_plcbarcode_length = 0;

    Boolean isonline = true;

    Boolean iserror = false;

    //1-执行任务；2-取货完成；3-放货完成；
    int flag;

    int last_mode = 0;
    int last_move = 0;
    int last_error = 0;
    int last_task = 0;
    String last_container;
    String inst_message;
    String device_code;

    String message;

    //请求成功标记
    Boolean requireSucess = false;

    //申请成功标记
    Boolean applySucess = false;

    public boolean exe_declaration() {
        try {
            this.barcode = this.barcode();
            this.formatcode = this.formatBarcode();
            return true;
        } catch (Exception var3) {
            String message = "获取条码异常";
            return false;
        }
    }

    public String formatBarcode() throws Exception {
        String barcode = this.barcode();
        if (!StrUtil.isEmpty(barcode)) {
            barcode = barcode.trim();
        }

        return barcode;
    }

    public String barcode() {
        ScannerDeviceDriver scanner = this.getScanner();
        return scanner.readBarcode();
    }

    public void clearBarcode() {
        ScannerDeviceDriver scanner = this.getScanner();
        scanner.cleanBarcode();
        logServer.deviceExecuteLog(this.device_code, "", "", "清理条码");
    }
    public synchronized boolean finish_instruction(){
        try {
            instructionService.finish(inst);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private ScannerDeviceDriver getScanner() {
        String scanner_code = (String) this.getDevice().getExtraValue().get(StandardConveyorWithScannerConfig.relation_scanner);
        if (StrUtil.isEmpty(scanner_code)) {
            log.error("未配置读码器");
//            throw new Exception("未配置读码器");
        } else {
            Device device = deviceAppservice.findDeviceByCode(scanner_code);
            if (device == null) {
//                throw new Exception("无设备:" + scanner_code);
                log.error("无设备:" + scanner_code);
            } else {
                DeviceDriver deviceDriver = device.getDeviceDriver();
                if (!(deviceDriver instanceof ScannerDeviceDriver)) {
//                    throw new Exception("扫码器类型不对,不是ScannerDeviceDriver");
                    log.error("扫码器类型不对,不是ScannerDeviceDriver");
                } else {
                    ScannerDeviceDriver driver = (ScannerDeviceDriver) deviceDriver;
                    return driver;
                }
            }
        }
        return null;
    }

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


    @Override
    public void execute(){
        try {
            device_code = this.getDeviceCode();
            heartbeat = this.itemProtocol.getHeartbeat();
            mode = this.itemProtocol.getMode();
            move = this.itemProtocol.getMove();
            error = this.itemProtocol.getError();
            task = this.itemProtocol.getTask();
            plcbarcode =  this.itemProtocol.getplcBarCode();
            plcbarcode_length =  this.itemProtocol.getBarCode_length();

            if (mode != last_mode) {
                logServer.deviceExecuteLog(this.device_code, "", "", "信号mode：" + last_mode + "->" + mode +"复位请求标记");
                if(mode == 2){
                    this.setRequireSucess(false);
                    this.setApplySucess(false);
                    message = null;
                }
            }
            if (move != last_move) {
                if (move == 0) {
                    message = null;
                    inst_message = null;
                    clearBarcode();
                    thingToNothing();
                }
                logServer.deviceExecuteLog(this.device_code, "", "", "信号move：" + last_move + "->" + move);
            }
            if (error != last_error) {
                logServer.deviceExecuteLog(this.device_code, "", "", "信号error：" + last_error + "->" + error);
            }
            if (plcbarcode_length != last_plcbarcode_length) {
                logServer.deviceExecuteLog(this.device_code, "", "", "信号plcbarcode_length：" + last_plcbarcode_length + "->" + plcbarcode_length);
            }
            if (!StrUtil.equals(plcbarcode,last_plcbarcode) ) {
                logServer.deviceExecuteLog(this.device_code, "", "", "信号plcbarcode：" + last_plcbarcode + "->" + plcbarcode);
            }

            if (task != last_task) {
                logServer.deviceExecuteLog(this.device_code, "", "", "信号task：" + last_task+ "->" + task);
            }
            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(), "1") && StrUtil.equals(this.getDeviceCode(), inst.getNext_device_code())) {
                        inst.setExecute_device_code(this.device_code);
                        finish_instruction();
                    }
                    if (StrUtil.equals(inst.getInstruction_status(), "0") && StrUtil.equals(this.getDeviceCode(), inst.getStart_device_code())) {
                        inst.setInstruction_status("1");
                        inst.setExecute_device_code(this.device_code);
                        instructionService.update(inst);
                    }
                }
            }

        } 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 {
            this.setIsonline(true);
            this.setIserror(false);
            message = "";
            Instruction instruction = null;
            List toInstructions;
            switch (mode) {
                case 1:
                    log.debug("设备运转模式:等待工作");
                    break;
                case 2:
                    //申请任务
                    String newBarcode = null;

                    if(!StrUtil.isEmpty(barcode())){
                        newBarcode = barcode();
                    } else {
                        //
                        if(plcbarcode_length>2){
                            newBarcode = plcbarcode;
                        } else {
                            break;
                        }
                    }

                    if (move > 0 && !StrUtil.isEmpty(newBarcode) && !requireSucess) {
                        instruction_require(newBarcode.trim());
                    }
                    if (move > 0 && !StrUtil.isEmpty(newBarcode) && !applySucess) {
                        instruction_apply(newBarcode.trim());
                    }
            }
            switch (flag) {
                //取货完成
                case 1:
                    writing(2);
                    break;
                //放货完成
                case 2:
                    writing(3);
                    break;

            }
        }
        last_mode = mode;
        last_error = error;
        last_move = move;
        last_task = task;
        last_plcbarcode_length = plcbarcode_length;
        last_plcbarcode = plcbarcode;
    }

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

    protected void thingToNothing() throws Exception {
        this.setBarcode(null);
        this.setRequireSucess(false);
        this.setApplySucess(false);
        applySucess = false;
        clearBarcode();
        this.set_last_container(container);
        List list = new ArrayList();
        Map map = new HashMap();
        map.put("code","to_target");
        map.put("value","0");
        list.add(map);
        Map map2 = new HashMap();
        map2.put("code","to_task");
        map2.put("value","0");
        list.add(map2);
        Map map3 = new HashMap();
        map3.put("code","to_command");
        map3.put("value","0");
        list.add(map3);
        Map map4 = new HashMap();
        map4.put("code","to_strap_times");
        map4.put("value","0");
        list.add(map4);
        Map map5 = new HashMap();
        map5.put("code","to_length");
        map5.put("value","0");
        list.add(map5);
        Map map6 = new HashMap();
        map6.put("code","to_weight");
        map6.put("value","0");
        list.add(map6);
        Map map7 = new HashMap();
        map7.put("code","to_height");
        map7.put("value","0");
        list.add(map7);
        this.writing(list);
        message = null;
    }

    public void set_last_container(String barcode) {
        this.setContainer(null);
    }


    public void set_last_container_type_desc(String type) {
    }

    public boolean exe_business() {
        return true;
    }

    public void executing(Server server, Map<String, Object> itemMap) {
        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);
    }

    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);
    }

    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)) {
                Instruction instdto = instructionService.findByTaskcodeAndStatus(task.getTask_code());
                if(!StrUtil.equals(instdto.getStart_device_code(),this.device_code)){
                    message ="当前载具号"+container_code+"查找对应指令起点与当前设备不符";
//                    this.setIserror(true);
                    return false;
                }
                if(ObjectUtil.isNotEmpty(instdto)){
                    List list = new ArrayList();
                    Map map = new HashMap();

                    if(StrUtil.isNotEmpty(task.getTo_z())){
                        if(StrUtil.equals(task.getTo_z(),"01")){
                            map.put("code","to_target");
                            map.put("value","102");
                        } else if(StrUtil.equals(task.getTo_z(),"02")){
                            map.put("code","to_target");
                            map.put("value","201");
                        } else if(StrUtil.equals(task.getTo_z(),"03")){
                            map.put("code","to_target");
                            map.put("value","301");
                        }
                    }
                    list.add(map);
                    Map map2 = new HashMap();
                    map2.put("code","to_task");
                    map2.put("value",instdto.getInstruction_code());
                    list.add(map2);
                    Map map3 = new HashMap();
                    map3.put("code","to_command");
                    map3.put("value","1");
                    list.add(map3);
                    this.writing(list);
                    message = "下发电气任务号成功";
                    requireSucess = true;
                    applySucess = true;
                } else {
                    message = "任务号:"+ task.getTask_code()+"未找到指令";
                }

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

    /**
     * 请求指令
     * 定点任务时请求这里
     * @param container_code
     * @param container_type
     */
    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 taskdto = taskserver.findByContainer(container_code);
            if (!ObjectUtil.isEmpty(taskdto)) {
                if (!ObjectUtils.isEmpty(instructionService.findByTaskcodeAndStatus(taskdto.getTask_code()))) {
                    logServer.deviceExecuteLog(this.device_code, "", "", "申请任务时该载具号"+container_code
                            +"已存在对应任务，不再请求");
                            Instruction instdto = instructionService.findByTaskcodeAndStatus(taskdto.getTask_code());
                    if(!StrUtil.equals(instdto.getStart_device_code(),this.device_code)){
                        message ="当前载具号"+container_code+"查找对应指令起点与当前设备不符";
                        logServer.deviceExecuteLog(this.device_code, "", "", "申请任务"
                        +"当前载具号"+container_code+"查找对应指令起点与当前设备不符");
//                        this.setIserror(true);
//                        List list = new ArrayList();
//                        Map map = new HashMap();
//                        map.put("code","to_target");
//                        map.put("value","1011");
//                        list.add(map);
//                        Map map2 = new HashMap();
//                        map2.put("code","to_command");
//                        map2.put("value","1");
//                        Map map3 = new HashMap();
//                        map3.put("code","to_task");
//                        map3.put("value","0");
//                        list.add(map3);
//                        this.writing(list);
//                        this.setRequireSucess(true);
//                        this.setApplySucess(true);
                        return false;
                    }
                    this.setIserror(false);
                    if (ObjectUtil.isNotEmpty(instdto)) {
                        List list = new ArrayList();
                        Map map = new HashMap();

                        if (StrUtil.isNotEmpty(taskdto.getTo_z())) {
                            if (StrUtil.equals(taskdto.getTo_z(), "01")) {
                                map.put("code", "to_target");
                                map.put("value", "102");
                            } else if (StrUtil.equals(taskdto.getTo_z(), "02")) {
                                map.put("code", "to_target");
                                map.put("value", "201");
                            } else if (StrUtil.equals(taskdto.getTo_z(), "03")) {
                                map.put("code", "to_target");
                                map.put("value", "301");
                            }
                        }
                        list.add(map);
                        Map map2 = new HashMap();
                        map2.put("code", "to_task");
                        map2.put("value", instdto.getInstruction_code());
                        list.add(map2);
                        Map map3 = new HashMap();
                        map3.put("code", "to_command");
                        map3.put("value", "1");
                        list.add(map3);
                        this.writing(list);
                        message = "下发电气任务号成功";
                        logServer.deviceExecuteLog(this.device_code, "", "", "申请任务时该载具号"+container_code
                                +"已存在对应任务，下发电气信号");
//                        if(task != Integer.parseInt(instdto.getInstruction_code()) ){
//                            this.writing(list);
//                            logServer.deviceExecuteLog(device_code, "", "", instdto.getInstruction_code() + "再次下发电气信号");
//                        }
                        requireSucess = true;
                        applySucess = true;
                    } else {
                        message = "任务号:" + taskdto.getTask_code() + "未找到指令";
                    }
                    return true;
                }

                String taskid = taskdto.getTask_id();
                String taskcode = taskdto.getTask_code();
                String vehiclecode = taskdto.getVehicle_code();
                String priority = taskdto.getPriority();
                String start_point_code = taskdto.getStart_point_code();
                String start_device_code = taskdto.getStart_device_code();
                String route_plan_code = taskdto.getRoute_plan_code();
                String next_device_code = "";

                /**
                 * 开始平均分配
                 */
                String this_coevice_code = taskserver.queryAssignedByDevice(device_code, taskdto.getNext_device_code());
                if (StrUtil.isEmpty(this_coevice_code)) {
                    List<RouteLineDto> shortPathsList = routeLineService.getShortPathLines(start_device_code, taskdto.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 = taskdto.getTo_x() + "-" + taskdto.getTo_y() + "-" + taskdto.getTo_z();
                } else {
                    next_point_code = next_device_code;
                }

                if(!StrUtil.equals(taskdto.getStart_device_code(),this.device_code)){
                    message ="当前载具号"+container_code+"查找对应指令起点与当前设备不符";
//                    List list = new ArrayList();
//                    Map map = new HashMap();
//                    map.put("code","to_target");
//                    map.put("value","1011");
//                    list.add(map);
//                    Map map2 = new HashMap();
//                    map2.put("code","to_command");
//                    map2.put("value","1");
//                    Map map3 = new HashMap();
//                    map3.put("code","to_task");
//                    map3.put("value","0");
//                    list.add(map3);
//                    this.writing(list);
//                    this.setRequireSucess(true);
//                    this.setApplySucess(true);
                    return false;
                }
                Instruction instdto = new Instruction();
                instdto.setInstruction_id(IdUtil.simpleUUID());
                instdto.setRoute_plan_code(route_plan_code);
                instdto.setRemark(taskdto.getRemark());
                instdto.setMaterial(taskdto.getMaterial());
                instdto.setQuantity(taskdto.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) {
                    e.printStackTrace();
                    log.error("指令创建失败!",e.getMessage());
                    return  false;
                }
                //创建指令后修改任务状态
                taskdto.setTask_status("1");
                taskserver.update(taskdto);


                List list = new ArrayList();
                Map map = new HashMap();

                if(StrUtil.isNotEmpty(taskdto.getTo_z())){
                    if(StrUtil.equals(taskdto.getTo_z(),"01")){
                        map.put("code","to_target");
                        map.put("value","102");
                    } else if(StrUtil.equals(taskdto.getTo_z(),"02")){
                        map.put("code","to_target");
                        map.put("value","201");
                    } else if(StrUtil.equals(taskdto.getTo_z(),"03")){
                        map.put("code","to_target");
                        map.put("value","301");
                    }
                }
                list.add(map);
                Map map2 = new HashMap();
                map2.put("code","to_task");
                map2.put("value",instdto.getInstruction_code());
                list.add(map2);
                Map map3 = new HashMap();
                map3.put("code","to_command");
                map3.put("value","1");
                list.add(map3);
                this.writing(list);
//                if(task != Integer.parseInt(instdto.getInstruction_code()) ){
//                    this.writing(list);
//                    logServer.deviceExecuteLog(device_code, "", "", instdto.getInstruction_code() + "再次下发电气信号");
//                }
                requireSucess = true;
                applySucess = true;
            } else {
                if (StrUtil.equals(paramService.findByCode(AcsConfig.HASWMS).getValue(), "1")) {
                    message = "申请任务中...";
                    JSONObject apply = new JSONObject();
                    apply.put("vehicle_code", container_code);
                    apply.put("device_code", device_code);
                    apply.put("type","1");
                    String str = acsToWmsService.applyTaskToWms(apply);
                    JSONObject jo = JSON.parseObject(str);
                    if (ObjectUtil.isEmpty(jo)) {
                        message = "接口不通";
                        List list = new ArrayList();
                        Map map = new HashMap();
                        map.put("code","to_target");
                        map.put("value","1011");
                        list.add(map);
                        Map map2 = new HashMap();
                        map2.put("code","to_command");
                        map2.put("value","1");
                        Map map3 = new HashMap();
                        map3.put("code","to_task");
                        map3.put("value","0");
                        list.add(map3);
                        this.writing(list);
                        message = "申请任务失败接口不通下发退回";
                    } else {
                        if (jo.getInteger("status") == 200) {
                            message = "申请任务成功";
                            requireSucess = true;
                            applySucess = false;
                        } else {
                            if (jo.get("message")!=null){
                                message = jo.get("message").toString();
                            }

                            List list = new ArrayList();
                            Map map = new HashMap();
                            map.put("code","to_target");
                            map.put("value","1011");
                            list.add(map);
                            Map map2 = new HashMap();
                            map2.put("code","to_command");
                            map2.put("value","1");
                            list.add(map2);
                            Map map3 = new HashMap();
                            map3.put("code","to_task");
                            map3.put("value","0");
                            list.add(map3);
                            this.writing(list);
                            message = "申请任务失败下发退回，"+message;
                            requireSucess = true;

                        }
                    }
//                    requireSucess = true;
//                    message = "申请任务成功";
                }
            }
            return true;
        }
    }


    public void writing(String param, String value) {

        String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + param;
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();

        itemMap.put(to_param, Integer.parseInt(value));
//            itemMap.put(to_param, Integer.parseInt(value));
        this.control(itemMap);

    }

    public void writing(List list) {

//        String opcservcerid = this.getDevice().getOpc_server_id();
//        Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        for (int i = 0; i < list.size(); i++) {
            Object ob = list.get(i);
            JSONObject json = (JSONObject) JSONObject.toJSON(ob);
            if (!StrUtil.isEmpty(json.getString("value"))) {
                String to_param = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                        + "." + json.getString("code");
                itemMap.put(to_param, json.getString("value"));
            }
        }
        logServer.deviceExecuteLog(device_code, "", "", "下发电气信号:" + itemMap);
        this.control(itemMap);
    }

    @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.getAction() == 0) {
            action = "禁止取放";
        } else if (this.getAction() == 1) {
            action = "允许取货";
        } else if (this.getAction() == 2) {
            action = "允许放货";
        } else if (this.getAction() == 3) {
            action = "允许取放";
        }
        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);
        }
        jo.put("device_name", this.getDevice().getDevice_name());
        jo.put("driver_type", "standard_conveyor_control_with_scanner");
        jo.put("mode", mode);
        jo.put("move", move);
        jo.put("action", action);
        jo.put("is_click", true);
        jo.put("isOnline", this.getIsonline());
        jo.put("error", this.getError());
        jo.put("isError", this.getIserror());
        jo.put("message", this.getMessage());
        jo.put("inst_message", this.inst_message);
        jo.put("task", this.getTask());
        jo.put("barcode", plcbarcode);
        jo.put("barcode_length", plcbarcode_length);
        String requireSucess = "0";
        if (this.requireSucess) {
            requireSucess = "1";
        }
        jo.put("requireSucess", requireSucess);
        String applySucess = "0";
        if (this.applySucess) {
            applySucess = "1";
        }
        jo.put("applySucess", applySucess);

        return jo;
    }

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

}
