package com.example.mountaintravel.fragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.esri.android.map.FeatureLayer;
import com.esri.android.map.GraphicsLayer;
import com.esri.android.map.LocationDisplayManager;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISLocalTiledLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.android.map.event.OnStatusChangedListener;
import com.esri.core.geodatabase.ShapefileFeatureTable;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.Graphic;
import com.esri.core.renderer.Renderer;
import com.esri.core.renderer.SimpleRenderer;
import com.esri.core.symbol.CompositeSymbol;
import com.esri.core.symbol.FontStyle;
import com.esri.core.symbol.PictureMarkerSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.Symbol;
import com.esri.core.symbol.TextSymbol;
import com.esri.core.symbol.TextSymbol.HorizontalAlignment;
import com.esri.core.symbol.TextSymbol.VerticalAlignment;

import com.example.mountaintravel.kind.AddGraphic;
import com.example.mountaintravel.kind.FindDbData;
import com.example.mountaintravel.kind.NewInfo;
import com.example.mountaintravel.kind.TextDrawable;
import com.example.mountaintravel.util.AppJsonFileReader;
import com.example.mountaintravel.util.MD5Util;
import com.example.mountaintravel.util.StringChangeUtils;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.Utils;
import com.example.mountaintravel.variable.Variable;
import com.google.code.microlog4android.Logger;
import com.google.code.microlog4android.LoggerFactory;
import com.smart.gtstrvl.GameManagerActivity;
import com.smart.gtstrvl.R;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

@SuppressLint({ "ValidFragment", "NewApi" })
public class MapFragment extends Fragment {
	private Context context;
	public MapView mapView;
	private GraphicsLayer graphicsLayer;
	private LayoutInflater inflater;
	@SuppressWarnings("unused")
	private View callout_view;
	private int routeId;
	private String mineUserid;// 我的 user id
	String mineLocation_x;// 我的x坐标
	String mineLocation_y;// 我的y坐标
	boolean istag = false;
	/**
	 * 有成绩的 user 排名
	 */
	private Map<String, List<String>> rankingMap;

	private FindDbData dbData;
	private LocationDisplayManager ldm;
	private SharedPreferences sp;
	private GraphicsLayer resultLayer;
	private GraphicsLayer pointLayer;
	private GraphicsLayer mypointLayer;
	private int densityDPI;
	private ArrayList<NewInfo> list = new ArrayList<NewInfo>();
	ArrayList<Point> pointList;
	private Drawable startPoint;
	private Drawable stopPoint;

	public MapFragment(Context context) {
		this.context = context;
		dbData = new FindDbData(context);
	}

	public MapFragment() {
		super();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_3, container, false);
	}

	@SuppressLint({ "SdCardPath", "InflateParams" })
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {

		super.onActivityCreated(savedInstanceState);
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		routeId = sp.getInt("routeId", 1);
		mapView = (MapView) getView().findViewById(R.id.map);
		addGraphic = new AddGraphic(mapView, context);
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();
		densityDPI = dm.densityDpi;
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath() + "/" + "gts/" + "create_scenic_area_info/Basic.tpk");
		if (file.exists()) {
			ArcGISLocalTiledLayer tileLayer = new ArcGISLocalTiledLayer(
					"file:///sdcard/gts/create_scenic_area_info/Basic.tpk");
			mapView.centerAt(30.384595, 120.215493, false);
			mapView.addLayer(tileLayer);
		} else {
			ArcGISTiledMapServiceLayer tileLayer = new ArcGISTiledMapServiceLayer(
					"http://218.108.4.35:6080/arcgis/rest/services/Basic/MapServer");
			mapView.centerAt(30.384595, 120.215493, false);
			mapView.addLayer(tileLayer);
		}
		graphicsLayer = new GraphicsLayer();
		resultLayer = new GraphicsLayer();
		pointLayer = new GraphicsLayer();
		mypointLayer = new GraphicsLayer();
		mapView.addLayer(mypointLayer);
		mapView.addLayer(graphicsLayer);
		mapView.addLayer(resultLayer);
		inflater = LayoutInflater.from(context);
		callout_view = inflater.inflate(R.layout.callout2, null);
		mapView.setAllowRotationByPinch(true);
		mapView.enableWrapAround(true);
		mapView.setEsriLogoVisible(false);
		mapView.setMapBackground(Color.WHITE, 0, 0, 0);
		getid();

		// thread = new Thread(new MyThread());
		// thread.start();
	}

	public void getid() {
		mapView.setOnStatusChangedListener(new OnStatusChangedListener() {
			private static final long serialVersionUID = 1L;

			@Override
			public void onStatusChanged(Object source, STATUS status) {
				if ((status == STATUS.INITIALIZED) && (source == mapView)) {
					DefaultTrailShapefile();
					test();
					thread = new Thread(new MyThread());
					thread.start();
					new Thread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if (!sp.getString("parameter", "").equals("")) {
								HashMap<String, Object> parameterMap = StringChangeUtils
										.toObject(
												sp.getString("parameter", ""),
												HashMap.class);
								Object result_obj = parameterMap
										.get("repeaterAxisList");
								List<String> AllUserInformation = (List<String>) result_obj;
								pointList = new ArrayList<Point>();
								for (int i = 0; i < AllUserInformation.size(); i++) {
									HashMap<String, Object> userInfomation = StringChangeUtils
											.toObject(
													AllUserInformation.get(i),
													HashMap.class);
									String locationX = StringUtils
											.toString(userInfomation
													.get("axisX"));
									String locationY = StringUtils
											.toString(userInfomation
													.get("axisY"));
									double x = Double.parseDouble(locationX);
									double y = Double.parseDouble(locationY);
									// String repeaterSort =
									// StringUtils.toString(userInfomation.get("repeaterSort"));
									// String userId =
									// StringUtils.toString(userInfomation.get("axisX"));
									pointList.add(addGraphic.setPoint(x, y));
									if (i == 0) {
										// testcode(120.211353, 30.372421, "1",
										// "起点", otherUserPic);
										// Message message = new Message();
										// message.what = 2;
										// message.obj =
										// GameManagerActivity.result.toString();
										// handler.sendMessage(message);
										// testcode(x, y, "1", "1",
										// otherUserPic);
										testcode(x, y, startPoint);
									}
									if (i == (AllUserInformation.size() - 1)) {
										// testcode(x, y, "4", "",
										// otherUserPic);
										// testcode(x, y, "终点");
										// testcode(x, y, "1", "1",
										// otherUserPic);
										testcode(x, y, stopPoint);
									}
								}
								graphicsLayer.addGraphic(addGraphic
										.onDrawLine(pointList));
								graphicsLayer.setVisible(true);
							}

							// addGraphic.onDrawLine();
						}
					}).start();
				}
			}
		});
	}

	/*
	 * public List<String> list() { List<String> aa = new ArrayList<String>();
	 * aa.add("name"); aa.add("1234"); aa.add("name2"); aa.add("12345");
	 * aa.add("name3"); aa.add("123456"); return aa; }
	 */

	public void test() {
		// roadAdapter adapter = new roadAdapter(context,
		// dbData.findRoad("起点编号"));
		sqlLine(dbData.duan(routeId + ""));
	}

	// 点击线路item，加载线路
	public void sqlLine(List<String> list) {
		otherUserPic = getActivity().getResources().getDrawable(
				R.drawable.point_travel);
		startPoint = getActivity().getResources().getDrawable(R.drawable.tp_1);
		stopPoint = getActivity().getResources().getDrawable(R.drawable.tp_2);
		minePic = getActivity().getResources().getDrawable(
				R.drawable.location_pic);
		dev = getActivity().getResources().getDrawable(R.drawable.dev);
		mapView.addLayer(graphicsLayer);
		for (int i = 0; i < list.size(); i++) {
			graphicsLayer.addGraphic(addGraphic.addLine(list.get(i)));
		}
		json("geometry.json");
		graphicsLayer.setVisible(true);
	}

	public void testcode(double x, double y, Drawable drawable) {
		if (x == 0.0 || y == 0.0) {
			return;
		}

		/*
		 * x=120.209591847; y=30.3809260150001;
		 */
		PictureMarkerSymbol pic = new PictureMarkerSymbol(drawable);
		CompositeSymbol compositeSymbolPolygon = new CompositeSymbol();
		compositeSymbolPolygon.add(pic);
		Point mapPoint = latAndlonToMapPoint(x, y);
		Graphic graphic = new Graphic(mapPoint, compositeSymbolPolygon);
		pointLayer.addGraphic(graphic);
		mapView.addLayer(pointLayer);
	}

	public void testcode(double x, double y, Drawable drawable, String myPoint) {
		if (x == 0.0 || y == 0.0) {
			return;
		}

		/*
		 * x=120.209591847; y=30.3809260150001;
		 */
		PictureMarkerSymbol pic = new PictureMarkerSymbol(drawable);
		CompositeSymbol compositeSymbolPolygon = new CompositeSymbol();
		compositeSymbolPolygon.add(pic);
		Point mapPoint = latAndlonToMapPoint(x, y);
		Graphic graphic = new Graphic(mapPoint, compositeSymbolPolygon);
		mypointLayer.addGraphic(graphic);
	}

	public void testcode(double x, double y, String rank, String name,
			Drawable drawable) {
		if (x == 0.0 || y == 0.0) {
			return;
		}

		/*
		 * x=120.209591847; y=30.3809260150001;
		 */
		TextDrawable nameDrawable = new TextDrawable(context);
		nameDrawable.setText(name);
		nameDrawable.setTextColor(Color.BLACK);
		nameDrawable.setTextSize(textSize(densityDPI));
		nameDrawable.setTextAlign();
		int drawableWidth = nameDrawable.getMinimumWidth();
		float width = drawableWidth / 2;
		if (name.equals("我")) {
			nameDrawable.setTextColor(Color.RED);
		}
		TextSymbol tesRank = new TextSymbol(15, rank, Color.RED);
		tesRank.setHorizontalAlignment(HorizontalAlignment.CENTER);
		tesRank.setVerticalAlignment(VerticalAlignment.MIDDLE);
		PictureMarkerSymbol pic = new PictureMarkerSymbol(drawable);
		PictureMarkerSymbol picName = new PictureMarkerSymbol(nameDrawable);
		picName.setOffsetX(width + 12.0f);
		picName.setOffsetY(7.0f);
		CompositeSymbol compositeSymbolPolygon = new CompositeSymbol();
		compositeSymbolPolygon.add(pic);
		compositeSymbolPolygon.add(tesRank);
		compositeSymbolPolygon.add(picName);
		Point mapPoint = latAndlonToMapPoint(x, y);
		Graphic graphic = new Graphic(mapPoint, compositeSymbolPolygon);
		resultLayer.addGraphic(graphic);
	}

	public float textSize(int dpi) {
		float size = 0;
		if (dpi <= 240) {
			size = 8.0f;
		} else if (240 < dpi && dpi <= 320) {
			size = 6.0f;
		} else if (320 < dpi && dpi <= 480) {
			size = 4.5f;
		} else if (dpi > 480) {
			size = 3.0f;
		}
		return size;
	}

	int count = 0;
	Utils util = new Utils();

	public class MyThread implements Runnable { // thread
		@SuppressWarnings("static-access")
		public void run() {
			while (!istag) {
				try {
					if (count == 0) {
						mypointLayer.removeAll();
						if (!Variable.myPointX.equals("")
								&& !Variable.myPointY.equals("")) {
							testcode(Double.parseDouble(Variable.myPointX),
									Double.parseDouble(Variable.myPointY),
									minePic, "");
						}
						loginByHttpClient();
						count++;
					} else {
						Thread.sleep(1000); // sleep 1000ms
						count++;
						if (count >= 20) {
							System.out.println(Variable.myPointX + "myPointX");
							mypointLayer.removeAll();
							if (!Variable.myPointX.equals("")
									&& !Variable.myPointY.equals("")) {
								testcode(Double.parseDouble(Variable.myPointX),
										Double.parseDouble(Variable.myPointY),
										minePic, "");
							}
							loginByHttpClient();
							count = 1;
						}
					}

				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 * 地理坐标转投影坐标
	 */
	public Point latAndlonToMapPoint(double x, double y) {
		Point point = new Point(x, y);
		Point mapPoint = (Point) GeometryEngine.project(point,
				SpatialReference.create(4326), mapView.getSpatialReference());
		return mapPoint;
	}

	@SuppressWarnings("unused")
	private boolean isWorked(String className) {
		ActivityManager myManager = (ActivityManager) getActivity()
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(30);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(className)) {
				return true;
			}
		}
		return false;
	}

	// 新建Handler的对象，在这里接收Message，然后更新TextView控件的内容
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				resultLayer.removeAll();
				IteratorMap(rankingMap);
				break;
			}
		}
	};

	private void loginByHttpClient() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address
				+ "/terminal/eventApplyUserVerify";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("out_msg", params()));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				@SuppressWarnings("unused")
				HttpEntity entity1 = response.getEntity();
				String is = EntityUtils.toString(response.getEntity(), "UTF-8");
				byte[] outMsgBytes = is.getBytes("UTF-8");
				byte[] contentBytes = Base64.decodeBase64(outMsgBytes);
				GameManagerActivity.result = new String(contentBytes, "UTF-8");
				System.out.println(GameManagerActivity.result);
				list.clear();
				mineUserid = sp.getString("userid", "");

				rankingMap = new HashMap<String, List<String>>();
				HashMap<String, Object> result_map = StringChangeUtils
						.toObject(GameManagerActivity.result, HashMap.class);
				HashMap<String, Object> result_data = StringChangeUtils
						.toObject(result_map.get("result_data").toString(),
								HashMap.class);
				Object result_obj = result_data.get("result");
				List<String> AllUserInformation = (List<String>) result_obj;
				int userCount = AllUserInformation.size();
				if (userCount == 0) {
					return;
				}
				for (int i = 0; i < AllUserInformation.size(); i++) {
					HashMap<String, Object> userInfomation = StringChangeUtils
							.toObject(AllUserInformation.get(i), HashMap.class);
					String userId = StringUtils.toString(userInfomation
							.get("userId"));//
					String loacation_x = StringUtils.toString(userInfomation
							.get("axis_x"));// x 坐标
					String loacation_y = StringUtils.toString(userInfomation
							.get("axis_y"));// y 坐标
					String userName = StringUtils.toString(userInfomation
							.get("userName"));// user name
					/*
					 * String eventTop = StringUtils.toString(userInfomation
					 * .get("eventTop"));// 排名
					 */
					String eventTime = StringUtils.toString(userInfomation
							.get("eventTime"));// 排名
					String code = StringUtils.toString(userInfomation
							.get("code"));//
					if (userId.equals(mineUserid)) {
						mineLocation_x = loacation_x;
						mineLocation_y = loacation_y;
					}
					/*
					 * code000表示有成绩999表示无成绩
					 */
					if (!code.equals("999") && eventTime != null) {
						double eventTop = Double.parseDouble(eventTime);
						NewInfo info = new NewInfo(userName, loacation_x,
								loacation_y, userId, eventTop);
						list.add(info);
					}
					/*
					 * if (!code.equals("999")) { str.add(eventTop);
					 * str.add(userName); str.add(loacation_x);
					 * str.add(loacation_y); rankingMap.put(userId, str); }
					 */}

				Comparator comp = new Comparator() {
					public int compare(Object o1, Object o2) {
						NewInfo p1 = (NewInfo) o1;
						NewInfo p2 = (NewInfo) o2;
						if (p1.getString5() < p2.getString5())
							return -1;
						else if (p1.getString5() == p2.getString5())
							return 0;
						else if (p1.getString5() > p2.getString5())
							return 1;
						return 0;
					}
				};
				Collections.sort(list, comp);
				rankingMap.clear();
				for (int i = 0; i < list.size(); i++) {
					List<String> str = new ArrayList<String>();
					str.add(i + 1 + "");
					str.add(list.get(i).getString1());
					str.add(list.get(i).getString2());
					str.add(list.get(i).getString3());
					rankingMap.put(list.get(i).getString4(), str);
				}
				Message message = new Message();
				message.what = 1;
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}
	}

	public String code = "";
	private String params = "";
	private String key = ".5Xf_01KXd352s177Jx3wxXc074poII";
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	private String time = format.format(new Date());
	private String type = "android";
	private String sign = MD5Util.MD5(time + type + key);
	public String data = "";
	public String partner = "eventApplyUserVerify";
	public String key2 = "eventApplyUserVerify";
	private Thread thread;
	private Drawable otherUserPic;
	private Drawable minePic;
	private Drawable dev;

	public String params() {
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		// 方法名称
		code = "getUserEventResult";
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		paramsMap.put("eventId", GameManagerActivity.eventId);// 赛事Id现在测试写的1
		paramsMap.put("repeaterSn", sp.getString("repeaterSn", ""));
		paramsMap.put("deviceSn", sp.getString("deviceSn", ""));
		data = StringChangeUtils.toJson(paramsMap);
		sign = StringChangeUtils.md5to32(data + key2);
		Map<String, Object> paramsMap2 = new HashMap<String, Object>();
		paramsMap2.put("partner", partner);
		paramsMap2.put("code", code);
		paramsMap2.put("key", key);
		paramsMap2.put("data", data);
		paramsMap2.put("sign", sign);
		return params = StringChangeUtils.toJson(paramsMap2);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		istag = true;
	}

	/**
	 * 解析json
	 * 
	 * @param str
	 */

	/**
	 * 遍历map集合
	 */
	@SuppressWarnings("unchecked")
	public void IteratorMap(Map<String, List<String>> rankingMap) {

		int userCount = rankingMap.size();// 成绩列表总人数
		int mineRank = -1;
		for (Entry<String, List<String>> entry : rankingMap.entrySet()) {
			String userid = entry.getKey();// userid
			List<String> list = (List<String>) entry.getValue();
			if (mineUserid.equals(userid)) {
				mineRank = Integer.parseInt(list.get(0));
				break;
			}
		}
		for (Entry<String, List<String>> entry : rankingMap.entrySet()) {
			// String userid = entry.getKey();// userid
			List<String> list = (List<String>) entry.getValue();
			// if (mineUserid.equals(userid)) {
			// mineRank = Integer.parseInt(list.get(0));
			// }
			String rank = list.get(0);// user 名次
			int intrank = Integer.parseInt(rank);
			String username = list.get(1);// user name
			String x = list.get(2);// user location_x
			String y = list.get(3);// user location_y
			// System.out.println(" Key is user_id= " + entry.getKey()
			// +"\t username=:"+username+"\t locationx=:"+x+"\t locationy=:"+y+"\t rank=:"+rank);
			// 成绩列表是否包含当前登录用户
			if (rankingMap.containsKey(mineUserid)) {// 我在排名内
				if (userCount > 15) {// 总人数》15
					if (mineRank > 13 && userCount > (mineRank + 2)) {// 我的排名>13，总人数>我的排名+2,显示前10名和我的前2，后2名
						if (((mineRank - 2) <= intrank
								&& intrank <= (mineRank + 2) && intrank != mineRank)
								|| intrank <= 10) {
							testcode(Double.parseDouble(x),
									Double.parseDouble(y), rank, username,
									otherUserPic);
						} else if (intrank == mineRank) {
							// testcode(Double.parseDouble(x),
							// Double.parseDouble(y), mineRank + "", "我",
							// minePic);
						}
					} else if (mineRank > 13 && userCount <= (mineRank + 2)) {// 我的排名>13，总人数<=我的排名+2,显示前10名和后5名
						if ((intrank > (userCount - 5) || intrank <= 10)
								&& intrank != mineRank) {
							testcode(Double.parseDouble(x),
									Double.parseDouble(y), rank, username,
									otherUserPic);
						} else if (intrank == mineRank) {
							// testcode(Double.parseDouble(x),
							// Double.parseDouble(y), mineRank + "", "我",
							// minePic);
						}

					} else if (mineRank > 10 && mineRank <= 13) {// 我在排名内，我的排名<mineRank（我的排名）<=13，显示前10名
						if (intrank <= 15 && intrank != mineRank) {
							testcode(Double.parseDouble(x),
									Double.parseDouble(y), rank, username,
									otherUserPic);
						} else if (intrank == mineRank) {
							// testcode(Double.parseDouble(x),
							// Double.parseDouble(y), mineRank + "", "我",
							// minePic);
						}
					} else if (mineRank <= 10) {// 我在排名内，我的排名《=10，显示前10名
						if (intrank <= 10 && mineRank != intrank) {
							testcode(Double.parseDouble(x),
									Double.parseDouble(y), rank, username,
									otherUserPic);
						} else if (mineRank == intrank) {
							// testcode(Double.parseDouble(x),
							// Double.parseDouble(y), mineRank + "", "我",
							// minePic);
						}
					}
				} else {// 我在排名内，总人数《=15，全部显示
					if (intrank == mineRank) {
						// testcode(Double.parseDouble(x),
						// Double.parseDouble(y),
						// mineRank + "", "我", minePic);
					} else {
						testcode(Double.parseDouble(x), Double.parseDouble(y),
								rank, username, otherUserPic);
					}
				}
			} else {// 我不在排名内
				if (mineRank == -1) {// 我不在排名内，显示自己位置
					// testcode(Double.parseDouble(mineLocation_x),
					// Double.parseDouble(mineLocation_y), " ", "我",
					// minePic);
					mineRank--;
				}
				if (intrank <= 10 && mineRank == -2) {// 我不在排名内，前10名
					testcode(Double.parseDouble(x), Double.parseDouble(y),
							rank, username, otherUserPic);
				}
			}

		}
	}

	List<Map<String, Object>> Scenic;
	private AddGraphic addGraphic;

	public void json(String name) {
		String jsonStr = AppJsonFileReader.getJson(getActivity(), name);
		Scenic = AppJsonFileReader.getGeometryPoint(jsonStr);
		for (int i = 0; i < Scenic.size(); i++) {
			graphicsLayer.addGraphic(addGraphic.addPicture(dev, Scenic.get(i)));
		}
	}

	public void DefaultTrailShapefile() {
		String shpPath = getSDPath() + "/shapfile/trailRoad/trail.shp";
		try {
			ShapefileFeatureTable shapefileFeatureTable = new ShapefileFeatureTable(
					shpPath);
			FeatureLayer defaultfeatureLayertrail = new FeatureLayer(
					shapefileFeatureTable);
			Symbol symbol = new SimpleLineSymbol(getResources().getColor(
					R.color.trailRoadColor), 3);
			// 骑行道颜色 #E69800
			Renderer renderer = new SimpleRenderer(symbol);
			defaultfeatureLayertrail.setRenderer(renderer);
			mapView.addLayer(defaultfeatureLayertrail);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public String getSDPath() {
		File sdDir = null;
		// 判断SD卡是否存在
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取根目录
		}
		return sdDir.toString();
	}
}
