package com.szpg.task;

import java.util.List;

import org.apache.log4j.Logger;

import com.szpg.db.dao.PgAcuDao;
import com.szpg.db.dao.PgAlarmRuleDao;
import com.szpg.db.dao.PgDeviceDao;
import com.szpg.db.dao.PgHjsbblDao;
import com.szpg.db.dao.impl.PgAcuDaoImpl;
import com.szpg.db.dao.impl.PgAlarmRuleDaoImpl;
import com.szpg.db.dao.impl.PgDeviceDaoImpl;
import com.szpg.db.dao.impl.PgHjsbblDaoImpl;
import com.szpg.db.data.PgAcu;
import com.szpg.db.data.PgAlarmRule;
import com.szpg.db.data.PgDevice;
import com.szpg.db.data.PgHjsbbl;
import com.szpg.plc.message.command.write.SetCH4ThresholdWordCommand;
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.plc.util.Bytes;
import com.szpg.service.SetSensorThresholdService;
import com.szpg.util.Configure;
import com.szpg.util.NumberFormat;

/**
 * 设置甲烷报警阈值
 * 
 * @author admin
 *
 */
public class SetCH4ThresholdTask implements Runnable {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private PgHjsbblDao blDao = new PgHjsbblDaoImpl();
	
	public SetCH4ThresholdTask() {
		
	}

	@Override
	public void run() {
		// 1查找所有的甲烷报警阈值
		PgAlarmRuleDao ruleDao = new PgAlarmRuleDaoImpl();
		PgDeviceDao devDao = new PgDeviceDaoImpl();
		PgAcuDao acuDao = new PgAcuDaoImpl();
		
		List<PgAlarmRule> rules = ruleDao.findRuleListByDevtype("甲烷检测仪");
		if (null != rules && rules.isEmpty() == false) {
			logger.info("开始启动校正甲烷浓度报警阈值 定时任务[" + rules.size() + "]");
			
			for (PgAlarmRule rule : rules) {
				int deviceId = rule.getPgdeviceid();
				double high = 0.0;
				try {
					high = NumberFormat.parseDouble(rule.getHighvalue(), "0.00");
				} catch (Exception ex) {
					logger.error(ex);
					ex.printStackTrace();
				}
				
				PgDevice device = devDao.findDeviceById(deviceId);
				if (null != device) {
					String deviceCode = device.getAssetcode();
					String acucode = deviceCode.substring(0, deviceCode.indexOf(".", 6));
					PgAcu acu = acuDao.findACUByCode(acucode);
					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();
						
						DTProtocolInterface finspi = ProtocolFactory.getDefaultDTProtocol();
						
						// 发送设置甲烷浓度报警阈值
						SetCH4ThresholdWordCommand setThreCmd = new SetCH4ThresholdWordCommand();
						setThreCmd.setThreshold((float) high);
						PgHjsbbl tBlObj = blDao.findBlByBh(deviceCode + ".Set");
						if (null != tBlObj) {
							setThreCmd.setMessageProducerId(sour);
							setThreCmd.setMessageProducerHost(client.getHost());
							setThreCmd.setDestinationId(dest);
							
							// SID在new对象的时候已经生成
							
							// 内存区域——按字写
							setThreCmd.setMemoryArea(FINSConstants.MEMORY_WORK_AREA_WORD);
							
							int start = tBlObj.getKszdz();
							int end = tBlObj.getJszdz();
							
							// 开始字地址
							setThreCmd.setStartAddress(ByteUtil.binToHexString(ByteUtil.intToBins(start, 2)) + "00");
							
							// 字数
							int n = end - start + 1;
							setThreCmd.setCount(n);
							
							// 字内容
							Bytes dataByte = SetSensorThresholdService.parseValueToBytes((float) high, n, client.getFlag());
							setThreCmd.setValue( dataByte.toBytes() );
							
							// 解析命令对象为字节数组
							byte[] content = finspi.messageToBytes(setThreCmd);
							
							// 通过socket接口发送出去
							ACUClientUtil.getInstance().sendACUCommand(client, content);
						}
					}
				}
				
				// 每个设备间隔1秒发送
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			logger.info("结束启动校正甲烷报警阈值 定时任务");
		}
	}
}
