package com.example.mountaintravel.fragment;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import pl.droidsonroids.gif.GifImageView;

import com.esri.core.geometry.Point;
import com.example.mountaintravel.adapter.Fragment5twoAdapter;
import com.example.mountaintravel.adapter.GamelistAdapter;
import com.example.mountaintravel.kind.GameInfo;
import com.example.mountaintravel.util.AesTerminalUtil;
import com.example.mountaintravel.util.LoginUtil;
import com.example.mountaintravel.util.MD5Util;
import com.example.mountaintravel.util.StreamTools;
import com.example.mountaintravel.util.StringChangeUtils;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;
import com.smart.gtstrvl.BrowseMapActivity;
import com.smart.gtstrvl.GameManagerActivity;
import com.smart.gtstrvl.LoginActivity;
import com.smart.gtstrvl.MainActivity;
import com.smart.gtstrvl.MyGradeActivity;
import com.smart.gtstrvl.R;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ProgressBar;

@SuppressLint({ "ValidFragment", "NewApi" })
public class JoinFragmentPage extends Fragment implements OnClickListener {
	private GamelistAdapter adapter;
	private Context context;
	private String key = ".5Xf_01KXd352s177Jx3wxXc074poII";
	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);
	private String status = "null";
	private ListView listView;
	private static final String TAG = "FragmentPage1";
	private int positiontrue = 0;
	private ArrayList<String> listinfo2 = new ArrayList<String>();
	private ArrayList<GameInfo> list = new ArrayList<GameInfo>();
	private RelativeLayout frag1_relative;
	private SharedPreferences sp;
	private LoadingView frag1_loadingview;
	int msgwhat = 1;
	private boolean has_permission = false;
	private boolean has_permission2 = false;

	public JoinFragmentPage(Context context) {
		this.context = context;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		return inflater.inflate(R.layout.fragment_1, container, false);
	}

	public void onResume() {
		// TODO Auto-generated method stub
		frag1_loadingview.start();
		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		frag1_loadingview.stop();
		super.onPause();
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		msgwhat = 1;
		setView();
		listView.setOnItemClickListener(listener);
		super.onActivityCreated(savedInstanceState);
	}

	android.widget.AdapterView.OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			positiontrue = position;
			PackageManager pkm = context.getPackageManager();
			has_permission = (PackageManager.PERMISSION_GRANTED == pkm
					.checkPermission(
							"android.permission.WRITE_EXTERNAL_STORAGE",
							"com.smart.gtstrvl"));
			has_permission2 = (PackageManager.PERMISSION_GRANTED == pkm
					.checkPermission("android.permission.ACCESS_FINE_LOCATION",
							"com.smart.gtstrvl"));
			if (has_permission && !has_permission2) {
				AlertDialog isExit = new AlertDialog.Builder(context).create();
				// 设置对话框消息
				isExit.setMessage("暂未开启位置权限,去打开位置权限?");
				// 添加选择按钮并注册监听
				isExit.setButton("确定", listener3);
				isExit.setButton2("取消", listener3);
				// 显示对话框
				isExit.show();
			} else if (!has_permission && has_permission2) {
				AlertDialog isExit = new AlertDialog.Builder(context).create();
				// 设置对话框消息
				isExit.setMessage("暂未开存储存储权限,去打开存储权限?");
				// 添加选择按钮并注册监听
				isExit.setButton("确定", listener3);
				isExit.setButton2("取消", listener3);
				// 显示对话框
				isExit.show();
			} else if (!has_permission && !has_permission2) {
				AlertDialog isExit = new AlertDialog.Builder(context).create();
				// 设置对话框消息
				isExit.setMessage("暂未开启权限,去打开权限?");
				// 添加选择按钮并注册监听
				isExit.setButton("确定", listener3);
				isExit.setButton2("取消", listener3);
				// 显示对话框
				isExit.show();
			} else {
				list.clear();
				if (adapter != null) {
					adapter.clear();
				}
				frag1_relative.setVisibility(View.VISIBLE);
				listView.setVisibility(View.GONE);
				new Thread(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						String code = LoginUtil.loginByHttpClientGet();

						if (code.equals("4009")) {
							msgwhat = 4;
							auLogin();
						} else if (code.equals("4008")) {
							msgwhat = 4;
							loginByHttpClient();
							// String ifBegin=gameInfo.getIfBegin();

						} else {
							Message message = new Message();
							message.what = 5;
							handler.sendMessage(message);
						}
					}
				}).start();

			}
		}

	};
	DialogInterface.OnClickListener listener3 = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Uri packageURI = Uri.parse("package:" + "com.smart.gtstrvl");
				Intent intent = new Intent(
						Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
						packageURI);
				startActivityForResult(intent, 10);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 10:
			if (has_permission && has_permission2) {
				list.clear();
				if (adapter != null) {
					adapter.clear();
				}
				frag1_relative.setVisibility(View.VISIBLE);
				listView.setVisibility(View.GONE);
				new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						String code = LoginUtil.loginByHttpClientGet();

						if (code.equals("4009")) {
							msgwhat = 4;
							auLogin();
						} else if (code.equals("4008")) {
							msgwhat = 4;
							loginByHttpClient();
							// String ifBegin=gameInfo.getIfBegin();
						} else {
							Message message = new Message();
							message.what = 5;
							handler.sendMessage(message);
						}
					}
				}).start();

			}
			break;

		default:
			break;
		}
	};

	@SuppressLint("NewApi")
	public void addview() {
		WindowManager manager = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getRealMetrics(outMetrics);

		frag1_relative = (RelativeLayout) getView().findViewById(
				R.id.frag1_relative);
		frag1_loadingview = new LoadingView(context, outMetrics.widthPixels);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, 6);
		// lp.addRule(RelativeLayout.ALIGN_BASELINE);
		frag1_relative.setOnClickListener(this);
		// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		frag1_relative.addView(frag1_loadingview, lp);

	}

	private void setView() {
		// TODO Auto-generated method stub
		addview();
		listView = (ListView) getView().findViewById(R.id.gamelist_lv);
		adapter = new GamelistAdapter(context);
		list.clear();
		adapter.clear();
		frag1_relative.setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				String code = LoginUtil.loginByHttpClientGet();
				if (code.equals("4009")) {
					msgwhat = 1;
					auLogin();

				} else if (code.equals("4008")) {
					msgwhat = 1;
					loginByHttpClient();
					// String ifBegin=gameInfo.getIfBegin();

				} else {
					Message message = new Message();
					message.what = 5;
					handler.sendMessage(message);
				}
			}
		}).start();

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		listView.setOnItemClickListener(null);
	}

	private void auLogin() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/login";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("type", type));
			parameters.add(new BasicNameValuePair("time", time));
			parameters.add(new BasicNameValuePair("sign", sign));
			parameters.add(new BasicNameValuePair("name", sp.getString(
					"userName", "")));
			//login_type表示登录类型现在默认是2表示手机登录
			parameters.add(new BasicNameValuePair("login_type", "2"));
			parameters.add(new BasicNameValuePair("pwds", sp.getString(
					"userPass", "")));
			parameters.add(new BasicNameValuePair("origin", "phone"));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			if ( !Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
																// //在浏览器中敲一下回车

			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				InputStream is = response.getEntity().getContent();
				int b = 0;
				StringBuffer sb = new StringBuffer();
				while ((b = is.read()) != -1) {
					sb.append((char) b);
				}

				String result = sb.toString();
				JSONObject json = new JSONObject(result);
				status = json.getString("status");
				sp.edit().putString("sesskey", json.getString("sesskey"))
						.commit();
				Map<String, Object> map = AesTerminalUtil
						.gtsApiAesDecryptToMap(json.getString("sesskey"));
				sp.edit().putString("nick_name", (String) map.get("nick_name"))
						.commit();
				//status=9002表示接口回传成功9003表示失败
				if (status.equals("9002")) {
					loginByHttpClient();
				} else {

					ToastUtil.show(context, "获取信息失败请重新登录");
				}

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	final Handler handler = new Handler() { // handle
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String obj = (String) msg.obj;
				frag1_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				if (obj.equals("加入有")) {
					listView.setOnItemClickListener(listener);
					adapter.addDataList(list);
					listView.setAdapter(adapter);
					adapter.notifyDataSetChanged();
					listView.setOnItemClickListener(listener);
				}
				if (obj.equals("加入空")) {
					listView.setOnItemClickListener(null);
					adapter = null;
					Fragment5twoAdapter adapter2 = new Fragment5twoAdapter(
							context);
					listinfo2.add("暂无信息");
					adapter2.addDataList(listinfo2);
					listView.setAdapter(adapter2);
					adapter2.notifyDataSetChanged();
					listView.setOnItemClickListener(null);
					listView.setDivider(new ColorDrawable(R.color.white_light));
				}

				break;
			case 4:
				listView.setOnItemClickListener(listener);
				frag1_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				adapter.addDataList(list);
				listView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				GameInfo gameInfo = adapter.getItem(positiontrue);
				String ifBegin = gameInfo.getIfBegin();
				String begintime = gameInfo.getBegintime();
				String eventId = gameInfo.getEventId();
				String deviceSn = gameInfo.getDeviceSn();
				sp.edit().putString("deviceSn", deviceSn).commit();
				int routeId = gameInfo.getRouteId();
				boolean official = gameInfo.getOfficial();
				boolean manager = gameInfo.getManager();
				
				String roadLine = gameInfo.getRoadLine();
				String hour = gameInfo.getHour();
				String min = gameInfo.getMin();
				String ss = gameInfo.getSs();
				if (ifBegin.equals("已结束")) {

					Intent intent = new Intent(context, MyGradeActivity.class);
					intent.putExtra("eventId", eventId);
					startActivity(intent);
				}
				if (ifBegin.equals("未开始") || ifBegin.equals("已开始")) {
					Intent intent = new Intent(context,
							GameManagerActivity.class);
					intent.putExtra("official", official);
					sp.edit().putInt("routeId", routeId).commit();
					intent.putExtra("manager", manager);
					intent.putExtra("hour", hour);
					intent.putExtra("min", min);
					intent.putExtra("ifBegin", ifBegin);
					intent.putExtra("begintime", begintime);
					intent.putExtra("eventId", eventId);
					intent.putExtra("ss", ss);
					if (!roadLine.equals("")) {
						sp.edit().putString("parameter", roadLine).commit();
					}
					startActivity(intent);
					getActivity().finish();
				}
				break;
			case 5:
				listView.setOnItemClickListener(null);
				frag1_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				ToastUtil.show(context, "网络不给力，请检测网络");
				break;
			}

			super.handleMessage(msg);
		}
	};

	private void loginByHttpClient() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/userapplyevent";
		System.out.println(uri);
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("apply_status", "1"));
			// 创建传递参数封装 实体对象
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters,
					"UTF-8");// 设置传递参数的编码
			// 把实体对象存入到httpPost对象中
			httpPost.setEntity(entity);
			if ( !Variable.JSESSIONID.equals("")) {
				httpPost.setHeader("Cookie", "JSESSIONID="
						+ Variable.JSESSIONID);
			}
			// 3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例
			HttpResponse response = client.execute(httpPost); // HttpUriRequest的后代对象
			if (response.getStatusLine().getStatusCode() == 200) {
				CookieStore mCookieStore = client.getCookieStore();
				List<Cookie> cookies = mCookieStore.getCookies();
				for (int i = 0; i < cookies.size(); i++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					if ("JSESSIONID".equals(cookies.get(i).getName())) {
						Variable.JSESSIONID = cookies.get(i).getValue();
						break;
					}
				}
				HttpEntity entity1 = response.getEntity();
				String result = EntityUtils.toString(response.getEntity(),
						
						"UTF-8");
				System.out.println(result);
				// String result = StreamTools.streamToString(is);
				// save(result);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				//code=1010表示有赛事，1009表示无赛事
				if (code.equals("1010")) {
					JSONArray arr = json.getJSONArray("data");
					if (arr.length() == 0) {
						GameInfo gameInfo = new GameInfo("", "", "", "", "",
								"", "", "", true, true, "", "", "", "", "", 0,
								"","");
						list.add(gameInfo);
						Message message = new Message();
						message.what = 1;
						message.obj = "加入空";
						handler.sendMessage(message);
						return;
					}
					for (int i = 0; i < arr.length(); i++) {
						
						JSONObject temp = (JSONObject) arr.get(i);
					
						String organizerName = temp.getString("organizerName");
						String deviceSn = temp.getString("deviceSn");
						String begintime1 = temp.getString("eventStartTime");
						String begintime = begintime1.substring(0, 10);
						String organizerId = temp.getString("organizerId");
						String eventName = temp.getString("eventName");
						String realtime1 = temp.getString("realStartTime");
						String realtime = "null";
						String routeIdgame = temp.getString("routeId");
						int routeId = Integer.parseInt(routeIdgame);
						String realendtime = "null";
						boolean manager = false;
						boolean official = false;
						String roadLine="";
						if (organizerId.equals(sp.getString("userid", ""))) {
							manager = true;
							official = false;
						}
						String eventType = temp.getString("eventType");

						if (eventType.equals("1") || eventType.equals("0")) {
							manager = false;
							official = false;
							roadLine=temp.toString();
						}
						
						if (eventType.equals("2")
								&& !organizerId.equals(sp.getString("userid",
										""))) {
							manager = false;
							official = false;
						}
						String realendtime1 = temp.getString("realEndTime");
						String endTime = temp.getString("eventEndTime");
						String eventEndTime1 = endTime.substring(0, 10);
						String eventEndTime = Variable
								.getStrTime(eventEndTime1);
						String hourminfull = Variable.getStrTime2(begintime);
						String hourmin = hourminfull.substring(8, 12);
						String hour = hourmin.substring(0, 2);
						String min = hourmin.substring(2, 4);
						String ss = hourmin.substring(4);
						String eventStartTime = Variable.getStrTime(begintime);
						String mileage = temp.getString("mileage");
						String number = temp.getString("number");
						String ifBegin = "null";
						String eventStatus = temp.getString("eventStatus");
						String eventId = temp.getString("eventId");
						int i2 = Integer.parseInt(begintime);
						int i3 = Integer.parseInt(eventEndTime1);
						if (official) {
							hourminfull = Variable.getStrTime2(begintime);
							hourmin = hourminfull.substring(8, 12);
							hour = hourmin.substring(0, 2);
							min = hourmin.substring(2, 4);
							ss = hourmin.substring(4);

							if (eventStatus.equals("0")) {
								ifBegin = "未开始";
							}
							if (eventStatus.equals("1")) {
								ifBegin = "已开始";
							}
							if (eventStatus.equals("2")) {
								ifBegin = "已结束";
							}

						}
						if (realtime1 != "null") {
							realtime = realtime1.substring(0, 10);
						}
						if (realendtime1 != "null") {
							realendtime = realendtime1.substring(0, 10);
						}
						if (!official) {
							if (realtime1 != "null") {
								hourminfull = Variable.getStrTime2(realtime);
								
								hourmin = hourminfull.substring(8, 14);
								hour = hourmin.substring(0, 2);
								min = hourmin.substring(2, 4);
								ss = hourmin.substring(4);
							}
							if (eventStatus.equals("0")) {
								ifBegin = "未开始";
							}
							if (eventStatus.equals("1")) {
								ifBegin = "已开始";
							}
							if (eventStatus.equals("2")) {
								ifBegin = "已结束";
							}
							if (realtime1 == "null") {
								hour = "null";
								min = "null";
							}
						}
						// String
						// url="http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=手表图片&step_word=&pn=2&spn=0&di=70336562890&pi=&rn=1&tn=baiduimagedetail&is=&istype=0&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=undefined&cs=755351398%2C3296742296&os=122229139%2C196038751&simid=3472567391%2C372064935&adpicid=0&ln=1978&fr=&fmq=1452589480916_R&ic=undefined&s=undefined&se=&sme=&tab=0&width=&height=&face=undefined&ist=&jit=&cg=&bdtype=0&objurl=http%3A%2F%2Fpic28.nipic.com%2F20130425%2F8952533_135144395000_2.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3Fooo_z%26e3Bgtrtv_z%26e3Bv54AzdH3Ffi5oAzdH3F0l99l9m_z%26e3Bip4s&gsm=0";
						GameInfo gameInfo = new GameInfo(organizerName,
								eventStartTime, begintime, ifBegin, mileage,
								number, hour, min, official, manager,
								eventName, "已通过", eventId, ss, "", routeId,
								deviceSn,roadLine);
						list.add(gameInfo);
					}
					Message message = new Message();
					message.what = msgwhat;
					message.obj = "加入有";
					handler.sendMessage(message);
				} else if (code.equals("1009")) {
					Message message = new Message();
					message.what = 1;
					message.obj = "加入空";
					handler.sendMessage(message);
				}
			} else {
				Message message = new Message();
				message.what = 1;
				message.obj = "加入空";
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Message message = new Message();
			message.what = 5;
			handler.sendMessage(message);
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}
