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

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

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.szpg.db.dao.PgAlarmDao;
import com.szpg.db.dao.PgAlarmRuleDao;
import com.szpg.db.dao.PgDeviceDao;
import com.szpg.db.dao.PgO2Dao;
import com.szpg.db.dao.impl.PgAlarmDaoImpl;
import com.szpg.db.dao.impl.PgAlarmRuleDaoImpl;
import com.szpg.db.dao.impl.PgDeviceDaoImpl;
import com.szpg.db.dao.impl.PgO2DaoImpl;
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.Configure;
import com.szpg.util.DataPushInterface;
import com.szpg.util.HttpRequest;
import com.szpg.util.NumberFormat;
import com.szpg.util.TimeFormat;

public class ReadO2ValueCommandResponse extends ReadMemoryCommandResponse {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2816512676498637196L;

	private final Logger logger = Logger.getLogger(this.getClass().getName());
	
	private List<Float> o2nd; // 氧气浓度值
	private List<Float> o2ldbjz; // 氧气联动报警值
	private String[] zcList; // 氧气监测设备资产列表，从配置文件中获取

	public ReadO2ValueCommandResponse() {
		o2nd = new ArrayList<Float>();
		o2ldbjz = new ArrayList<Float>();
	}

	public List<Float> getO2nd() {
		return o2nd;
	}

	public void setO2nd(List<Float> o2nd) {
		this.o2nd = o2nd;
	}

	public List<Float> getO2ldbjz() {
		return o2ldbjz;
	}

	public void setO2ldbjz(List<Float> o2ldbjz) {
		this.o2ldbjz = o2ldbjz;
	}
	
	public String[] getZcList() {
		return zcList;
	}

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

	@Override
	public void afterAction() {
		// 1将氧气浓度数据存入数据库
		PgO2Dao o2Dao = new PgO2DaoImpl();
		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];
				
				float value = o2nd.get(i);
				
				int deviceId = deviceDao.findDeviceIdByCode(zcbh);
				if (deviceId > 0) {
					o2Dao.addPblzRecord(o2nd.get(i), TimeFormat.formatTimestamp(this.getTime().getTime()), deviceId);
					
					// (一)如果有报警则立即推送
					// 判断是否超过报警阈值
					PgAlarmRule rule = ruleDao.findRuleByDevice(deviceId);
					if (null != rule) {
						double low = 0.0;
						try {
							low = NumberFormat.parseDouble(rule.getLowvalue(), "0.00");
						} catch (Exception ex) {
							logger.error(ex);
							ex.printStackTrace();
						}
						
						// 氧气浓度低于低限阈值
						if (low > 0.0001 && value < low) {
							PgAlarm alarm = new PgAlarm();
							alarm.setActive(1);
							alarm.setAlarm_date(this.getTime().getTime());
							alarm.setAlarm_value(NumberFormat.format(value, "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() + "，氧气浓度值为" + value;
							String bjsj = date.replace("-", "");
							String jwbjResp = DataPushInterface.addO2AlarmData(bjbh, zcbh, bjms, bjsj);
							logger.info("同步氧气报警记录日志结果：" + jwbjResp);
							
							// 将报警值推送至市级平台
							String jwResp = DataPushInterface.addO2Data(zcbh, NumberFormat.format(value, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
							logger.info("同步氧气浓度值结果：" + jwResp);
							
							// 自动打开当前舱段的排风机，手动关闭风机
							// 首先找到当前舱段的排风机资产编号
							if (Boolean.valueOf(Configure.getProperty("sys", "O2_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 = o2Dao.findLastValueByDevice(deviceId);
					if (Math.abs(value - lastValue) > 0.01) {
						// 将监测值推送至市级平台
						String o2Resp = DataPushInterface.addO2Data(zcbh, NumberFormat.format(value, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
						logger.info("同步氧气浓度值结果：" + o2Resp);
					}
					
					// (三)如果监测值有变化则推送
					// 每天小时各推送一个数据
					int minute = Calendar.getInstance().get(Calendar.MINUTE);
					if (minute < 10) {
						// 将监测值推送至市级平台
						String o2Resp = DataPushInterface.addO2Data(zcbh, NumberFormat.format(value, "0.00"), TimeFormat.format(this.getTime().getTime(), "yyyyMMddHHmmss"));
						logger.info("同步氧气浓度值结果：" + o2Resp);
					}
				} 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 + ".YQ.WORDCOUNT")) * 2) {
			logger.error("返回的数据长度与读取的不一致！");
			this.setValid(false);
			return;
		}
		
		// 获取目标ACU氧气监测值内存区域的起始字地址
		int start = Integer.parseInt(Configure.getProperty("acubl", acucode + ".YQ.START"));
		
		// 获取目标ACU氧气相关的资产列表，即氧气设备列表
		String zcListStr = Configure.getProperty("acubl", acucode + ".YQ.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];
			
			// 1解析氧气浓度监测值
			float value = getValueFromData(zcbh, start, messageData, zcbh + ".Value");
			
			// 2解析氧气浓度报警阈值
			float threshold = getValueFromData(zcbh, start, messageData, zcbh + ".Set");
			
			getO2nd().add(value);
			getO2ldbjz().add(threshold);
			
			logger.info("[" + zcbh + "][氧气浓度值" + value + "][氧气浓度报警阈值" + threshold + "]");
		}
		
		logger.info("解析[读取氧气浓度值]响应指令结束");
	}

}
