package com.example.mountaintravel.fragment;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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.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.ToastUtil;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;
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.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;

@SuppressLint({ "ValidFragment", "NewApi" })
public class MyCreateFragment extends Fragment implements OnClickListener {
	private Context context;
	private GamelistAdapter adapter2;
	private ListView listView;
	private static final String TAG = "FragmentPage2";
	private ArrayList<GameInfo> list2 = new ArrayList<GameInfo>();
	private int positiontrue = 0;
	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 = "";
	private RelativeLayout frag2_relative;
	private SharedPreferences sp;
	private LoadingView frag2_loadingview;
	private ArrayList<String> listinfo2 = new ArrayList<String>();
	private boolean has_permission = false;
	private boolean has_permission2 = false;

	public MyCreateFragment(Context context) {
		// TODO Auto-generated constructor stub
		this.context = context;
	}

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

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

	public void onPause() {
		// TODO Auto-generated method stub
		frag2_loadingview.stop();
		super.onPause();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		sp = context.getSharedPreferences("variable", Context.MODE_PRIVATE);
		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 {
				list2.clear();
				if (adapter2 != null) {
					adapter2.clear();
				}
				frag2_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")) {
							auLogin();
						}
						if (code.equals("4008")) {
							loginByHttpClient(4);
							// 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) {
				list2.clear();
				if (adapter2 != null) {
					adapter2.clear();
				}
				frag2_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")) {
							auLogin();
						}
						if (code.equals("4008")) {
							loginByHttpClient(4);
							// 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);

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

	private void setView() {
		// TODO Auto-generated method stub

		addview();

		listView = (ListView) getView().findViewById(R.id.gamelist_lv2);
		adapter2 = new GamelistAdapter(context);
		list2.clear();
		adapter2.clear();
		frag2_relative.setVisibility(View.VISIBLE);
		listView.setVisibility(View.GONE);
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				loginByHttpClient(1);
			}
		}).start();

	}

	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(4);
				} else {
					Intent intent = new Intent(context, LoginActivity.class);
					ToastUtil.show(context, "请登录");
				}

			}

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

	}

	private void loginByHttpClientGet() {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/islogin";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("weight", "80"));
			// 创建传递参数封装 实体对象
			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();
				String result = StreamTools.streamToString(is);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				// Message msg = new Message();
				// msg.obj = code;
				// msg.what = 0;
				// mHandler.sendMessage(msg);
				if (code.equals("4009")) {
					auLogin();
				} else if (code.equals("4008")) {
					loginByHttpClient(4);
					// String ifBegin=gameInfo.getIfBegin();
				}

			}

		} 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;
				frag2_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				if (obj.equals("加入有")) {
					listView.setOnItemClickListener(listener);
					adapter2.addDataList(list2);
					listView.setAdapter(adapter2);
					adapter2.notifyDataSetChanged();
					listView.setOnItemClickListener(listener);
				}
				if (obj.equals("加入空")) {
					adapter2 = null;
					listView.setOnItemClickListener(null);
					Fragment5twoAdapter adapter3 = new Fragment5twoAdapter(
							context);
					listinfo2.add("暂无信息");
					adapter3.addDataList(listinfo2);
					listView.setAdapter(adapter3);
					adapter3.notifyDataSetChanged();
					listView.setOnItemClickListener(null);
					listView.setDivider(new ColorDrawable(R.color.white_light));
				}

				break;
			case 4:
				listView.setOnItemClickListener(listener);
				frag2_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				adapter2.addDataList(list2);
				listView.setAdapter(adapter2);
				adapter2.notifyDataSetChanged();
				GameInfo gameInfo = adapter2.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 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);
					intent.putExtra("manager", manager);
					intent.putExtra("routeId", routeId);
					intent.putExtra("hour", hour);
					intent.putExtra("min", min);
					intent.putExtra("ifBegin", ifBegin);
					intent.putExtra("begintime", begintime);
					intent.putExtra("eventId", eventId);
					intent.putExtra("ss", ss);
					startActivity(intent);// weiwan
					getActivity().finish();
				}

				break;
			case 5:
				listView.setOnItemClickListener(null);
				frag2_relative.setVisibility(View.GONE);
				listView.setVisibility(View.VISIBLE);
				ToastUtil.show(context, "网络不给力，请检测网络");
				break;
			}

			super.handleMessage(msg);
		}
	};

	private void loginByHttpClient(int msgwhat) {
		// TODO Auto-generated method stub
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/usercreateevent";
		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");
				// String result = StreamTools.streamToString(is);
				JSONObject json = new JSONObject(result);
				String code = json.getString("code");
				if (code.equals("1010")) {
					JSONArray arr = json.getJSONArray("data");

					for (int i = 0; i < arr.length(); i++) {
						JSONObject temp = (JSONObject) arr.get(i);
						// String organizerName =
						// temp.getString("organizerName");
						String begintime1 = temp.getString("eventStartTime");
						String begintime = begintime1.substring(0, 10);
						String deviceSn = temp.getString("deviceSn");
						String realtime1 = temp.getString("realStartTime");
						String realtime = "null";
						String realendtime = "null";
						String realendtime1 = temp.getString("realEndTime");
						String name = temp.getString("name");
						String endTime = temp.getString("eventEndTime");
						String eventEndTime1 = endTime.substring(0, 10);
						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 eventId = temp.getString("id");
						String status=temp.getString("status");
						String routeIdgame = temp.getString("routeId");
						int routeId = Integer.parseInt(routeIdgame);
						int i2 = Integer.parseInt(begintime);
						int i3 = Integer.parseInt(eventEndTime1);
					
						if (realtime1 != "null") {
							realtime = realtime1.substring(0, 10);
						}
						if (realendtime1 != "null") {
							realendtime = realendtime1.substring(0, 10);
						}

						if (realtime1 != "null") {
							hourminfull = Variable.getStrTime2(realtime);
							hourmin = hourminfull.substring(8, 12);
							hour = hourmin.substring(0, 2);
							min = hourmin.substring(2, 4);
							ss = hourmin.substring(4);
						}
						if (realtime1 == "null") {
							hour = "null";
							min = "null";
						}

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

						// 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(sp.getString(
								"real_name", ""), eventStartTime, begintime,
								ifBegin, mileage, number, hour, min, false,
								true, name, "已通过", eventId, ss, "", routeId,deviceSn,"");
						list2.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

	}
}
