package com.szpg.service;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.szpg.db.dao.PgAcuCmdDao;
import com.szpg.db.dao.PgAcuDao;
import com.szpg.db.dao.impl.PgAcuCmdDaoImpl;
import com.szpg.db.dao.impl.PgAcuDaoImpl;
import com.szpg.db.data.PgAcu;
import com.szpg.db.data.PgAcuCmd;
import com.szpg.plc.message.command.WriteMemoryCommand;
import com.szpg.plc.protocol.DTProtocolInterface;
import com.szpg.plc.protocol.ProtocolFactory;
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.util.Configure;

/**
 * 设置环境变量报警阈值的服务过程
 * 
 * @author admin
 *
 */
public class SetSensorThresholdService {
	
	private PgAcuCmdDao cmdDao = new PgAcuCmdDaoImpl();
	private PgAcuDao acuDao = new PgAcuDaoImpl();
	
	public void executeService(ACUClient client, WriteMemoryCommand command) {
		// 解析命令对象为字节数组
		DTProtocolInterface finspi = ProtocolFactory.getDefaultDTProtocol();
		byte[] content = finspi.messageToBytes(command);
		
		// 通过socket接口发送出去
		ACUClientUtil.getInstance().sendACUCommand(client, content);
		
		// 1查找数据库中的ACU对象
		PgAcu acu = acuDao.findACUByHost(client.getHost());
		if (null == acu) {
			return;
		}
		
		// 2生成读取命令对象
		PgAcuCmd cmd = new PgAcuCmd();
		cmd.setCmd_type(command.getCommandType());
		cmd.setDest_acu_code(acu.getAcu_code());
		cmd.setTm(command.getTime().getTime());
		
		// 3将命令保存入数据库
		cmdDao.addCmdRecord(cmd);
		
		// 4定时将数据库中的命令置为超时
		int TIMEOUT = Integer.parseInt(Configure.getProperty("sys", "COMMAND_TIMEOUT", "2"));
		new ScheduledThreadPoolExecutor(1).schedule(new RemoteCommandTimeoutTask(cmd.getId()), TIMEOUT, TimeUnit.MINUTES);
	}
	
	/**
	 * 根据一期二期逻辑不同，返回字节数组
	 * @param value 需要转换的阈值
	 * @param n 所需要转换的字数
	 * @param flag 一期还是二期设备的标志位
	 */
	public static Bytes parseValueToBytes(float value, int n, String flag) {
		Bytes dataByte = new Bytes();
		if (flag.equals("11")) {
			// 一期设备直接存的浮点数
			byte[] temps = ByteUtil.intToBins(Float.floatToIntBits(value));
			
			for (int j = n; j > 0; j--) {
				dataByte.append(new byte[] {temps[2 * (j-1)], temps[2 * (j-1) + 1]});
			}
		} else if (flag.equals("23") || flag.equals("24")) {
			int valueInt = (int) value; // 二期设置阈值只支持整数
			byte[] temps = ByteUtil.intToBins(valueInt, n*2);
			
			for (int i = 0; i < temps.length; i++) {
				dataByte.append(temps[i]);
			}
		}
		
		return dataByte;
	}
}
