package cn.map.szmap.service;

import cn.base.bean.BeanHelper;
import cn.base.json.JsonHelper;
import cn.base.util.RHUtil;
import cn.map.shortroad.Point;
import cn.map.szmap.LayerConstant;
import cn.map.szmap.algorithm.SzMapAlgoService;
import cn.map.szmap.cache.CacheManager;
import cn.map.szmap.cache.ICache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("all")
@Component("szMapHttpService")
public class SzMapHttpService {
	private static Log logger = LogFactory.getLog(SzMapHttpService.class);
	private static final String ENCODING = "gbk";
	
	public String readMenuResource(){
		String rootpath = ConfigHelper.getRootPath();
		String menuConfig = ConfigHelper.fileToString(rootpath+"/szmap/mainConfig.json", ENCODING);
		logger.info("SzMapHttpService-menuconfig:"+menuConfig);
		return menuConfig;
	}
	public String getMapPropertyByKey(String key){
		String value = null;
		try {
			value = ConfigHelper.getPropertyByKey(key);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("SzMapHttpService-getBasePropertyByKey error:"+key);
		}
		return value;
	}
	public List<Map> getMapDataByLayerSeq(Map map){
		return CacheManager.getIntance().getCacheLayerDate(map);
	}
	
	/**
	 * 地图点位初始化
	 * @param map 包含4个key:minLng, minLat, maxLng, maxLat, layerSeq
	 * @return
	 */
	public Map getMapGridData(Map map){
		Map rsMap = new HashMap();
		List<Map> rsList = new ArrayList();
		List<Map> pointList = new ArrayList();
		int start = (int)map.get("start");
		int limit = (int)map.get("limit");
		int pageTotal = start + limit;
		int total = 0;
		pointList = CacheManager.getIntance().getCacheLayerDate(map);
		if (LayerConstant.LAYER_TYPE_MONITOR.equals(Long.valueOf((String)map.get("layerSeq")))) {
			//摄像头
			String LIKExzbh = (String)map.get("LIKExzbh");
			String LIKEsbbh = (String)map.get("LIKEsbbh");
			String LIKEtdmc = (String)map.get("LIKEtdmc");
			boolean selectAll = false;
			if(RHUtil.isEmpty(LIKExzbh)&&RHUtil.isEmpty(LIKEsbbh)&&RHUtil.isEmpty(LIKEtdmc)){
				selectAll = true;
			}
			for(int i=0;i<pointList.size();i++){
				Map pMap = pointList.get(i);
				if(RHUtil.isNotEmpty(pMap)){
					String xzbh = (String)pMap.get("xzbh");
					String sbbh = (String)pMap.get("sbbh");
					String tdmc = (String)pMap.get("tdmc");
					int xzbh_i = xzbh.indexOf(LIKExzbh);
					int	sbbh_i = sbbh.indexOf(LIKEsbbh);
					int tdmc_i = tdmc.indexOf(LIKEtdmc);
					if(selectAll){
						total++;
						// total大于start且total小于pageTotal
						if(total > start && total <= pageTotal){
							rsList.add(pMap);
						}
					}else{
						if(!(xzbh_i<0||sbbh_i<0||tdmc_i<0)){
							total++;
							if(total > start && total <= pageTotal){
								rsList.add(pMap);
							}							
						}
					}					
				}
			}
		}else if (LayerConstant.LAYER_TYPE_MONITORLOCATION.equals(Long.valueOf((String)map.get("layerSeq")))) {
			//车辆卡口图层
			String LIKExzbh = (String)map.get("LIKExzbh");
			String LIKElkmc = (String)map.get("LIKElkmc");
			boolean selectAll = false;
			if(RHUtil.isEmpty(LIKExzbh)&&RHUtil.isEmpty(LIKElkmc)){
				selectAll = true;
			}
			for(int i=0;i<pointList.size();i++){
				Map pMap = pointList.get(i);
				if(RHUtil.isNotEmpty(pMap)){
					String xzbh = (String)pMap.get("xzbh");
					String lkmc = (String)pMap.get("lkmc");
					int xzbh_i = xzbh.indexOf(LIKExzbh);
					int lkmc_i = lkmc.indexOf(LIKElkmc);
					if(selectAll){
						total++;
						if(total > start && total <= pageTotal){
							rsList.add(pMap);
						}
					}else{
						if(!(xzbh_i<0||lkmc_i<0)){
							total++;
							if(total > start && total <= pageTotal){
								rsList.add(pMap);
							}							
						}
					}				
				}
			}		
		}else if (LayerConstant.LAYER_TYPE_CHEGPS.equals(Long.valueOf((String)map.get("layerSeq")))) {
			//带GPS车辆
			String LIKEbmbh = (String)map.get("LIKEbmbh");
			String LIKEhphm = (String)map.get("LIKEhphm");
			boolean selectAll = false;
			if(RHUtil.isEmpty(LIKEbmbh)&&RHUtil.isEmpty(LIKEhphm)){
				selectAll = true;
			}
			for(int i=0;i<pointList.size();i++){
				Map pMap = pointList.get(i);
				if(RHUtil.isNotEmpty(pMap)){
					String bmbh = (String)pMap.get("gxbmbh");
					String hphm = (String)pMap.get("hphm");
					int bmbh_i = bmbh.indexOf(LIKEbmbh);
					int hphm_i = hphm.indexOf(LIKEhphm);
					if(selectAll){
						total++;
						if(total > start && total <= pageTotal){
							rsList.add(pMap);
						}
					}else{
						if(!(bmbh_i<0||hphm_i<0)){
							total++;
							if(total > start && total <= pageTotal){
								rsList.add(pMap);
							}							
						}
					}				
				}
			}		
		}else if (LayerConstant.LAYER_TYPE_ELECTRICFENCE.equals(Long.valueOf((String)map.get("layerSeq")))) {
			// 电子围栏图层
		}
		rsMap.clear();
		rsMap.put("total", total);
		rsMap.put("rows", rsList);
		return rsMap;
	}
	/**
	 * 地图点位初始化
	 * @param map 包含4个key:minLng, minLat, maxLng, maxLat, layerSeq
	 * @return
	 */
	public List<Map> getMapData(Map map){
		List<Map> points = new ArrayList();
		try {
			long t = System.currentTimeMillis();
			if (LayerConstant.LAYER_TYPE_CHEGPS.equals(Long.valueOf((String)map.get("layerSeq")))) {
				points = CacheManager.getIntance().getCacheLayerDate(map);
			} else {
				List<Map> lngLatList = SzMapAlgoService.getMapPointsOf32Blocks(map);
				List<Map> dataList = CacheManager.getIntance().getCacheLayerDate(map);
				if(dataList  == null || dataList.size()<=0){
					throw new Exception("数据为空，szmap私有配置是否开启？ 或数据库确无数据？ seq:"+map.get("seq"));
				}
				int mapLevel = Integer.parseInt((String)map.get("mapLevel"));
				int maxLevel = Integer.parseInt((String)map.get("maxLevel"));
				int limit = ConfigHelper.getInstance().getMaxSizeOfBlock();
				if (maxLevel <= mapLevel + 2) 
					limit  = 50;
				for (Map map2 : lngLatList) {
					Point point = new Point( (String)map2.get("minLng"), (String)map2.get("minLat"));
					Point point2 = new Point(  (String)map2.get("maxLng"), (String)map2.get("maxLat"));
					List pointList = new ArrayList();
					pointList.add(point);
					pointList.add(point2);
					List<Map> pointsOfBlock = SzMapAlgoService.getListByRec(pointList, dataList, false, limit);
				    points.addAll(pointsOfBlock);
				}
			}
			if(map.get("currentPopUpMarkerSeq")!=null && map.get("layerSeq").equals(map.get("currentPopUpMarkerSeq"))){
				
				String PopUpMarkerLongitude = map.get("popUpMarkerLongitude").toString();
				String PopUpMarkerLatitude = map.get("popUpMarkerLatitude").toString();
				
				Point pointmin = new Point((String)map.get("minLng"), (String)map.get("minLat"));
				Point pointmax = new Point((String)map.get("maxLng"),  (String)map.get("maxLat"));
				
				Double x = Double.parseDouble(PopUpMarkerLongitude);
				Double y = Double.parseDouble(PopUpMarkerLatitude);
				
				boolean oldpointin = SzMapAlgoService.isPointInCurrentRange(x, y, pointmin, pointmax);
				System.out.println("在不在" + oldpointin );
				
				if(oldpointin){
					
					String currentPopUpMarkerId = map.get("currentPopUpMarkerId").toString();
					String currentPopUpMarkerSeq = map.get("currentPopUpMarkerSeq").toString();
					
					boolean exist = false;
					for (Map o : points) {
						if(o.get("id").equals(currentPopUpMarkerId)){
							System.out.println("已找到当前marker");
							exist = true ;
							break;
						}
					}
					
					if(!exist){
						ICache cache =  CacheManager.getIntance().getLayer(Integer.parseInt(currentPopUpMarkerSeq));
						Map m1  = cache.get(currentPopUpMarkerId);
						points.add(m1);
					}
				}
			}
			
			long t2 = System.currentTimeMillis();
			logger.info("getMapData=========================== 耗时 " + (t2 - t) + " ms ..................");
			logger.info("points.length===========================  " + points.size() + "..................");
		} catch(Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService异常getMapData["+e.getMessage()+"]");
		}
		return points;
	}
	
	/**
	 * 点选
	 * @param map 包含3个key:longitude, latitude, layerSeq
	 * @return
	 */
	public  List<Map> getListByPoint(Map map) {
		List list = new ArrayList();
		try {
			long t = System.currentTimeMillis();
			Point point = new Point(map.get("longitude").toString(), map.get("latitude").toString());
			double width = 0.000100d;
			List<Map> channelList = CacheManager.getIntance().getCacheLayerDate(map);
			list =  SzMapAlgoService.getListByPoint(point, width, channelList);
			long t2 = System.currentTimeMillis();
			logger.info("getListByPoint=========================== 耗时 " + (t2 - t) + " ms ..................");
			logger.info("list.length===========================  " + list.size() + "..................");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService异常getListByPoint["+e.getMessage()+"]");
		}
		return list;
	}
	
	/**
	 * 圈选
	 * @param map 包含4个key:radius, longitude, latitude, layerSeq
	 * @return
	 */
	public  List<Map> getListByCircle(Map map) {
		List list = new ArrayList();
		try {
			long t = System.currentTimeMillis();
			double width = Double.parseDouble(map.get("radius").toString());
			double longitude = Double.parseDouble(map.get("longitude").toString());
			double latitude = Double.parseDouble(map.get("latitude").toString());
			List<Map> channelList = CacheManager.getIntance().getCacheLayerDate(map);
			list =  SzMapAlgoService.getListByCircle(longitude, latitude, width, channelList);
			long t2 = System.currentTimeMillis();
			logger.info("getListByCircle=========================== 耗时 " + (t2 - t) + " ms ..................");
			logger.info("list.length===========================  " + list.size() + "..................");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService异常getListByCircle["+e.getMessage()+"]");
		}
		return list;
	}
	
	/**
	 * 线选
	 * @param map 包含2个key:points,layerSeq
	 * @return
	 */
	public  List<Map> getListByLine(Map map) {
		List list = new ArrayList();
		try {
			long t = System.currentTimeMillis();
			List pointList = new ArrayList();
			String[] points = map.get("points").toString().split(",");
			for (int i = 0; i < points.length / 2; i++) {
				Point point = new Point( points[i * 2], points[i * 2 + 1]);
				pointList.add(point);
			}
			double width = 0.000100d;
			List<Map> channelList = CacheManager.getIntance().getCacheLayerDate(map);
			list =  SzMapAlgoService.getListByLine(pointList, width, channelList);
			long t2 = System.currentTimeMillis();
			logger.info("getListByCircle=========================== 耗时 " + (t2 - t) + " ms ..................");
			logger.info("list.length===========================  " + list.size() + "..................");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService异常getListByLine["+e.getMessage()+"]");
		}
		return list;
	}
	
	/**
	 * 框选
	 * @param map 包含4个key:minLng, minLat, maxLng, maxLat, layerSeq
	 * @return
	 */
	public List<Map> getListByRec(Map map){
		List list = new ArrayList();
		try {
			long t = System.currentTimeMillis();
			Point point = new Point( (String)map.get("minLng"), (String)map.get("minLat"));
			Point point2 = new Point(  (String)map.get("maxLng"), (String)map.get("maxLat"));
			List pointList = new ArrayList();
			pointList.add(point);
			pointList.add(point2);
			List<Map> channelList = CacheManager.getIntance().getCacheLayerDate(map);
			list = SzMapAlgoService.getListByRec(pointList, channelList, false, -1);
			long t2 = System.currentTimeMillis();
			logger.info("getListByCircle=========================== 耗时 " + (t2 - t) + " ms ..................");
			logger.info("list.length===========================  " + list.size() + "..................");
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService异常getListByRec["+e.getMessage()+"]");
		}
		return list;
	}
	
	/*
	public String update_ViChannel(Map obj ){
		try {
			if(obj == null) return  LoginConstants.LOGIN_ERROR;
			Map ret  = BeanHelper.getViChannelDao().update_ViChannel(obj);
			if(ret.containsKey("success")){
				ICache iCache = CacheManager.getIntance().getLayer(LayerConstant.LAYER_TYPE_MONITOR.intValue());
				((MonitorCacheImpl)iCache).updateMonitorInfo(obj);
			}
			return LoginConstants.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService update_ViChannel:" + e);
		}
		return LoginConstants.LOGIN_ERROR;
	}
	*/
	
	/**
	 * 获取VpMap
	 * @param obj
	 * @return
	 */
	public String getVpMap(Map obj ){
		try {
			return JsonHelper.encodeObject2Json(BeanHelper.getModuleConfFactory().getDitu());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("SzMapHttpService getVpMap:" + e);
		}
		return null;
	}


}
