package com.fr.tx.common.netty.cpu3;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.fr.tx.common.dao.EquipNdDao;
import com.fr.tx.common.dao.EquipWdDao;
import com.fr.tx.common.dao.EquipYgylDao;
import com.fr.tx.common.dao.EquipYjylDao;
import com.fr.tx.common.dao.GunDao;
import com.fr.tx.common.dao.RealDataDao;
import com.fr.tx.common.dao.impl.EquipNdDaoImpl;
import com.fr.tx.common.dao.impl.EquipWdDaoImpl;
import com.fr.tx.common.dao.impl.EquipYgylDaoImpl;
import com.fr.tx.common.dao.impl.EquipYjylDaoImpl;
import com.fr.tx.common.dao.impl.GunDaoImpl;
import com.fr.tx.common.dao.impl.RealDataDaoImpl;
import com.fr.tx.common.data.CacheData;
import com.fr.tx.common.entity.EquipNdEntity;
import com.fr.tx.common.entity.EquipWdEntity;
import com.fr.tx.common.entity.EquipYgylEntity;
import com.fr.tx.common.entity.EquipYjylEntity;
import com.fr.tx.common.entity.GunEntity;
import com.fr.tx.common.entity.RealDataEntity;
import com.fr.tx.common.util.CrcUtil;
import com.fr.tx.common.util.StringUtil;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class DataSave {
	/**
	 * 日志
	 */
	private static Logger logger = Logger.getLogger(DataSave.class.getName());

	public DataSave() {
	}
	/**
	 * 保存加油数据
	 * @param 
	 * 站点编号station 
	 * 数据命令res
	 * */
	public int doInsertRealData(String station,String res){
		int ret=0;
		try {
			// TODO 读取加油数据 6801031f01190805185545000004afa600047482190805190257000000f76c000c565c0816
			//枪号
			String gunno = res.substring(8, 10);
			
			System.out.println("gunno:"+gunno);
			
			//地址
			String dressno= res.substring(2,4);
			GunEntity gunEn = new GunEntity();
			GunDao gunDao = new GunDaoImpl();
			//站点
			gunEn.setStation_no(station);
			//油枪对应的板子号
			gunEn.setAddStart(gunno);
			//地址
			gunEn.setAddArea(dressno);
			//去数据库查询油枪信息 （枪号   修正系数）
			List<GunEntity> list = gunDao.getGunData(gunEn);
			String reregas = "1";
			String reregass = "1";
			if(list.size()>0){
				gunEn = list.get(0);
				//真实枪号
				gunno = gunEn.getNo();
				reregas = gunEn.getReregas();
				reregass = gunEn.getReregass();
			}else{
				logger.info("站点"+station+"未创建枪号：" + res.substring(2, 4));
				return -1;
			}
			//gunno=addrGun.get(dressno+gunno);
	/*		if(dressno.startsWith("0")){
				dressno=dressno.substring(1,2);
			}*/
			String beginString=res.substring(10,24);
			String oil=res.substring(24,32);
			String gas=res.substring(32,40);
			String endString=res.substring(40,54);
			String oils=res.substring(54,62);
			String gass=res.substring(62,70);
			Date begin=hexToDate(beginString);
			Date end=hexToDate(endString);
			double oild=hexToDouble(oil,gunno);
			double gasd=hexToDouble(gas,gunno);
			double oilsd=hexToDouble(oils,gunno);
			double gassd=hexToDouble(gass,gunno);
			DecimalFormat decimalFormat = new DecimalFormat("0.00");
			//油气流量
			gasd = Double.parseDouble(reregas) * gasd;
			gasd=Double.parseDouble(decimalFormat.format(gasd));
			//油气流速
			gassd = Double.parseDouble(reregass) * gassd;
			gassd=Double.parseDouble(decimalFormat.format(gassd));
			//delorder = orders.get("clearOneHistory" + gunno);
			RealDataEntity en = new RealDataEntity();
			RealDataDao dao = new RealDataDaoImpl();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			en.setEndTime(df.format(end));
			en.setStartTime(df.format(begin));
			//根据开始结束时间查询数据是否已存在  已存在则直接返回并删除
			if(dao.getDumpCount(en)>0){
				return 1;
			}
			en.setStation_no(station);
			en.setTime(df.format(end));
			en.setJyll(""+oild);
			en.setYqll(""+gasd);
			en.setJyls(""+oilsd);
			en.setYqls(""+gassd);
			en.setKeepTime(""+((end.getTime()-begin.getTime())/1000));
			en.setGunNo(gunno);
			double point=0d;
			//连续加油小于15为无效数据   不记录气液比警告
			if (oild == 0 || gasd == 0 || oild<15) {
/*				point = 0;
				en.setIsWarning("0"); // 0不警告
*/				
				return 1;
			} else {
				point = gasd / oild;
				point=Double.parseDouble(decimalFormat.format(point));
				logger.info("气液比：" + point);
				//此处写死先
				if (point > (1.3d) || point < (0.9d)) {
					en.setIsWarning("1"); // 1警告
				} else {
					en.setIsWarning("0"); // 0不警告
				}
			}
			en.setQyb(""+point);
			ret = dao.insert(en);
			//updatewarning(gunno);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return ret;
	}
	/**
	 * 保存油枪配置数据
	 * */
	public int doSaveGun(JSONObject json){
		int p = 0;
		try {
			GunEntity ge = new GunEntity();
			GunDao gd = new GunDaoImpl();
			//站点编号
			ge.setStation_no(json.getString("stationNo"));
			//加油机编号
			ge.setMacNo(json.getString("macNo"));
			//枪号
			ge.setNo(json.getString("no"));
			//地址
			ge.setAddArea(json.getString("addr"));
			//板子序号
			ge.setAddStart(json.getString("stDress"));
			//油枪状态
			ge.setStatus(json.getString("status"));
			//回气量修正系数
			ge.setReregas(json.getString("reregas"));
			//回气速度修正系数
			ge.setReregass(json.getString("reregass"));
			//根据枪号和站点编号查询   存在则更新  不存在则新增
			List<GunEntity> list = gd.getGunData(ge);
			if(list.size()>0){
				p = gd.save(ge);
			}else{
				p = gd.insert(ge);
			}
			if(p>0){
				p=1;
			}else{
				p=0;
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return p;
	}
	/**
	 * 保存加油数据
	 * */
	public int doSaveGunLog(JSONObject json){
		int p = 0;
		try {
			RealDataEntity re = new RealDataEntity();
			RealDataDao rd = new RealDataDaoImpl();
			//站点编号
			re.setStation_no(json.getString("stationNo"));
			//枪号
			re.setGunNo(json.getString("gunNo"));
			//时间
			re.setTime(json.getString("time"));
			//回气量
			re.setYqll(json.getString("yqll"));
			//加油量
			re.setJyll(json.getString("jyll"));
			//预警状态
			re.setIsWarning(json.getString("isWarning"));
			//气液比
			re.setQyb(json.getString("qyb"));
			//开始加油时间
			re.setStartTime(json.getString("startTime"));
			//结束加油时间
			re.setEndTime(json.getString("endTime"));
			//持续时间
			re.setKeepTime(json.getString("keepTime"));
			//最大油气流速
			re.setYqls(json.getString("yqls"));
			//最大加油流速
			re.setJyls(json.getString("jyls"));
			rd.insert(re);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return p;
	}
	/**
	 * 保存浓度数据
	 * */
	public int saveNd(JSONObject json){
		int p = 0;
		EquipNdEntity en = new EquipNdEntity();
		EquipNdDao ed = new EquipNdDaoImpl();
		//站点
		en.setStation_no(json.getString("stationNo"));
		//地址
		en.setAddr(json.getString("addr"));
		//浓度
		en.setNd(json.getString("nd"));
		//时间
		en.setCtime(json.getString("ctime"));
		ed.insert(en);
		return p;
	}
	/**
	 * 保存问度数据
	 * */
	public int saveWd(JSONObject json){
		int p = 0;
		EquipWdEntity en = new EquipWdEntity();
		EquipWdDao ed = new EquipWdDaoImpl();
		//站点
		en.setStation_no(json.getString("stationNo"));
		//地址
		en.setAddr(json.getString("addr"));
		//温度
		en.setWd(json.getString("wd"));
		//时间
		en.setCtime(json.getString("ctime"));
		ed.insert(en);
		return p;
	}
	/**
	 * 保存油罐数据
	 * */
	public int saveYg(JSONObject json){
		int p = 0;
		EquipYgylEntity en = new EquipYgylEntity();
		EquipYgylDao ed = new EquipYgylDaoImpl();
		//站点
		en.setStation_no(json.getString("stationNo"));
		//地址
		en.setAddr(json.getString("addr"));
		//油罐压力
		en.setYgyl(json.getString("ygyl"));
		//时间
		en.setCtime(json.getString("ctime"));
		ed.insert(en);
		return p;
	}
	/**
	 * 保存油机数据
	 * */
	public int saveYj(JSONObject json){
		int p = 0;
		EquipYjylEntity en = new EquipYjylEntity();
		EquipYjylDao ed = new EquipYjylDaoImpl();
		//站点
		en.setStation_no(json.getString("stationNo"));
		//地址
		en.setAddr(json.getString("addr"));
		//油罐压力
		en.setYgyl(json.getString("ygyl"));
		//时间
		en.setCtime(json.getString("ctime"));
		ed.insert(en);
		return p;
	}
	/**
	 * 分析油枪数据
	 * @param 
	 * 站点编号station 
	 * 数据命令res
	 * */
	public void AnslytRealData(JSONObject jsonObject){
		//获取抢号
		String gunNo = jsonObject.getString("gunNo");
		if(gunNo.startsWith("0")){
			gunNo = gunNo.substring(1,2);
		}
		//获取状态
		String status = jsonObject.getString("sts");
		String station = jsonObject.getString("St");
		if("01".equals(status)){
			String json = "{\"no\":\""+gunNo+"\",\"type\":\""+0+"\",\"msg\":\""+gunNo+"号枪加油进行中"+"\"}";
			CacheData.sessionWebMap.get(station).writeAndFlush(new TextWebSocketFrame(json));
		}
		if("02".equals(status)){
			String json = "{\"no\":\""+gunNo+"\",\"type\":\""+1+"\",\"msg\":\""+gunNo+"号枪油枪正常"+"\"}";
			CacheData.sessionWebMap.get(station).writeAndFlush(new TextWebSocketFrame(json)); 
		}
	}
	public double hexToDouble(String a,String gunno){
		double oild = 0d;
		try {
			oild=Integer.parseInt(a,16)/1000d;

		} catch (Exception e) {
			// TODO: handle exception
		}
//		oild = Double.parseDouble(reregas.get(gunno)) * oild;
//		oild=Double.parseDouble(decimalFormat.format(oild));
		return oild;
	}
	public  Date hexToDate(String a){
		Date date = null;
		try {
			byte[] b=CrcUtil.stringTobytes(a);
			date=new Date(b[0]+100,b[1]-1,b[2],b[3],b[4],b[5]);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return date;
	}
	
}
