package com.smart.gtstrvl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import jcifs.dcerpc.msrpc.netdfs;

import org.apache.commons.codec.binary.Base64;

import com.esri.core.analysis.a;
import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.service.MyGPSservice;
import com.example.mountaintravel.util.EventinfoListener;
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.example.mountaintravel.view.TitleBarView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.bean.SHARE_MEDIA;

import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Build.VERSION;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

public class EventInfoActivity extends BaseActivity implements OnClickListener {
	private WebView eventinfo_webview;
	private SwipeRefreshLayout eventinfo_swipeLayout;
	private static final String TAG = "EventInfoActivity";
	private String url = "";
	private RelativeLayout event_relative;
	private LoadingView virtual_loadingview;
	private SharedPreferences sp;
	LinearLayout event_layout;
	EventinfoListener eventinfoListener;
	private boolean has_permission = false;
	private boolean has_permission2 = false;
	private boolean flag = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setContentView(R.layout.activity_event_info);
		initTitleBar("竞赛详情");
		// initTitleBar(R.drawable.leadback, R.drawable.add, "赛事详情",
		// mylistener);
		eventinfoListener = new EventinfoListener(this);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		eventinfo_webview = (WebView) findViewById(R.id.eventinfo_webview);
		event_layout = (LinearLayout) findViewById(R.id.event_layout);
		eventinfo_swipeLayout = (SwipeRefreshLayout) findViewById(R.id.eventinfo_swipeLayout);
		eventinfo_swipeLayout.setVisibility(View.VISIBLE);
		addview();
		WebSettings wSet = eventinfo_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		eventinfo_webview.getSettings().setDomStorageEnabled(false);
		eventinfo_webview.getSettings().setAppCacheEnabled(false);
		if (!sp.getString("eventId", "").equals("")) {
			url = "http://" + Variable.address
					+ "/terminal/event/event_info?sesskey="
					+ sp.getString("sesskey", "") + "&eventId="
					+ sp.getString("eventId", "");
		} else {
			url = "http://" + Variable.address
					+ "/terminal/event/event_info?sesskey="
					+ sp.getString("sesskey", "") + "&eventId="
					+ sp.getString("toapplyid", "");
		}

		// 设置 Application Caches 缓存目录
		eventinfo_webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(EventInfoActivity.this.CONNECTIVITY_SERVICE);
				State mobile = cwjManager.getNetworkInfo(
						ConnectivityManager.TYPE_MOBILE).getState();
				State wifi = cwjManager.getNetworkInfo(
						ConnectivityManager.TYPE_WIFI).getState();
				if (!(mobile == State.CONNECTED || mobile == State.CONNECTING
						|| wifi == State.CONNECTED || wifi == State.CONNECTING)) {
					ToastUtil.show(EventInfoActivity.this, "网络异常，请检查网络");
					return true;
				}
				virtual_loadingview.start();
				if (url.contains("error?err=1")
						&& !url.contains("error?err=11")) {
					ToastUtil.show(EventInfoActivity.this, "请先登录");
					startActivity(LoginActivity.class);
					return true;
				}
				if (url.contains("event/event_info")) {
					url = "http://" + Variable.address
							+ "/terminal/event/event_info?sesskey="
							+ sp.getString("sesskey", "") + "&eventId="
							+ sp.getString("eventId", "");
					view.loadUrl(url);
					return true;
				}
				if (url.contains("wap/event_repeater_ranking_user_info")) {
					Intent intent = new Intent(EventInfoActivity.this,
							SportInfoActivity.class);
					intent.putExtra("url", url);
					startActivity(intent);
					return true;
				}
				if (url.contains("/terminal/join_event_team?type=")) {
					int typeId = StringUtils.indexOf(url, "type=");
					String team = url.substring(typeId + 5);
					if (team.equals("notTeam")) {
						Intent intent = new Intent(EventInfoActivity.this,
								ApplyActivity.class);
						if (!sp.getString("eventId", "").equals("")) {
							intent.putExtra("eventId",
									sp.getString("eventId", ""));
						} else {
							intent.putExtra("eventId",
									sp.getString("toapplyid", ""));
						}
						startActivity(intent);
					}
					if (team.equals("haveTeam")) {
						Intent intent = new Intent(EventInfoActivity.this,
								TeamMemberActivity.class);
						if (!sp.getString("eventId", "").equals("")) {
							intent.putExtra("eventId",
									sp.getString("eventId", ""));
						} else {
							intent.putExtra("eventId",
									sp.getString("toapplyid", ""));
						}
						startActivity(intent);
					}
					if (team.equals("teamOrganizer")) {
						Intent intent = new Intent(EventInfoActivity.this,
								TeamManageActivity.class);
						if (!sp.getString("eventId", "").equals("")) {
							intent.putExtra("eventId",
									sp.getString("eventId", "杀死"));
						} else {
							intent.putExtra("eventId",
									sp.getString("toapplyid", "杀死"));
						}
						startActivity(intent);
					}
					return true;
				}
				if (url.contains("error?err=4")) {
					Toast.makeText(EventInfoActivity.this,
							"您申请的赛事存在时间上的冲突，不能申请", 1).show();
					return true;
				}
				/*
				 * 已结束赛事成绩页
				 */
				if (url.contains("terminal/eventrank")) {
					Intent intent = new Intent(EventInfoActivity.this,
							MyGradeActivity.class);
					if (!sp.getString("eventId", "").equals("")) {
						intent.putExtra("eventId", sp.getString("eventId", ""));
					} else {
						intent.putExtra("eventId",
								sp.getString("toapplyid", ""));
					}
					startActivity(intent);
					return true;
				}
				/*
				 * 竞赛首页捕捉已结束的赛事
				 */
				if (url.contains("event/event_view")
						|| url.contains("wap/event_repeater_ranking")) {
					int a = StringUtils.indexOf(url, "eventId=");
					String eventId = url.substring(a + 8);
					Intent intent = new Intent(EventInfoActivity.this,
							MyGradeActivity.class);
					intent.putExtra("eventId", eventId);
					startActivity(intent);
					return true;
				}
				if (url.contains("event/event_manage")) {
					PackageManager pkm = 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(
								EventInfoActivity.this).create();
						// 设置对话框消息
						isExit.setMessage("暂未开启位置权限,去打开位置权限?");
						// 添加选择按钮并注册监听
						isExit.setButton("确定", listener3);
						isExit.setButton2("取消", listener3);
						// 显示对话框
						isExit.show();
					} else if (!has_permission && has_permission2) {
						AlertDialog isExit = new AlertDialog.Builder(
								EventInfoActivity.this).create();
						// 设置对话框消息
						isExit.setMessage("暂未开存储存储权限,去打开存储权限?");
						// 添加选择按钮并注册监听
						isExit.setButton("确定", listener3);
						isExit.setButton2("取消", listener3);
						// 显示对话框
						isExit.show();
					} else if (!has_permission && !has_permission2) {
						AlertDialog isExit = new AlertDialog.Builder(
								EventInfoActivity.this).create();
						// 设置对话框消息
						isExit.setMessage("暂未开启权限,去打开权限?");
						// 添加选择按钮并注册监听
						isExit.setButton("确定", listener3);
						isExit.setButton2("取消", listener3);
						// 显示对话框
						isExit.show();
					} else {
						if (VERSION.SDK_INT >= 23) {
							if (isWorked("com.example.mountaintravel.service.MyGPSservice")) {
								Intent stopIntent = new Intent(EventInfoActivity.this,
										MyGPSservice.class);
								stopService(stopIntent);
							}
							if (!isWorked("com.example.mountaintravel.service.MyGPSservice")) {
								Intent startIntent = new Intent(
										EventInfoActivity.this,
										MyGPSservice.class);
								startService(startIntent);
							}
						}
						gamemanager(url);
					}

					return true;
				}
				if (url.contains("error?err=3")) {
					AlertDialog isExit = new AlertDialog.Builder(
							EventInfoActivity.this).create();
					isExit.setMessage("暂无绑定设备，去绑定我的登山设备");
					isExit.setButton("确定", listener);
					isExit.setButton2("取消", listener);
					isExit.show();
					return true;
				}
				if (url.contains("error?err=2")) {
					ToastUtil.show(EventInfoActivity.this, "请先登录");
					startActivity(LoginActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				}
				if (url.contains("error?err=11")) {
					ToastUtil.show(EventInfoActivity.this, "请先登录");
					startActivity(LoginActivity.class);
					return true;
				}
				if (url.contains("error?err=9")) {
					ToastUtil.show(EventInfoActivity.this, "请先完善用户信息");
					startActivity(PinfoActivity.class);
					return true;
				}
				if (url.contains("success?suc=1")
						|| url.contains("success?suc=2")
						|| url.contains("success?suc=4")
						|| url.contains("success?suc=5")) {
					ToastUtil.show(EventInfoActivity.this, "申请成功");
					if (url.contains("nickName")) {
						int a = StringUtils.indexOf(url, "nickName=");
						String nickName = url.substring(
								url.indexOf("nickName=") + 9,
								url.indexOf("&sex"));
						int sexId = StringUtils.indexOf(url, "sex=");
						String sex = url.substring(sexId + 4);
						if (sex.equals("0")) {
							sp.edit().putString("sex", "女").commit();
						} else {
							sp.edit().putString("sex", "男").commit();
						}
						byte[] outMsgBytes;
						try {
							outMsgBytes = nickName.getBytes("UTF-8");
							byte[] contentBytes = Base64
									.decodeBase64(outMsgBytes);
							String nick_name = new String(contentBytes, "UTF-8");
							sp.edit().putString("nick_name", nick_name)
									.commit();
							Intent intent = new Intent(EventInfoActivity.this,
									ApplyActivity.class);
							if (!sp.getString("eventId", "").equals("")) {
								intent.putExtra("eventId",
										sp.getString("eventId", ""));
							} else {
								intent.putExtra("eventId",
										sp.getString("toapplyid", ""));
							}
							startActivity(intent);
							sp.edit().putBoolean("apply", true).commit();
							return true;
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
						}

					}
					Intent intent = new Intent(EventInfoActivity.this,
							ApplyActivity.class);
					if (!sp.getString("eventId", "").equals("")) {
						intent.putExtra("eventId", sp.getString("eventId", ""));
					} else {
						intent.putExtra("eventId",
								sp.getString("toapplyid", ""));
					}
					startActivity(intent);
					sp.edit().putBoolean("apply", true).commit();
					return true;
				}

				else if (url.contains("error?err=7")) {
					ToastUtil.show(EventInfoActivity.this, "操作失败");

					return true;
				} else if (url.contains("error?err=5")) {
					ToastUtil.show(EventInfoActivity.this,
							"您已超出赛事的允许报名时间,请选择其它赛事报名");
					return true;
				} else if (url.contains("error?err=6")) {
					ToastUtil.show(EventInfoActivity.this, "缺少必要参数请填写完整");
					return true;
				} else if (url.contains("terminal/adddevice")) {
					startActivity(BindActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				} else if (url.contains("terminal/touserinfo")) {
					startActivity(PinfoActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(EventInfoActivity.this.CONNECTIVITY_SERVICE);
				State mobile = cwjManager.getNetworkInfo(
						ConnectivityManager.TYPE_MOBILE).getState();
				State wifi = cwjManager.getNetworkInfo(
						ConnectivityManager.TYPE_WIFI).getState();
				if (!(mobile == State.CONNECTED || mobile == State.CONNECTING
						|| wifi == State.CONNECTED || wifi == State.CONNECTING)) {
					ToastUtil.show(EventInfoActivity.this, "网络异常，请检查网络");
				}
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag = false;
				view.loadUrl("file:///android_asset/loading.html");

			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				flag = true;
				new Thread() {
					@Override
					public void run() {
						// super.run();
						int i = 0;
						while (flag) {
							i++;
							Log.d(TAG, i + "");
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							if (i > 60) {
								runOnUiThread(new Runnable() {
									public void run() {
										eventinfo_webview
												.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});

							}

						}
					}
				}.start();
				if (!eventinfo_swipeLayout.isRefreshing())
					eventinfo_webview.setVisibility(View.GONE);
				event_relative.setVisibility(View.VISIBLE);
				eventinfo_webview.setVisibility(View.GONE);
				eventinfo_swipeLayout.setOnClickListener(null);
				eventinfo_swipeLayout.setVisibility(View.GONE);
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, url + ",.,.,,sdasdsdsd ");

			}

			@Override
			public void onPageFinished(WebView view, String url) {
				flag = false;
				virtual_loadingview.stop();
				eventinfo_swipeLayout.setRefreshing(false);
				eventinfo_webview.setVisibility(View.VISIBLE);
				event_relative.setVisibility(View.GONE);
				event_relative.setOnClickListener(null);
				eventinfo_swipeLayout.setVisibility(View.VISIBLE);
				super.onPageFinished(view, url);
			}
		});

		eventinfo_swipeLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
					@Override
					public void onRefresh() {
						eventinfo_webview.loadUrl(url);
					}
				});

		eventinfo_webview.loadUrl(url);
	}
	private boolean isWorked(String className) {
		ActivityManager myManager = (ActivityManager) EventInfoActivity.this
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(300);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(className)) {
				return true;
			}
		}
		return false;
	}
	private void gamemanager(String url) {
		int a = StringUtils.indexOf(url, "parameter=");
		String parameter1 = url.substring(a + 10);
		String parameter;
		try {
			byte[] outMsgBytes = parameter1.getBytes("UTF-8");
			byte[] contentBytes = Base64.decodeBase64(outMsgBytes);
			parameter = new String(contentBytes, "UTF-8");
			eventinfoListener.pulldata(parameter);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序

				Intent intent = new Intent(EventInfoActivity.this,
						BindActivity.class);

				startActivityForResult(intent, 1);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;

			}
		}
	};
	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);
				startActivity(intent);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};

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

		event_relative = (RelativeLayout) findViewById(R.id.event_relative);
		virtual_loadingview = new LoadingView(getBaseContext(),
				outMetrics.widthPixels);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, 6);
		// lp.addRule(RelativeLayout.ALIGN_BASELINE);
		event_relative.setOnClickListener(this);
		// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
		event_relative.addView(virtual_loadingview, lp);

	}

	public void onResume() {
		virtual_loadingview.start();
		super.onResume();
	}

	@Override
	public void onPause() {
		virtual_loadingview.stop();
		super.onPause();
	}

	@Override
	public void onClick(View v) {

	}

	@SuppressLint("NewApi")
	@Override
	protected void onDestroy() {
		super.onDestroy();
		flag = false;
		if (eventinfo_webview != null) {
			eventinfo_swipeLayout.removeView(eventinfo_webview);
			eventinfo_webview.removeAllViews();
			eventinfo_webview.onPause();
			eventinfo_webview.destroy();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			eventinfo_webview.loadUrl(url);
			break;
		case 2:
			eventinfo_webview.loadUrl(url);
			break;
		case 10:
			gamemanager(url);
			break;
		}
	}

	public void initTitleBar(String text) {
		TitleBarView v = (TitleBarView) findViewById(R.id.titleBarView1);
		if (v != null) {
			v.initTitleBar(R.drawable.zuoback, -1, text,
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (v.getId() == R.id.left_icon) {
								startActivity(MainActivity.class);
							}
						}
					});
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(MainActivity.class);
		}
		return false;
	}
}
