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

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_driver.RequestMethodEnum;
import org.nl.acs.ext.wms.data.feedBackTaskStatus.FeedBackTaskStatusRequest;
import org.nl.acs.ext.wms.service.AcsToWmsService;
import org.nl.acs.utils.ReadUtil;
import org.nl.acs.device.service.DeviceService;
import org.nl.acs.device_driver.DeviceDriver;
import org.nl.acs.device_driver.driver.AbstractOpcDeviceDriver;
import org.nl.acs.device_driver.driver.ExecutableDeviceDriver;
import org.nl.acs.instruction.service.InstructionService;
import org.nl.acs.route.service.RouteLineService;
import org.nl.acs.task.service.TaskService;
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.Map;

/**
 * 自动门驱动
 */
@Slf4j
@Data
@RequiredArgsConstructor
public class StandardAutodoorDeviceDriver extends AbstractOpcDeviceDriver implements DeviceDriver, ExecutableDeviceDriver {
    protected ItemProtocol itemProtocol = new ItemProtocol(this);

    InstructionService instructionService = SpringContextHolder.getBean("instructionServiceImpl");

    DeviceService deviceservice = SpringContextHolder.getBean("deviceServiceImpl");

    RouteLineService routelineserver = SpringContextHolder.getBean("routeLineServiceImpl");

    TaskService taskserver = SpringContextHolder.getBean("taskServiceImpl");

    AcsToWmsService acsToWmsService=SpringContextHolder.getBean("acsToWmsServiceImpl");
    String container;
    String container_type_desc;
    String last_container_type_desc;
    String last_container;
    //放货准备锁
    String putReadyLock = null;
    //有货标记
    protected boolean has_goods_tag = false;
    String devicecode;
    int mode = 0;
    int action = 0;
    int error = 0;
    Boolean iserror = false;

    int move = 0;
    int task = 0;
    int state = 0;
    int last_state = 0;
    int last_action = 0;
    int last_mode = 0;
    int last_error = 0;
    int last_move = 0;
    int last_task = 0;

    boolean hasVehicle = false;
    boolean isReady = false;
    protected int instruction_num = 0;
    protected int instruction_num_truth = 0;
    protected boolean hasGoods = false;
    boolean isFold = false;
    private String assemble_check_tag;
    private Boolean sampleMode0;
    private Boolean sampleMode3;
    private Integer sampleError;
    private Boolean sampleOnline;
    protected String displayMessage = null;
    public int display_message_time_out = 30000;
    public Date display_message_time;
    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 int instruction_require_time_out;
    boolean requireSucess = false;

    private int instruction_finished_time_out;

    int branchProtocol = 0;

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


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

        String device_code = this.getDevice().getDevice_code();
        mode = this.itemProtocol.getMode();
        action = this.itemProtocol.getAction();
        error = this.itemProtocol.getError();
        if (mode != last_mode) {
        }
        if (action != last_action) {
        }
        if (error != last_error) {
        }
        if (state != last_state) {
            //固化室状态变更后通知lms更新固化室状态
            FeedBackTaskStatusRequest request = new FeedBackTaskStatusRequest();
            request.setState(String.valueOf(state));
            request.setDevice_code(this.devicecode);
            request.setType("1");
            acsToWmsService.notify(request);
        }
        last_action = action;
        last_mode = mode;
        last_error = error;
        last_state = state;
        //message = StringFormatUtl.format("设备报警:{}", new Object[]{});
        // String manual_create_task = this.getDevice().getExtraValue().get("manual_create_task").toString();
    }

    public synchronized String getStatus() {
        JSONObject jo = new JSONObject();

        if (action == 1) {
            jo.put("name", this.getDevice().getDevice_code());
            jo.put("status", "OPEN");

        } else if (action == 2) {
            jo.put("name", this.getDevice().getDevice_code());
            jo.put("status", "CLOSE");

        } else {
            jo.put("name", this.getDevice().getDevice_code());
            jo.put("status", "ERROR");
        }
        return jo.toString();
    }


    public void writing(String param,int command) {
        String to_command = String.format("%s.%s.%s.%s", 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_command, command);
        ReadUtil.write(itemMap, server);
        log.info("下发PLC信号：{},{}", to_command, command);
        System.out.println("设备：" + devicecode + ",下发PLC信号：" + to_command + ",value:" + command);

    }

    public synchronized void OpenOrClose(String type) {

        //开门
        if ("1".equals(type)) {
            writing(ItemProtocol.item_to_command,1);
        } else {
            writing(ItemProtocol.item_to_command,2);
        }

    }

}
