package com.szpg.rmi;

import com.szpg.db.dao.PgDeviceDao;
import com.szpg.db.dao.PgJgDao;
import com.szpg.db.dao.impl.PgDeviceDaoImpl;
import com.szpg.db.dao.impl.PgJgDaoImpl;
import com.szpg.db.data.PgJgStat;
import com.szpg.plc.message.command.write.SetJgLockBitCommand;
import com.szpg.plc.message.command.write.SetJgOffBitCommand;
import com.szpg.plc.message.command.write.SetJgOnBitCommand;
import com.szpg.service.RemoteDeviceControlService;
import com.szpg.service.command.ElectronicWellCommandService;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;
import com.szpg.db.dao.PgAcuDao;
import com.szpg.db.dao.PgHjsbblDao;
import com.szpg.db.dao.impl.PgAcuDaoImpl;
import com.szpg.db.dao.impl.PgHjsbblDaoImpl;
import com.szpg.db.data.PgAcu;
import com.szpg.db.data.PgHjsbbl;
import com.szpg.plc.message.AppMessageConstants;
import com.szpg.plc.message.command.ReadMemoryCommand;
import com.szpg.plc.message.command.write.SetJgUnlockBitCommand;
import com.szpg.plc.protocol.DTProtocolInterface;
import com.szpg.plc.protocol.ProtocolFactory;
import com.szpg.plc.protocol.fins.FINSConstants;
import com.szpg.plc.server.ACUClient;
import com.szpg.plc.server.ACUClientUtil;
import com.szpg.plc.util.ByteUtil;
import com.szpg.service.ReadControllerStatusService;
import com.szpg.util.Configure;
import com.szpg.util.HttpRequest;
import com.szpg.util.UnicodeConvertor;

import z.json.JSONObject;

public class RemoteJGCommandAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2221187086461756012L;

	private String zcbh;
	
	private String format;
	private String jsoncallback;
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	public String getZcbh() {
		return zcbh;
	}

	public void setZcbh(String zcbh) {
		this.zcbh = zcbh;
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public String getJsoncallback() {
		return jsoncallback;
	}

	public void setJsoncallback(String jsoncallback) {
		this.jsoncallback = jsoncallback;
	}
	
	/**
	 * 读取井盖实时状态
	 * @return
	 * @throws Exception
	 */
	public String readJgStatus() throws Exception {
		// 返回结果
		JSONObject jResult = new JSONObject();
		
		PgAcuDao acuDao = new PgAcuDaoImpl();
		
		if (null == zcbh || zcbh.equals("") == true) {
			jResult.put("success", false);
			jResult.put("code", "1");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("资产编号为空"));
			
			returnToFront(jResult);
			return null;
		}
		
		String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
		PgAcu acu = acuDao.findACUByCode(acucode);
		if (null == acu) {
			jResult.put("success", false);
			jResult.put("code", "2");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("未找到资产对应的PLC主机"));
			
			returnToFront(jResult);
			return null;
		}
		
		ACUClient client = ACUClientUtil.getInstance().getClients().get(acu.getAcu_host() + ":" + acu.getAcu_port());
		if (null != client) {
			ReadMemoryCommand command = ReadMemoryCommand.getInstance(AppMessageConstants.CMD_TYPE_READJGSTATUS);
			String sour = Configure.getProperty("sys", "LOCALHOST.NET") + 
						  Configure.getProperty("sys", "LOCALHOST.NODE") + 
						  Configure.getProperty("sys", "LOCALHOST.UNIT");
			command.setMessageProducerId(sour);
			command.setMessageProducerHost(client.getHost());
			
			String dest = client.getNet() + client.getNode() + client.getUnit();
			command.setDestinationId(dest);
			command.setMemoryArea(FINSConstants.MEMORY_WORK_AREA_WORD); //按字读取内容
			
			try {
				// 设置读取的地址范围
				// 从配置文件读取而来
				command.setStartAddress(ByteUtil.binToHexString(ByteUtil.intToBins(Integer.parseInt(Configure.getProperty("acubl", client.getAcucode() + ".JGSTAT.START")), 2)) + "00");
				command.setCountWord(Integer.parseInt(Configure.getProperty("acubl", client.getAcucode() + ".JGSTAT.WORDCOUNT")));
				
				// 调用服务过程执行命令发送服务
				ReadControllerStatusService service = new ReadControllerStatusService();
				service.executeService(client, command);
				logger.info(command);
			} catch (Exception ex) {
				logger.error("发送查询井盖指令异常" + ex);
			}
			
			jResult.put("success", true);
			jResult.put("resaon", UnicodeConvertor.string2Unicode("发送成功，请等待响应"));
			
			returnToFront(jResult);
			return null;
		} else {
			jResult.put("success", false);
			jResult.put("code", "3");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("PLC主机不在线"));
			
			returnToFront(jResult);
			return null;
		}
	}
	
	/**
	 * 远程解锁井盖
	 * @return
	 * @throws Exception
	 */
	public String unlockJg() throws Exception {
		// 返回结果
		JSONObject jResult = new JSONObject();
		
		if (null == zcbh || zcbh.equals("") == true) {
			jResult.put("success", false);
			jResult.put("code", "1");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("资产编号为空"));
			
			returnToFront(jResult);
			return null;
		}
		
		// 查找ACU的信息
		PgAcuDao acuDao = new PgAcuDaoImpl();
		
		String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
		PgAcu acu = acuDao.findACUByCode(acucode);
		if (null == acu) {
			jResult.put("success", false);
			jResult.put("code", "2");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("未找到资产对应的PLC主机"));
			
			returnToFront(jResult);
			return null;
		}
		
		ACUClient client = ACUClientUtil.getInstance().getClients().get(acu.getAcu_host() + ":" + acu.getAcu_port());
		if (null != client) {
			// 源地址
			String sour = Configure.getProperty("sys", "LOCALHOST.NET") + 
						  Configure.getProperty("sys", "LOCALHOST.NODE") + 
						  Configure.getProperty("sys", "LOCALHOST.UNIT");
			
			// 目标地址
			String dest = client.getNet() + client.getNode() + client.getUnit();
			
			// 发送设置解锁位的命令
			SetJgUnlockBitCommand setUnlockCmd = ElectronicWellCommandService.buildUnlockCommand(sour, dest, zcbh);
			if (null != setUnlockCmd) {
				setUnlockCmd.setMessageProducerHost(client.getHost());

				RemoteDeviceControlService service = new RemoteDeviceControlService();
				service.executeService(client, setUnlockCmd, zcbh);

				Logger.getLogger(this.getClass().getName()).info(setUnlockCmd);
			} else {
				jResult.put("success", false);
				jResult.put("code", "4");
				jResult.put("reason", UnicodeConvertor.string2Unicode("未找到资产对应的解锁井盖变量"));
				
				returnToFront(jResult);
				return null;
			}
			
			// 5秒后查询一次井盖的状态
			Thread.sleep(5 * 1000);
			// 调用远程接口查询井盖状态
			String baseURL = Configure.getProperty("sys", "PGDSC_API_URL");
			HttpRequest.sendGet(baseURL + "remote/readJgStatus.action", "zcbh=" + zcbh);
			
			// 成功返回
			jResult.put("success", true);
			jResult.put("code", "0");
			
			returnToFront(jResult);
			return null;
		} else {
			jResult.put("success", false);
			jResult.put("code", "3");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("PLC主机不在线"));
			
			returnToFront(jResult);
			return null;
		}
	}
	
	/**
	 * 远程锁定井盖
	 * @return
	 * @throws Exception
	 */
	public String lockJg() throws Exception {
		// 返回结果
		JSONObject jResult = new JSONObject();
		
		if (null == zcbh || zcbh.equals("") == true) {
			jResult.put("success", false);
			jResult.put("code", "1");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("资产编号为空"));
			
			returnToFront(jResult);
			return null;
		}
		
		// 查找ACU的信息
		PgAcuDao acuDao = new PgAcuDaoImpl();
		
		String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
		PgAcu acu = acuDao.findACUByCode(acucode);
		if (null == acu) {
			jResult.put("success", false);
			jResult.put("code", "2");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("未找到资产对应的PLC主机"));
			
			returnToFront(jResult);
			return null;
		}
		
		ACUClient client = ACUClientUtil.getInstance().getClients().get(acu.getAcu_host() + ":" + acu.getAcu_port());
		if (null != client) {
			// 源地址
			String sour = Configure.getProperty("sys", "LOCALHOST.NET") + 
						  Configure.getProperty("sys", "LOCALHOST.NODE") + 
						  Configure.getProperty("sys", "LOCALHOST.UNIT");
			
			// 目标地址
			String dest = client.getNet() + client.getNode() + client.getUnit();
			
			SetJgLockBitCommand setLockCmd = ElectronicWellCommandService.buildLockCommand(sour, dest, zcbh);
			if (null != setLockCmd) {
				setLockCmd.setMessageProducerHost(client.getHost());

				RemoteDeviceControlService service = new RemoteDeviceControlService();
				service.executeService(client, setLockCmd, zcbh);

				Logger.getLogger(this.getClass().getName()).info(setLockCmd);
			} else {
				jResult.put("success", false);
				jResult.put("code", "4");
				jResult.put("reason", UnicodeConvertor.string2Unicode("未找到资产对应的锁定井盖变量"));
				
				returnToFront(jResult);
				return null;
			}
			
			// 5秒后查询一次井盖的状态
			Thread.sleep(5 * 1000);
			// 调用远程接口查询井盖状态
			String baseURL = Configure.getProperty("sys", "PGDSC_API_URL");
			HttpRequest.sendGet(baseURL + "remote/readJgStatus.action", "zcbh=" + zcbh);
			
			// 成功返回
			jResult.put("success", true);
			jResult.put("code", "0");
			
			returnToFront(jResult);
			return null;
		} else {
			jResult.put("success", false);
			jResult.put("code", "3");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("PLC主机不在线"));
			
			returnToFront(jResult);
			return null;
		}
	}


	/**
	 * 远程打开井盖
	 * @return
	 * @throws Exception
	 */
	public String openJg() throws Exception {
		// 返回结果
		JSONObject jResult = new JSONObject();

		if (null == zcbh || zcbh.equals("") == true) {
			jResult.put("success", false);
			jResult.put("code", "1");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("资产编号为空"));

			returnToFront(jResult);
			return null;
		}

		// 查找ACU的信息
		PgAcuDao acuDao = new PgAcuDaoImpl();

		String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
		PgAcu acu = acuDao.findACUByCode(acucode);
		if (null == acu) {
			jResult.put("success", false);
			jResult.put("code", "2");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("未找到资产对应的PLC主机"));

			returnToFront(jResult);
			return null;
		}

		ACUClient client = ACUClientUtil.getInstance().getClients().get(acu.getAcu_host() + ":" + acu.getAcu_port());
		if (null != client) {
			// 源地址
			String sour = Configure.getProperty("sys", "LOCALHOST.NET") +
					Configure.getProperty("sys", "LOCALHOST.NODE") +
					Configure.getProperty("sys", "LOCALHOST.UNIT");

			// 目标地址
			String dest = client.getNet() + client.getNode() + client.getUnit();

			// 2 发送设置启动位的命令
			// 构建打开井盖指令
			SetJgOnBitCommand setOnCmd = ElectronicWellCommandService.buildTurnOnCommand(sour, dest, zcbh);
			if (null != setOnCmd) {
				setOnCmd.setMessageProducerHost(client.getHost());

				RemoteDeviceControlService service = new RemoteDeviceControlService();
				service.executeService(client, setOnCmd, zcbh);

				Logger.getLogger(this.getClass().getName()).info(setOnCmd);
			} else {
				jResult.put("success", false);
				jResult.put("code", "4");
				jResult.put("reason", UnicodeConvertor.string2Unicode("未找到资产对应的打开井盖变量"));

				returnToFront(jResult);
				return null;
			}

			// 返回成功给界面
			jResult.put("success", true);
			jResult.put("code", "0");
			returnToFront(jResult);

			return null;
		} else {
			jResult.put("success", false);
			jResult.put("code", "3");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("PLC主机不在线"));

			returnToFront(jResult);
			return null;
		}
	}


	/**
	 * 远程关闭井盖
	 * @return
	 * @throws Exception
	 */
	public String closeJg() throws Exception {
		// 返回结果
		JSONObject jResult = new JSONObject();

		if (null == zcbh || zcbh.equals("") == true) {
			jResult.put("success", false);
			jResult.put("code", "1");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("资产编号为空"));

			returnToFront(jResult);
			return null;
		}

		// 查找ACU的信息
		PgAcuDao acuDao = new PgAcuDaoImpl();

		String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
		PgAcu acu = acuDao.findACUByCode(acucode);
		if (null == acu) {
			jResult.put("success", false);
			jResult.put("code", "2");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("未找到资产对应的PLC主机"));

			returnToFront(jResult);
			return null;
		}

		ACUClient client = ACUClientUtil.getInstance().getClients().get(acu.getAcu_host() + ":" + acu.getAcu_port());
		if (null != client) {
			// 源地址
			String sour = Configure.getProperty("sys", "LOCALHOST.NET") +
					Configure.getProperty("sys", "LOCALHOST.NODE") +
					Configure.getProperty("sys", "LOCALHOST.UNIT");

			// 目标地址
			String dest = client.getNet() + client.getNode() + client.getUnit();

			// 2 发送设置停止位的命令
			SetJgOffBitCommand setOffCmd = ElectronicWellCommandService.buildTurnOffCommand(sour, dest, zcbh);
			if (null != setOffCmd) {
				setOffCmd.setMessageProducerHost(client.getHost());

				RemoteDeviceControlService service = new RemoteDeviceControlService();
				service.executeService(client, setOffCmd, zcbh);

				Logger.getLogger(this.getClass().getName()).info(setOffCmd);
			} else {
				jResult.put("success", false);
				jResult.put("code", "4");
				jResult.put("reason", UnicodeConvertor.string2Unicode("未找到资产对应的关闭井盖变量"));

				returnToFront(jResult);
				return null;
			}

			// 返回成功给界面
			jResult.put("success", true);
			jResult.put("code", "0");
			returnToFront(jResult);

			return null;
		} else {
			jResult.put("success", false);
			jResult.put("code", "3");
			jResult.put("resaon", UnicodeConvertor.string2Unicode("PLC主机不在线"));

			returnToFront(jResult);
			return null;
		}
	}


	public String readJgStatusFromDB() throws Exception {
		// 返回结果
		JSONObject jResult = new JSONObject();

		PgDeviceDao deviceDao = new PgDeviceDaoImpl();
		PgJgDao jgDao = new PgJgDaoImpl();

		int deviceId = deviceDao.findDeviceIdByCode(zcbh);
		if (deviceId > 0) {
			PgJgStat jgStat = jgDao.findLatestStatByDevice(deviceId);
			if (null != jgStat) {
				jResult.put("jgStat", jgStat.toJson());
			}
		}

		returnToFront(jResult);
		return null;
	}
	
	/**
	 * 给前端返回
	 * @param jResult
	 * @throws Exception
	 */
	private void returnToFront(JSONObject jResult) throws Exception {
		// 返回jsonp格式的数据
		if (null != format && format.equalsIgnoreCase("jsonp") == true) {
			ServletActionContext.getResponse().getWriter().write(jsoncallback + "(" + jResult.toString() + ");");
		}

		ServletActionContext.getResponse().getWriter().write(jResult.toString());
	}
}
