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

import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nl.acs.agv.server.AgvService;
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.log.service.DeviceExecuteLogService;
import org.nl.acs.monitor.DeviceStageMonitor;
import org.nl.acs.opc.DeviceAppService;
import org.nl.acs.route.service.RouteLineService;
import org.nl.acs.task.service.TaskService;
import org.nl.system.service.param.ISysParamService;
import org.nl.config.SpringContextHolder;
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 EmptyVehicleStackingPositionDeviceDriver 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(InstructionService.class);
    @Autowired
    DeviceService deviceservice = SpringContextHolder.getBean(DeviceService.class);
    @Autowired
    TaskService taskserver = SpringContextHolder.getBean(TaskService.class);
    @Autowired
    RouteLineService routeLineService = SpringContextHolder.getBean(RouteLineService.class);
    @Autowired
    AcsToWmsService acsToWmsService = SpringContextHolder.getBean(AcsToWmsServiceImpl.class);
    @Autowired
    ISysParamService paramService = SpringContextHolder.getBean(ISysParamService.class);
    @Autowired
    DeviceExecuteLogService logServer = SpringContextHolder.getBean(DeviceExecuteLogService.class);
    @Autowired
    AgvService agvService = SpringContextHolder.getBean(AgvService.class);

    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;

    int heartbeat = 0;
    int mode = 0;
    int move = 0;
    int error = 0;
    int number = 0;
    int container_type = 0;
    int task = 0;

    Boolean isonline = true;

    Boolean iserror = false;

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

    int last_mode = 0;
    int last_move = 0;
    int last_error = 0;

    String device_code;

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

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

    @Override
    public void execute() {
        String message = null;

        device_code = this.getDeviceCode();
        heartbeat = this.itemProtocol.getItem_heartbeat();
        mode = this.itemProtocol.getItem_mode();
        move = this.itemProtocol.getItem_mode();
        error = this.itemProtocol.getItem_error();
        number = this.itemProtocol.getItem_number();
        container_type = this.itemProtocol.getItem_container_type();
        task = this.itemProtocol.getItem_task();


        if (mode != last_mode) {
            this.setRequireSucess(false);
        }
        if (move != last_move) {
            if (move == 0) {
                thingToNothing();
            }
        }
        if (error != last_error) {
        }


        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 (flag) {
                //取货完成
                case 1:
                    writing(2);
                    break;
                //放货完成
                case 2:
                    writing(3);
                    break;

            }
        }

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


    public synchronized boolean instruction_apply(String container_code) throws Exception {
        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;
            requireSucess = true;
            return true;
        }
    }

    protected void thingToNothing() {

    }

    public void writing(int command) {
        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 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(String key, String value) {
        String to_command = this.getDevice().getOpc_server_code() + "." + this.getDevice().getOpc_plc_code() + "." + this.getDevice().getDevice_code()
                + "." + key;
        //String opcservcerid = this.getDevice().getOpc_server_id();
//Server server = ReadUtil.getServer(opcservcerid);
        Map<String, Object> itemMap = new HashMap<String, Object>();
        itemMap.put(to_command, value);
        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.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) {

    }
}
