package fr.zng.xxzx.netty.dispatcher;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import fr.zng.xxzx.common.cacheData.ZngCacheData;
import fr.zng.xxzx.common.dao.HqCnoDao;
import fr.zng.xxzx.common.dao.ShljDao;
import fr.zng.xxzx.common.dao.ShwsDao;
import fr.zng.xxzx.common.dao.TdFlowDao;
import fr.zng.xxzx.common.dao.UnoDao;
import fr.zng.xxzx.common.dao.impl.HqCnoDaoImpl;
import fr.zng.xxzx.common.dao.impl.ShljDaoImpl;
import fr.zng.xxzx.common.dao.impl.ShwsDaoImpl;
import fr.zng.xxzx.common.dao.impl.TdFlowDaoImpl;
import fr.zng.xxzx.common.dao.impl.UnoDaoImpl;
import fr.zng.xxzx.common.entity.HqCnoEntity;
import fr.zng.xxzx.common.entity.ShljEntity;
import fr.zng.xxzx.common.entity.ShwsEntity;
import fr.zng.xxzx.common.entity.TdFlowEntity;
import fr.zng.xxzx.common.entity.UnoEntity;
import fr.zng.xxzx.common.util.CommUtil;
import fr.zng.xxzx.common.util.StringUtil;
import net.sf.json.JSONObject;

/**
 * HTTP SERVER处理类
 * 
 * @author shijf
 *
 */
public class MyHandler implements HttpHandler {

	static Logger logger = Logger.getLogger(MyHandler.class);
	
	/**
	 * 油枪报警是否已上传环保
	 * @param 枪号   是否上传   0否，1是
	 * */
	Map<String,String> mapHb = new HashMap<String,String>();
	
	
	@Override
	public void handle(HttpExchange exchange)  {

		// 定义返回结果
		JSONObject result = new JSONObject();
		/**
		 * 解析请求参数与地址信息
		 */
		URI uri = exchange.getRequestURI();
		Map<String, String> map = new HashMap<String, String>();
		String[] arrSplit = null;
		arrSplit = uri.getQuery().split("[&]");
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");
			// 解析出键值
			if (arrSplitEqual.length > 1) {
				// 正确解析
				map.put(arrSplitEqual[0], arrSplitEqual[1]);
				// logger.info("参数"+arrSplitEqual[0]+":"+arrSplitEqual[1]);
			}
		}

		/**
		 * 正对function做不同的业务逻辑处理
		 */
		String function = map.get("function");
		if (StringUtil.isNotEmpty(function)) {
			//开门
			if("open".equals(function)){
				result = open(map,result);
			}
			//关门
			else if("close".equals(function)){
				result = close(map,result);
			}
			//生活污水数据上传
			else if("shwsUpload".equals(function)){
				upLoadShws(map,result);
			}
		} else {
			result.put("ret", "0");
			result.put("msg", "参数业务功能未定义");
		}
		// 结果返回给请求端
		Headers headers = exchange.getResponseHeaders();
		headers.add("Access-Control-Allow-Origin", "*");
		headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		headers.add("Access-Control-Allow-Headers", "Content-Type");
		headers.add("Content-Type", "application/json");
		String data = "";
		OutputStream out = exchange.getResponseBody(); // 获得输出流
		try {
			exchange.sendResponseHeaders(200, data.length());
			out.write(result.toString().getBytes());
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			// 设置响应头属性及响应信息的长度
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private JSONObject open(Map<String, String> map, JSONObject result){
		try {
			//查询设备是否存在
			String deviceId = map.get("deviceUid");
			String portUid = map.get("portUid");
			//获取我们的桶号，用户号，船号
			String colno = getCno(portUid).getCno();
			if(StringUtil.isEmpty(deviceId)){
				result.put("code", "-1");
				result.put("msg", "deviceUid为空");
				return result;
			}
			HqCnoEntity pdt = getHqPdt(deviceId,portUid);
			if(pdt!=null){
				String imei = pdt.getImei();
				//海启传过来的桶号，用户号，船号
				String userUid = map.get("userUid");
				String shipUid = map.get("shipUid");
				UnoEntity user = getUser(userUid);
				if(user ==null){
					result.put("code", "2100");
					result.put("msg", "用户账户认证失败");
					return result;
				}
				//插入一条开门未投递记录
				TdFlowEntity en = new TdFlowEntity();
				en.setUno(user.getUno());
				en.setBpoint(user.getPoint());
				en.setBweight(user.getWeight());
				en.setColno(colno);
				en.setImei(imei);
				en.setCreater(user.getUno());
				en.setUpdater(user.getUno());
				en.setDel("0");
				TdFlowDao tdao = new TdFlowDaoImpl();
				String uuid = tdao.insert2(en);
				//根据设备号获取ip
				String ip = ZngCacheData.sessionCodeIP.get(imei);
				String time = System.currentTimeMillis()/1000+"";
				String endata = "0000000000000000";
				//桶号，操作流水号，状态，超时时间
				String data = colno+uuid+"01"+"A0860100";
				String replyData = CommUtil.doMakeData2("2003","00", imei, time, endata,
						data);
				long now = System.currentTimeMillis();
				String str = ZngCacheData.sessionXtTime.get(imei);
				if(str!=null){
					long timeXt = 	Long.parseLong(str);
					if(now-timeXt<2000){
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				//根据ip获取设备发送开门
				ZngCacheData.sessionMap.get(ip).getChannel().writeAndFlush(replyData);
				ZngCacheData.sessionMap.get(ip).getChannel().flush();
				CommUtil.doPrint(null, "", " 发送数据 .." + replyData);
				JSONObject uid = new JSONObject();
				uid.put("uid",uuid);
				result.put("code", "0");
				result.put("msg", "ok");
				result.put("data",uid);
			}else{
				//设备未注册
				result.put("code", "-1");
				result.put("msg", "设备未注册");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	
	private JSONObject close(Map<String, String> map, JSONObject result){
		try {
			String uuid = map.get("uuid");
			if(StringUtil.isEmpty(uuid)){
				result.put("code", "-1");
				result.put("msg", "uuid为空");
				return result;
			}
			//根据uuid去查询上传数据
			TdFlowEntity tdFlowEn = new TdFlowEntity();
			tdFlowEn.setUuid(uuid);
			TdFlowDao tdFlowDao = new TdFlowDaoImpl();
			//该笔记录对应的投递情况
			tdFlowEn = tdFlowDao.getTdFlowByUuid(tdFlowEn);
			if(StringUtil.isEmpty(tdFlowEn.getWeight())){
				//说明还未关门，先关门再等待结果上传
				String imei = tdFlowEn.getImei();
				String colno = tdFlowEn.getColno();
				String ip = ZngCacheData.sessionCodeIP.get(imei);
				String time = "0000000000";
				String endata = "0000000000000000";
				//桶号，操作流水号，状态，超时时间
				String data = colno+uuid+"02";
				String replyData = CommUtil.doMakeData2("2003","00", imei, time, endata,
						data);
				long now = System.currentTimeMillis();
				String str = ZngCacheData.sessionXtTime.get(imei);
				if(str!=null){
					long timeXt = 	Long.parseLong(str);
					if(now-timeXt<2000){
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
				//根据ip获取设备发送关门
				ZngCacheData.sessionMap.get(ip).getChannel().writeAndFlush(replyData);
				ZngCacheData.sessionMap.get(ip).getChannel().flush();
				CommUtil.doPrint(null, "", " 发送数据 .." + replyData);
				try {
					Thread.sleep(5000);
					//延迟5s后二次读取投递记录
					tdFlowEn = tdFlowDao.getTdFlowByUuid(tdFlowEn);
					if(StringUtil.isEmpty(tdFlowEn.getWeight())){
						//查询失败
						result.put("code", "9000");
						result.put("msg", "查询交易结果失败，请稍后查询");
					}else{
						//结果返回船e行
						result.put("code", "0");
						result.put("msg", "ok");
						JSONObject uid = new JSONObject();
						uid.put("actionUid",uuid);
						uid.put("count",tdFlowEn.getWeight());
						uid.put("unit","kg");
						result.put("data", uid);
						//插入长航中间库
						ShljEntity shljEn = new ShljEntity();
						ShljDao shljDao = new ShljDaoImpl();
						shljEn.setWeight(tdFlowEn.getWeight()+"");
						shljEn.setShipId("");
						shljEn.setShipId("");
						shljDao.insertShlj(shljEn);
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				//有投递结果直接返回船e行
				result.put("code", "0");
				result.put("msg", "ok");
				JSONObject uid = new JSONObject();
				uid.put("actionUid",uuid);
				uid.put("count",tdFlowEn.getWeight());
				uid.put("unit","kg");
				result.put("data", uid);
				//插入长航中间库
				ShljEntity shljEn = new ShljEntity();
				ShljDao shljDao = new ShljDaoImpl();
				shljEn.setWeight(tdFlowEn.getWeight()+"");
				shljEn.setShipId("");
				shljEn.setShipId("");
				shljDao.insertShlj(shljEn);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
	//查询设备状态信息
	private HqCnoEntity getHqPdt(String deviceId,String portUid){
		//先从缓存取
		HqCnoEntity hcEntity = ZngCacheData.sessionPdt.get(deviceId+portUid);
		if(hcEntity==null){
			HqCnoDao pdt = new HqCnoDaoImpl();
			HqCnoEntity pdtEn = new HqCnoEntity();
			pdtEn.setDeviceId(deviceId);
			pdtEn.setPortUid(portUid);
			hcEntity = pdt.getHqPdt(pdtEn);
			ZngCacheData.sessionPdt.put(deviceId+portUid,hcEntity);
		}
		return hcEntity;
	}
	//上传生活污水
	private JSONObject upLoadShws(Map<String, String> map, JSONObject result){
		try {
			String sl = map.get("sl");
			String userId = map.get("userId");
			String shipId = map.get("shipId");
			ShwsEntity shws = new ShwsEntity();
			shws.setSl(sl);
			shws.setUserId(userId);
			shws.setShipId(shipId);
			ShwsDao sd = new ShwsDaoImpl();
			sd.insertShws(shws);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	} 
	//查询用户信息
	private UnoEntity getUser(String userUid){
		UnoEntity userEntity = ZngCacheData.sessionUser.get(userUid);
		if(userEntity == null){
			UnoDao user = new UnoDaoImpl();
			userEntity = user.getByUserUid(userUid);
			ZngCacheData.sessionUser.put(userUid,userEntity);
		}
		return userEntity;
	}
	//查询桶号对应关系
	private HqCnoEntity getCno(String portUid){
		HqCnoEntity hqCnoEntity =  ZngCacheData.sessionCno.get(portUid);
		if(hqCnoEntity == null){
			HqCnoDao hqCnoDao = new HqCnoDaoImpl();
			hqCnoEntity = hqCnoDao.getCno(portUid);
			ZngCacheData.sessionCno.put(portUid,hqCnoEntity);
		}
		return hqCnoEntity;
	}
}
