package com.szpg.plc.message.response.read;

import com.szpg.db.dao.*;
import com.szpg.db.dao.impl.*;
import com.szpg.db.data.PgAlarm;
import com.szpg.db.data.PgAlarmRule;
import com.szpg.db.data.PgDevice;
import com.szpg.plc.message.response.ReadMemoryCommandResponse;
import com.szpg.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 解析二期硫化氢及甲烷实时值响应
 * @author admin
 *
 */
public class ReadHSCH4ValueCommandResponse extends ReadMemoryCommandResponse {

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

	private final Logger logger = Logger.getLogger(this.getClass().getName());

	private List<Float> hs; //硫化氢监测值
	private List<Float> ch4; //甲烷监测值
	private String[] zcList; //温湿度监测的资产列表，从配置文件中获取

	public ReadHSCH4ValueCommandResponse() {
		hs = new ArrayList<Float>();
		ch4 = new ArrayList<Float>();
	}

	public List<Float> getHs() {
		return hs;
	}

	public void setHs(List<Float> hs) {
		this.hs = hs;
	}

	public List<Float> getCh4() {
		return ch4;
	}

	public void setCh4(List<Float> ch4) {
		this.ch4 = ch4;
	}

	public String[] getZcList() {
		return zcList;
	}

	public void setZcList(String[] zcList) {
		this.zcList = zcList;
	}

	@Override
	public void afterAction() {
		// 1将硫化氢监测值数据存入数据库
		PgHSDao hsDao = new PgHSDaoImpl();
		PgCh4Dao ch4Dao = new PgCh4DaoImpl();
		PgDeviceDao deviceDao = new PgDeviceDaoImpl();
		PgAlarmRuleDao ruleDao = new PgAlarmRuleDaoImpl();
		PgAlarmDao alarmDao = new PgAlarmDaoImpl();
		
		if (null != zcList && zcList.length > 0) {
			// 遍历硫化氢设备列表，将硫化氢浓度监测值存入数据库
			for (int i = 0; i < zcList.length; i++) {
				String zcbh = zcList[i];
				
				int deviceId = deviceDao.findDeviceIdByCode(zcbh);
				if (deviceId > 0) {
					// 硫化氢监测仪的后续操作
					if (zcbh.indexOf("HS") >= 0) {
						if (hs.get(i) != null) {
							float hsValue = hs.get(i);
							
							try {
								hsDao.addPblzRecord(hsValue, TimeFormat.formatTimestamp(this.getTime().getTime()), deviceId);
							} catch (Exception ex) {
								logger.error("添加硫化氢监测记录异常");
							}
							
							// (一)如果有报警则立即推送
							// 判断是否超过报警阈值
							PgAlarmRule rule = ruleDao.findRuleByDevice(deviceId);
							if (null != rule) {
								double high = 0.0;
								try {
									high = NumberFormat.parseDouble(rule.getHighvalue(), "0.00");
								} catch (Exception ex) {
									logger.error(ex);
									ex.printStackTrace();
								}
								
								// 硫化氢超过高限阈值
								if (high > 0.0001 && hsValue > high) {
									PgAlarm alarm = new PgAlarm();
									alarm.setActive(1);
									alarm.setAlarm_date(this.getTime().getTime());
									alarm.setAlarm_value(NumberFormat.format(hsValue, "0.00"));
									alarm.setAlarmdevid(deviceId);
									alarm.setAlarmtypeid(PgAlarm.ALARM_TYPE_PGRUN);
									alarm.setDescription("硫化氢浓度超过高限阈值");
									alarm.setUserid(null);

									alarmDao.insertAlarmRecord(alarm);

									// 将报警日志推送至市级平台
									String date = TimeFormat.formatDate(getTime().getTime());
									int count = alarmDao.findAlarmCountByDate(date);
									String bjbh = "THXC." + date + "." + NumberFormat.format(count+1, "0000");
									String bjms = alarm.getDescription() + "，硫化氢浓度值为" + hsValue;
									String bjsj = date.replace("-", "");
									String jwbjResp = DataPushInterface.addHSAlarmData(bjbh, zcbh, bjms, bjsj);
									logger.info("同步硫化氢报警记录日志结果：" + jwbjResp);

									// 将报警值推送至市级平台
									String jwResp = DataPushInterface.addHSData(zcbh, NumberFormat.format(hsValue, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
									logger.info("同步硫化氢浓度值结果：" + jwResp);

									// 自动打开当前舱段的排风机，手动关闭风机
									// 首先找到当前舱段的排风机资产编号
									if (Boolean.valueOf(Configure.getProperty("sys", "HS_ON_FJ", "false")) == true) {
										String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
										String cabin = zcbh.substring(zcbh.lastIndexOf(".") + 1, zcbh.lastIndexOf(".") + 2);
										List<PgDevice> fjs = deviceDao.findDeviceByPositionAndType(acucode, "F", cabin);
										if (null != fjs && fjs.isEmpty() == false) {
											String baseURL = Configure.getProperty("sys", "PGDSC_API_URL");
											for (PgDevice fj : fjs) {
												String fjzcbh = fj.getAssetcode();

												// 调用远程接口启动风机
												HttpRequest.sendGet(baseURL + "remote/turnOnFj.action", "zcbh=" + fjzcbh);
											}
										}
									}
								}
							}
							/*
							// (二)如果监测值有变化则推送
							// 判断硫化氢浓度值是否有变化
							double lastValue = hsDao.findLastValueByDevice(deviceId);
							if (Math.abs(hsValue - lastValue) > 0.01) {
								// 将监测值推送至市级平台
								String coResp = DataPushInterface.addHSData(zcbh, NumberFormat.format(hsValue, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
								logger.info("同步硫化氢浓度值结果：" + coResp);
							}

							// (三)如果监测值没有变化
							// 每天小时各推送一个数据
							int minute = Calendar.getInstance().get(Calendar.MINUTE);
							if (minute < 10) {
								// 将监测值推送至市级平台
								String coResp = DataPushInterface.addHSData(zcbh, NumberFormat.format(hsValue, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
								logger.info("同步硫化氢浓度值结果：" + coResp);
							}
							*/
						}
					} else if (zcbh.indexOf("CH") >= 0) {
						if (null != ch4.get(i)) {
							float ch4Value = ch4.get(i);
							
							try {
								ch4Dao.addPblzRecord(ch4Value, TimeFormat.formatTimestamp(this.getTime().getTime()), deviceId);
							} catch (Exception ex) {
								logger.error("添加甲烷监测记录异常");
							}
							
							// (一)如果有报警则立即推送
							// 判断是否超过报警阈值
							PgAlarmRule rule = ruleDao.findRuleByDevice(deviceId);
							if (null != rule) {
								double high = 0.0;
								try {
									high = NumberFormat.parseDouble(rule.getHighvalue(), "0.00");
								} catch (Exception ex) {
									logger.error(ex);
									ex.printStackTrace();
								}

								// 甲烷浓度超过高限阈值
								if (high > 0.0001 && ch4Value > high) {
									PgAlarm alarm = new PgAlarm();
									alarm.setActive(1);
									alarm.setAlarm_date(this.getTime().getTime());
									alarm.setAlarm_value(NumberFormat.format(ch4Value, "0.00"));
									alarm.setAlarmdevid(deviceId);
									alarm.setAlarmtypeid(PgAlarm.ALARM_TYPE_PGRUN);
									alarm.setDescription("甲烷浓度超过高限阈值");
									alarm.setUserid(null);

									alarmDao.insertAlarmRecord(alarm);
									
									// 将报警日志推送至市级平台
									String date = TimeFormat.formatDate(getTime().getTime());
									int count = alarmDao.findAlarmCountByDate(date);
									String bjbh = "THXC." + date + "." + NumberFormat.format(count+1, "0000");
									String bjms = alarm.getDescription() + "，甲烷浓度值为" + ch4Value;
									String bjsj = date.replace("-", "");
									String jwbjResp = DataPushInterface.addCH4AlarmData(bjbh, zcbh, bjms, bjsj);
									logger.info("同步甲烷报警记录日志结果：" + jwbjResp);
									
									// 将报警值推送至市级平台
									String jwResp = DataPushInterface.addCH4Data(zcbh, NumberFormat.format(ch4Value, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
									logger.info("同步甲烷浓度值结果：" + jwResp);
									
									// 自动打开当前舱段的排风机，手动关闭风机
									// 首先找到当前舱段的排风机资产编号
									if (Boolean.valueOf(Configure.getProperty("sys", "CH4_ON_FJ", "false")) == true) {
										String acucode = zcbh.substring(0, zcbh.indexOf(".", 6));
										String cabin = zcbh.substring(zcbh.lastIndexOf(".") + 1, zcbh.lastIndexOf(".") + 2);
										List<PgDevice> fjs = deviceDao.findDeviceByPositionAndType(acucode, "F", cabin);
										if (null != fjs && fjs.isEmpty() == false) {
											String baseURL = Configure.getProperty("sys", "PGDSC_API_URL");
											for (PgDevice fj : fjs) {
												String fjzcbh = fj.getAssetcode();

												// 调用远程接口启动风机
												HttpRequest.sendGet(baseURL + "remote/turnOnFj.action", "zcbh=" + fjzcbh);
											}
										}
									}
								}
							}
							
							/*
							// (二)如果监测值有变化则推送
							// 判断甲烷浓度值是否有变化
							double lastValue = ch4Dao.findLastValueByDevice(deviceId);
							if (Math.abs(ch4Value - lastValue) > 0.01) {
								// 将监测值推送至市级平台
								String jwResp = DataPushInterface.addCH4Data(zcbh, NumberFormat.format(value, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
								logger.info("同步甲烷浓度值结果：" + jwResp);
							}
							
							// (三)如果监测值有变化则推送
							// 每天小时各推送一个数据
							int minute = Calendar.getInstance().get(Calendar.MINUTE);
							if (minute < 10) {
								// 将监测值推送至市级平台
								String jwResp = DataPushInterface.addCH4Data(zcbh, NumberFormat.format(ch4Value, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
								logger.info("同步甲烷浓度值结果：" + jwResp);
							}
							*/
						}
					}
				} else {
					logger.warn("未找到资产[" + zcbh + "]");
				}
			}
		}
	}

	@Override
	public void parseData() {
		// 获取目标ACU的代码
		String acucode = this.getAcucode();
		byte[] messageData = this.getResponseData();
		
		logger.info("开始解析[读取硫化氢及甲烷值][" + acucode + "]指令响应");
		
		// 判断数据的长度是否满足要求
		if (messageData.length != Integer.parseInt(Configure.getProperty("acubl", acucode + ".HSCH4.WORDCOUNT")) * 2) {
			logger.error("返回的数据长度与读取的不一致！");
			this.setValid(false);
			return;
		}

		// 获取目标ACU硫化氢及甲烷监测值内存区域的起始字地址
		int start = Integer.parseInt(Configure.getProperty("acubl", acucode + ".HSCH4.START"));
		
		// 获取目标ACU硫化氢及甲烷相关的资产列表，即硫化氢设备列表
		String zcListStr = Configure.getProperty("acubl", acucode + ".HSCH4.ZC.LIST");
		if (StringUtils.isEmpty(zcListStr) == true) {
			this.setValid(false);
			return;
		}
		zcList = zcListStr.split(";");
		
		// 解析硫化氢监测值以
		for (int i = 0; i < zcList.length; i++) {
			String zcbh = zcList[i];
			
			if (zcbh.indexOf("HS") >= 0) {
				// 1解析硫化氢监测值
				float valueHS = getValueFromDataSecond(zcbh, start, messageData, zcbh + ".Value");

				getHs().add(valueHS);
				getCh4().add(null); // 硫化氢监测仪没有甲烷值
				logger.info("[" + zcbh + "][硫化氢值" + valueHS + "]");
			} else if (zcbh.indexOf("CH") >= 0) {
				// 3解析甲烷监测值
				float valueCH4 = getValueFromDataSecond(zcbh, start, messageData, zcbh + ".Value");
				
				getCh4().add(valueCH4);
				getHs().add(null); // 甲烷监测仪没有硫化氢值
				logger.info("[" + zcbh + "][甲烷值" + valueCH4 + "]");
			}
		}
		
		logger.info("解析[读取硫化氢及甲烷值]响应指令结束");
	}
 
}
