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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.ext.wms.service.impl.AcsToWmsServiceImpl;
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.common.utils.CodeUtil;
import org.nl.config.SpringContextHolder;
import org.openscada.opc.lib.da.Server;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    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 operation_type = 0;
    int last_mode = 0;
    int last_error = 0;
    int last_move = 0;
    int last_task = 0;

    Boolean isonline = true;
    int hasGoods = 0;
    String message = null;
    Boolean iserror = false;


    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;
    String inst_message;

    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 = 0;

    String device_code;

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


    @Override
    public void execute() {
        String message = null;
        try {
            device_code = this.getDeviceCode();
            mode = this.itemProtocol.getMode();
            error = this.itemProtocol.getError();
            move = this.itemProtocol.getMove();
            task = this.itemProtocol.getTask();
            hasGoods = this.itemProtocol.getMove();
            operation_type = this.itemProtocol.getOperation_type();
            if (mode != last_mode) {
            }
            if (move != last_move) {
                if (move == 0) {
                    thingToNothing();
                }
                this.setRequireSucess(false);

            }
            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(), "1") && StrUtil.equals(this.getDeviceCode(), inst.getNext_device_code())) {
                        finish_instruction();
                    }
                    if (StrUtil.equals(inst.getInstruction_status(), "0") && StrUtil.equals(this.getDeviceCode(), inst.getStart_device_code())) {
                        inst.setInstruction_status("1");
                        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 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 (!StrUtil.isEmpty(material) && !StrUtil.isEmpty(qty) && material.length() > 0 && qty.length() > 0 && !requireSucess) {
                        this.instruction_require(container);
                    }
                    break;
                case 3:

                    break;
                case 4:
                    //叫料

                    break;
                case 5:
                    //申请空盘
                    if (move == 0 && !requireSucess) {
                        apply_OutEmpty();
                    }
                    break;
                case 6:
                    //申请入库
                    if (move != 0 && !applySucess) {
                        instruction_apply();
                    }
                    if (move != 0 && !requireSucess) {
                        apply_InEmpty();
                    }
                    break;
            }


            switch (flag) {
                //取货完成
                case 1:
                    writing(2);
                    break;
                //放货完成
                case 2:
                    writing(3);
                    break;

            }

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

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

    protected void thingToNothing() {
        log.debug("从有货到无货 清理数据");
        this.setRequireSucess(false);
        this.setApplySucess(false);
        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(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 command, int target, int task) {

        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + org.nl.acs.device_driver.basedriver.standard_conveyor_control_with_scanner.ItemProtocol.item_to_command;
        String to_target = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + org.nl.acs.device_driver.basedriver.standard_conveyor_control_with_scanner.ItemProtocol.item_to_target;
        String to_task = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + org.nl.acs.device_driver.basedriver.standard_conveyor_control_with_scanner.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 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_apply() {
        return false;
    }

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

    /**
     * 请求指令
     *
     * @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;
            TaskDto dto = new TaskDto();
            String now = DateUtil.now();
            dto.setTask_id(IdUtil.simpleUUID());
            dto.setCreate_by(this.getDevice().getDevice_code());
            dto.setUpdate_by(this.getDevice().getDevice_code());
            dto.setStart_point_code(this.getDevice().getDevice_code());
            dto.setVehicle_code(container_code);
            dto.setVehicle_type(container_type);

            String taskcode = CodeUtil.getNewCode("TASK_NO");
            dto.setTask_code("-" + taskcode);
            dto.setTask_status("0");
            dto.setPriority("101");
            RouteLineDto jo = routelineserver.findByCode(this.getDevice().getDevice_code());
            String next_device_codecode = jo.getNext_device_code();
            if (StrUtil.isEmpty(next_device_codecode)) {
                throw new RuntimeException("该设备未找到对应路由");
            }
            dto.setNext_point_code(next_device_codecode);
            dto.setUpdate_time(now);
            dto.setCreate_time(now);

//            WQLObject wo = WQLObject.getWQLObject("acs_task");
//             JSONObject json = (JSONObject) JSONObject.toJSON(dto);
//
//            wo.insert(json);
            Task entity = ConvertUtil.convert(dto, Task.class);
            taskMapper.insert(entity);

            requireSucess = false;
            return true;
        }
    }


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

    public void apply_OutEmpty() {

    }

    public synchronized boolean apply_InEmpty(){
        return false;
    }

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

    }
}
