package com.xt.hb.gis.ctl;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.stereotype.Controller;

import com.xt.hb.gis.common.DataServerGlobal;
import com.xt.hb.gis.common.GlobalFlexData;
import com.xt.hb.gis.util.HttpProxy;
import com.yuanxd.tools.hscbdt.HscbdtService;
import com.yuanxd.tools.hscbdt.bean.SeqShips;
import com.yuanxd.tools.hscbdt.bean.Ship;
import com.yuanxd.tools.hscbdt.bean.ShipPosition;
import com.yuanxd.tools.utils.string.StringUtils;

/**
 * 海事AIS相关Flex服务接口
 * 
 * @author 袁晓冬
 *
 */
@Controller
@RemotingDestination("aisCtl")
public class AisCtl extends BaseCtl {
	@Autowired
	HscbdtService hscbdtService;


	/**
	 * 根据url,id获取单对象信息
	 * 
	 * @return
	 */
	public JSONObject initFlexData() throws Exception {
		JSONObject jsonObject = new JSONObject();
		GlobalFlexData global = new GlobalFlexData();
	    Class<?> cls = global.getClass();////////////////////////通过类的名称反射类
        Object obj=cls.newInstance();//////////////////////对象实例化
		Field[] fieldArr = cls.getDeclaredFields(); // 获取实体类的所有属性，返回Field数组
		for (int j = 0; j < fieldArr.length; j++) { // 遍历所有属性
            String name = fieldArr[j].getName(); // 获取属性的名字
            String value = (String) fieldArr[j].get(obj); // 获取属性的名字
    		jsonObject.element(name, value);
		}
		return jsonObject;
	}

	/**
	 * 区域检索ais船舶数据
	 * 
	 * @param extend
	 * @return
	 */
	public Ship[] queryAis(String extend) {
		Map<String, Object> ext = parseData(extend);
		SeqShips ships = hscbdtService.searchObjectResultByArea(1,
				String.valueOf(ext.get("xmin")) + "," + String.valueOf(ext.get("ymin")) + ",",
				String.valueOf(ext.get("xmax")) + "," + String.valueOf(ext.get("ymax")));
		if (ships != null && ships.getShips().length > 0) {
			for (Ship ship : ships.getShips()) {
				if ("0".equals(ship.getEta())) {
					ship.setEta("");
				}
			}
		}
		return ships == null ? null : ships.getShips();
	}

	/**
	 * 根据mmsi查询船舶轨迹
	 * 
	 * @param mmsi
	 * @param beginDate
	 * @param endDate
	 * @return
	 */
	public Collection<ShipPosition> queryAISCBsByMMSI(String mmsi, String beginDate, String endDate) {
		ShipPosition[] poss = hscbdtService.findTrackObject(mmsi,
				StringUtils.isEmpty(beginDate) ? new Date() : new Date(Long.parseLong(beginDate)),
				StringUtils.isEmpty(endDate) ? new Date() : new Date(Long.parseLong(endDate)));
		ArrayList<ShipPosition> posList = new ArrayList<ShipPosition>();
		if (poss.length > 0) {
			for (int i = (poss.length - 1); i > -1; i--) {
				if(null!=poss[i]) {
					posList.add(poss[i]);
				}
			}
		}
		return posList;
	}

	/**
	 * 查询单船轨迹
	 * 
	 * @param mmsi
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public ArrayList<ShipPosition> queryAISCBsByMMSI2(String mmsi, String startTime, String endTime) {
		Date startDate = new Date(Long.parseLong(startTime));
		Date endDate = new Date(Long.parseLong(endTime));
		String trackStr = hscbdtService.findTrack(mmsi, startDate, endDate);
		ArrayList<ShipPosition> posList = new ArrayList<ShipPosition>();
		ShipPosition routeVo = null;
		// 解析逗号分隔字符串
		String[] routeArr = trackStr.split(",");
		Date date = new Date();
		for (int i = (routeArr.length - 1); i > -1; i--) {
			// 解析 “|” 号分隔字符串
			String str = routeArr[i];
			String[] strArr = str.split("\\|");
			if (strArr.length > 0) {
				routeVo = new ShipPosition();
				routeVo.setLon(strArr[1]);
				routeVo.setLat(strArr[2]);
				if (StringUtils.isNotEmpty(strArr[3])) {
					date = new Date();
					// 加毫秒数
					date.setTime(Long.parseLong(strArr[3] + "000"));
					routeVo.setTime(date);
				}
				routeVo.setAngle(strArr[4]);
				posList.add(routeVo);
			}
		}
		return posList;
	}

	/**
	 * 获取港口港区企业树
	 * 
	 * @return
	 */
	public JSONArray queryGkgqqyTree(String flg) {
		String url = DataServerGlobal.GKGQQY_URL + "?wh="+flg;
		JSONArray jsonArray = null;
		try {
			String strJson = HttpProxy.http_get_json(url);
			jsonArray = JSONArray.fromObject(strJson);
			// com.alibaba.fastjson.JSONArray arr =
			// com.alibaba.fastjson.JSONObject.parseArray(strJson);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonArray;
	}

	/**
	 * 获取视频树
	 * 
	 * @return
	 */
	public JSONArray querySpTree() {
		String url = DataServerGlobal.SP_URL;
		JSONArray jsonArray = null;
		try {
			String strJson = HttpProxy.http_get_json(url);
			strJson = strJson.replace("null", "[]");
			jsonArray = JSONArray.fromObject(strJson);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonArray;
	}

	/**
	 * 获取港区信息
	 * 
	 * @return
	 */
	public JSONObject querySingleGq(Integer id) {
		return getSingleJsonObj(DataServerGlobal.SINGlE_GQ_URL, id);
	}

	/**
	 * 获取码头信息
	 * 
	 * @return
	 */
	public JSONObject querySingleMt(Integer id) {
		JSONObject obj = getSingleJsonObj(DataServerGlobal.SINGlE_MT_URL, id);
		if(null != obj) {
			// 固定数据组
			String[] zyhlArr = {"煤炭及制品","石油、天然气及制品","金属矿石",
					"钢铁","矿建材料","水泥",
					"木材","非金属矿石","化肥及农药",
					"盐","粮食","机械、设备、电器",
					"化工原料及制品","有色金属","轻工、医药产品",
					"农、林、牧、渔业产品","其它"};
			String[] mtytArr = {"原油码头","液化天然气码头","液体散货码头",
					"危险品码头","煤炭、矿石码头","件杂货码头",
					"散粮码头","集装箱码头","滚装、客运码头",
					"多用途码头","通用码头"};
			if(null != obj.get("ZYHL")) {
				String zyhl = obj.get("ZYHL").toString();
				String zyhlShow = "";
				// 判断主要货类
				if(zyhl.length() == zyhlArr.length) {
					for(int i = 0; i < zyhl.length(); i++) {
						if("Y".equals(zyhl.charAt(i)) || i==7) {
							zyhlShow += zyhlArr[i] + ",";
						}
					}
				}
				if(zyhlShow.length() > 0) {
					zyhlShow = zyhlShow.substring(0, zyhlShow.length() - 1);
					obj.element("ZYHL", zyhlShow);
				} else {
					obj.element("ZYHL", "");
				}
			}
			if(null != obj.get("MTYT")) {
				String mtyt = obj.get("MTYT").toString();
				String mtytShow = "";
				// 判断码头用途
				if(mtyt.length() == mtytArr.length) {
					for(int i = 0; i < mtyt.length(); i++) {
						if("Y".equals(mtyt.charAt(i))) {
							mtytShow += mtytArr[i] + ",";
						}
					}
				}
				if(mtytShow.length() > 0) {
					mtytShow = mtytShow.substring(0, mtytShow.length() - 1);
					obj.element("MTYT", mtytShow);
				} else {
					obj.element("MTYT", "");
				}
			}
			
		}
		return obj;
	}

	/**
	 * 获取泊位信息
	 * 
	 * @return
	 */
	public JSONObject querySingleBw(Integer id) {
		return getSingleJsonObj(DataServerGlobal.SINGlE_BW_URL, id);
	}

	/**
	 * 获取经营人信息
	 * 
	 * @return
	 */
	public JSONObject querySingleJyr(Integer id) {
		return getSingleJsonObj(DataServerGlobal.SINGlE_JYR_URL, id);
	}

	/**
	 * 获取取水口信息
	 * 
	 * @return
	 */
	public JSONObject querySingleQsk(Integer id) {
		return getSingleJsonObj(DataServerGlobal.SINGlE_QSK_URL, id);
	}

	/**
	 * 获取船舶预警区域信息
	 * 
	 * @return
	 */
	public JSONObject querySingleCbyj(Integer id) {
		return getSingleJsonObj(DataServerGlobal.SINGlE_CBYJ_URL, id);
	}

	/**
	 * 获取泊位分页信息
	 * 
	 * @return
	 */
	public JSONObject queryBwPage(Integer id, Integer page, Integer size) {
		String url = DataServerGlobal.BW_PAGE_URL+id+"&page="+page+"&size="+size;
		JSONObject jsonObject = null;
		try {
			String strJson = HttpProxy.http_get_json(url);
			if(null == strJson) {
				strJson = "";
			}
			strJson = strJson.replace("null", "\"\"");
			if(StringUtils.isNotEmpty(strJson)) {
				jsonObject = JSONObject.fromObject(strJson);
			} else {
				jsonObject = new JSONObject();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * 根据url,id获取单对象信息
	 * 
	 * @return
	 */
	public JSONObject getSingleJsonObj(String url, Integer id) {
		String uid = String.valueOf(id);
		JSONObject jsonObject = null;
		try {
			String strJson = HttpProxy.http_get_json(url+"/"+uid);
			if(StringUtils.isNotEmpty(strJson)) {
				jsonObject = JSONObject.fromObject(strJson);
			} else {
				jsonObject = new JSONObject();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	/**
	 * 获取船名
	 * 
	 * @return
	 */
	public String getShipName(String name) {
		String url = DataServerGlobal.SHIPNAME_URL;
		String strJson = "";
		if(StringUtils.isNotEmpty(name)) {
			try {
				name = name.replaceAll(" ", "%20");
				url = url + "/"+name;
				strJson = HttpProxy.http_get_json(url);
				if(StringUtils.isNotEmpty(strJson)) {
					strJson = strJson.replace("\"", "");
				} else {
					return "";
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return strJson;
	}

}
