package com.smart.gtstrvl;

import com.example.mountaintravel.base.BaseActivity;
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 android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
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.WindowManager;
import android.view.View.OnClickListener;
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.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

public class VirtualRoadActivity extends BaseActivity implements
		OnClickListener {
	private WebView road_webview;
	private static final String TAG = "VirtualRoadActivity";
	private String url = "";
	private RelativeLayout virtual_relative;
	private LoadingView virtual_loadingview;
	private SharedPreferences sp;
	LinearLayout virtual_layout;
	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_virtual_road);
		initTitleBar("添加虚拟赛事");
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		road_webview = (WebView) findViewById(R.id.road_webview);
		virtual_layout = (LinearLayout) findViewById(R.id.virtual_layout);
		addview();
		WebSettings wSet = road_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		road_webview.getSettings().setDomStorageEnabled(false);
		road_webview.getSettings().setAppCacheEnabled(false);
		url = "http://" + Variable.address + "/terminal/addevent?sesskey="
				+ sp.getString("sesskey", "");
		// 设置 Application Caches 缓存目录
		road_webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				
				if (url.contains("error?err=1")
						&& !url.contains("error?err=11")) {
					ToastUtil.show(VirtualRoadActivity.this, "请先登录");
					startActivity(LoginActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				}
				if (url.contains("error?err=10")) {
					ToastUtil.show(VirtualRoadActivity.this, "请先登录");
					startActivity(LoginActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				}
//				if (url.contains("error?err=3")) {
//					AlertDialog isExit = new AlertDialog.Builder(
//							VirtualRoadActivity.this).create();
//					isExit.setMessage("暂无绑定设备，去绑定我的登山设备");
//					// 添加选择按钮并注册监听
//					isExit.setButton("确定", listener);
//					isExit.setButton2("取消", listener);
//					isExit.setCancelable(false);
//					// 显示对话框
//					isExit.show();
//					return true;
//				}
				if (url.contains("error?err=2")) {

					ToastUtil.show(VirtualRoadActivity.this, "请先登录");
					startActivity(LoginActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				}
				if (url.contains("error?err=11")) {
					ToastUtil.show(VirtualRoadActivity.this, "请先登录");
					startActivity(LoginActivity.class, R.anim.left_out,
							R.anim.right_in);
					return true;
				}
				if (url.contains("error?err=9")) {
					AlertDialog isExit = new AlertDialog.Builder(
							VirtualRoadActivity.this).create();
					isExit.setMessage("个人信息不完整，去完善我的基本信息");
					isExit.setButton("确定", listener2);
					isExit.setButton2("取消", listener2);
					isExit.setCancelable(false);
					isExit.show();
					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(VirtualRoadActivity.this, "创建成功");
					url = "http://" + Variable.address
							+ "/terminal/memberindex?sesskey="
							+ sp.getString("sesskey", "");
					road_webview.loadUrl(url);
					startActivity(GameListActivity.class, R.anim.left_out,
							R.anim.right_in);
					finish();
					return true;
				}

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

					return true;
				} else if (url.contains("error?err=5")) {
					ToastUtil.show(VirtualRoadActivity.this,
							"您已超出赛事的允许报名时间,请选择其它赛事报名");

					return true;
				} else if (url.contains("error?err=6")) {
					ToastUtil.show(VirtualRoadActivity.this, "缺少必要参数请填写完整");

					return true;
				} else if (url.contains("terminal/adddevice")) {
					startActivity(BindActivity.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
				super.onReceivedError(view, errorCode, description, failingUrl);
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(VirtualRoadActivity.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(VirtualRoadActivity.this, "网络异常，请检查网络");
				} 
				flag=false;
				view.loadUrl("file:///android_asset/loading.html");

			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				flag=false;
				road_webview.setVisibility(View.VISIBLE);
				virtual_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				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) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (i > 60) {
								runOnUiThread( new Runnable() {
									public void run() {
										road_webview.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});
								
							}

						}
					}

				}.start();
				virtual_relative.setVisibility(View.VISIBLE);
				road_webview.setVisibility(View.GONE);
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, url);
			}

		});

		
		road_webview.loadUrl(url);
	}

//	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
//		public void onClick(DialogInterface dialog, int which) {
//			switch (which) {
//			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
//				Intent intent = new Intent(VirtualRoadActivity.this,
//						BindActivity.class);
//				startActivityForResult(intent, 1);
//				break;
//			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
//				finish();
//				break;
//			}
//		}
//	};
	DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Intent intent = new Intent(VirtualRoadActivity.this,
						PinfoActivity.class);

				startActivityForResult(intent, 2);
				sp.edit().putBoolean("virtual", true).commit();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				finish();
				break;

			}
		}
	};

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

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

	}

	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) {
								if (sp.getBoolean("virtualPinfo", false)) {
									sp.edit().putBoolean("virtualPinfo", false)
											.commit();
									startActivity(MainActivity.class);
									return;
								}
								finish();
							}
						}
					});
		}
	}

	// 创建赛事完善信息成功返回属性主界面的昵称
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 创建退出对话框
			if (sp.getBoolean("virtualPinfo", false)) {
				sp.edit().putBoolean("virtualPinfo", false).commit();
				startActivity(MainActivity.class);
				return true;
			}
			finish();

		}

		return false;

	}

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

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

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

	}

	@SuppressLint("NewApi")
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		flag=false;
		sp.edit().putBoolean("bind", false).commit();
		if (road_webview != null) {
			virtual_layout.removeView(road_webview);
			road_webview.removeAllViews();
			road_webview.onPause();
			road_webview.destroy();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			if (!sp.getBoolean("bind", false)) {
				finish();
				return;
			}
			road_webview.loadUrl(url);
			break;
		case 2:
			road_webview.loadUrl(url);
			break;
		}
	}
}
