package com.smart.gtstrvl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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 com.example.mountaintravel.base.BaseActivity;
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.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Rect;
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.ViewTreeObserver;
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.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class ScenicActivity extends BaseActivity implements OnClickListener {
	private WebView scenic_webview;
	private static final String TAG = "ScenicActivity";
	private String url = "";
	private RelativeLayout scenic_relative;
	private LoadingView scenic_loadingview;
	private SharedPreferences sp;
	RelativeLayout scenic_layout;
	private String id = "";
	private String imgUrl = "";
	private String keyword = "";
	private String name = "";
	TextView scenic_tv;
	private String phone = "";
	private ImageView main_leftivback;
	private boolean flag = true;
	private View rootView;// activity的根视图
	boolean has_permission = false;
	boolean has_permission2 = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
			// 透明状态栏
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			/*
			 * getWindow().addFlags(
			 * WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			 */
			// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			setContentView(R.layout.activity_scenic);
		} else {
			getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
			setContentView(R.layout.activity_scenic2);
		}
		addview();
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		scenic_tv = (TextView) findViewById(R.id.scenic_tv);
		main_leftivback = (ImageView) findViewById(R.id.main_leftivback);
		main_leftivback.setOnClickListener(this);
		Intent intent = getIntent();
		String url = intent.getStringExtra("scenic");
		int nameId = StringUtils.indexOf(url, "name=");
		id = url.substring(url.indexOf("=") + 1, url.indexOf("&name"));
		name = url.substring(url.indexOf("name=") + 5, url.indexOf("&imgUrl"));
		imgUrl = url.substring(url.indexOf("imgUrl=") + 7,
				url.indexOf("&keyword"));
		if (url.contains("sesskey")) {
			keyword = url.substring(url.indexOf("keyword=") + 8,
					url.indexOf("&sesskey"));

		} else {
			int keywordId = StringUtils.indexOf(url, "keyword=");
			keyword = url.substring(keywordId + 8);

		}
		if (!url.contains("sesskey")) {
			url = url + "&sesskey=" + sp.getString("sesskey", "");
		}
		if (keyword.equals("")) {
			scenic_tv.setText(name);
		} else {
			scenic_tv.setText(name + "(" + keyword + ")");
		}

		// url="https://www.baidu.com/";
		// url="http://gwms.517gts.com/terminal/scenic/area_info?id=401&name=%E7%9A%8B%E4%BA%AD&imgUrl=/upload/scenicArea/1468483654477_10.jpg,&sesskey=4B96miX1kGI%20e3RW6OF/aK/vdyzyPam7s1a4ertIa1kM8B4aT2ig%2041U75ixt3P39Qw5ziAJU1eN%20Ydv9xiLrogXJzU23hJH5Zgk9GVP8Dc1mcVOXK%206bCRWwmlr6/4VVc2D%20yhU2F7J%20611aQmeuw6Bqm3jM9PSZRdf22d88XJ6Wdn4irb%20hmoFThavJz%20bZ/xN4mgefl5vKplXkjlAW33Tk%20k68b5MbhE9tYcQKPuVH9kJFjHBB72uIXWV9LDcrYkdFSzeXeb%20oNmUTymFvoZYAFS0mvUKwwc7SuVaZZO7D6z6Z3rrv8nyYwy52TKFKBgtwXAldSYBx18TPrJf5fk5mtph1V7X2Qo4HamXXRHJNWSzN8duwOaWdqtMvIw7";
		scenic_webview = (WebView) findViewById(R.id.scenic_webview);
		scenic_layout = (RelativeLayout) findViewById(R.id.scenic_layout);
		WebSettings wSet = scenic_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		scenic_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
		scenic_webview.getSettings().setDomStorageEnabled(false);
		scenic_webview.getSettings().setAppCacheEnabled(false);
		// 设置 Application Caches 缓存目录
		scenic_webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				scenic_loadingview.start();

				Log.d(TAG, url);
				// 拨打电话
				if (url.contains("area_info/phone")) {
					PackageManager pkmr = getPackageManager();
					boolean has_permissioncall = (PackageManager.PERMISSION_GRANTED == pkmr
							.checkPermission("android.permission.CALL_PHONE",
									"com.smart.gtstrvl"));
					if (!has_permissioncall) {
						if (VERSION.SDK_INT >= 23) {
							AlertDialog isExit = new AlertDialog.Builder(
									ScenicActivity.this).create();
							isExit.setMessage("暂未开启电话权限,去打开电话权限?");
							isExit.setButton("确定", listenerpower);
							isExit.setButton2("取消", listenerpower);
							isExit.show();
						} else {
							ToastUtil.show(ScenicActivity.this, "无电话权限");
						}
					} else {
						int phoneInt = StringUtils.indexOf(url, "phone=");
						phone = url.substring(phoneInt + 6);
						AlertDialog isExit = new AlertDialog.Builder(
								ScenicActivity.this).create();
						isExit.setMessage("                    " + phone);
						isExit.setButton("呼叫", listener);
						isExit.setButton2("取消", listener);
						isExit.show();
					}

					return true;
				}
				if (url.contains("/terminal/scenic/area_info?type=share")) {
					/*
					 * int imgUrlId = StringUtils.indexOf(url, "imgUrl=");
					 * imgUrl = url.substring(imgUrlId + 7);
					 * System.out.println(imgUrl + "hei");
					 */
					final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[] { SHARE_MEDIA.SINA };
					UMImage image = new UMImage(ScenicActivity.this, imgUrl);
					new ShareAction(ScenicActivity.this)
							.setDisplayList(displaylist)
							.withMedia(image)
							.withText("我正在" + name + "，分享一下美景")
							.withTargetUrl(
									"http://www.hibigoo.com/wap/html/t-index.html")
							.setListenerList(new UMShareListener() {
								@Override
								public void onResult(SHARE_MEDIA platform) {
									Toast.makeText(ScenicActivity.this,
											platform + " 分享成功啦",
											Toast.LENGTH_SHORT).show();
								}

								@Override
								public void onError(SHARE_MEDIA platform,
										Throwable t) {
									Toast.makeText(ScenicActivity.this,
											platform + " 分享失败啦",
											Toast.LENGTH_SHORT).show();
								}

								@Override
								public void onCancel(SHARE_MEDIA platform) { //
									Toast.makeText(ScenicActivity.this,
											platform + " 分享取消了",
											Toast.LENGTH_SHORT).show();
								}
							}).open();
					return true;
				}
				if (url.contains("scenic/area_info?type=ditu")) {
					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) {
						if (VERSION.SDK_INT >= 23) {
							AlertDialog isExit = new AlertDialog.Builder(
									ScenicActivity.this).create();
							// 设置对话框消息
							isExit.setMessage("暂未开启位置权限,去打开位置权限?");
							// 添加选择按钮并注册监听
							isExit.setButton("确定", listenerpower);
							isExit.setButton2("取消", listenerpower);
							// 显示对话框
							isExit.show();
						} else {
							ToastUtil.show(ScenicActivity.this, "无位置权限");
						}
					} else if (!has_permission && has_permission2) {
						if (VERSION.SDK_INT >= 23) {
							AlertDialog isExit = new AlertDialog.Builder(
									ScenicActivity.this).create();
							isExit.setMessage("暂未开存储存储权限,去打开存储权限?");
							isExit.setButton("确定", listenerpower);
							isExit.setButton2("取消", listenerpower);
							isExit.show();
						} else {
							ToastUtil.show(ScenicActivity.this, "无存储权限");
						}
					} else if (!has_permission && !has_permission2) {
						if (VERSION.SDK_INT >= 23) {
							AlertDialog isExit = new AlertDialog.Builder(
									ScenicActivity.this).create();
							isExit.setMessage("暂未开启权限,去打开权限?");
							isExit.setButton("确定", listenerpower);
							isExit.setButton2("取消", listenerpower);
							isExit.show();
						} else {
							ToastUtil.show(ScenicActivity.this, "无位置和存储权限");
						}
					} else {
						int codeId = StringUtils.indexOf(url, "code=");
						String code = url.substring(codeId + 5);
						Intent intent = new Intent(ScenicActivity.this,
								BrowseMapActivity.class);
						intent.putExtra("name", name);
						intent.putExtra("code", code);
						startActivity(intent);
						sp.edit().putBoolean("getcode", true).commit();
					}

					return true;
				}
				if (url.contains("terminal/scenic/area_info?type=favorite")) {
					if (!sp.getBoolean("isloginsuccess", false)) {
						Intent intent = new Intent(ScenicActivity.this,
								LoginActivity.class);
						sp.edit().putBoolean("comment", true).commit();
						startActivityForResult(intent, 2);
					} else {
						/*
						 * id = url.substring(url.indexOf("&id=") + 4,
						 * url.indexOf("&imgUrl")); System.out.println(id +
						 * "hei");
						 */
						new Thread(new Runnable() {
							@Override
							public void run() {
								collect();
							}

						}).start();
					}
					return true;
				}
				if (url.contains("area_info?isLogin")) {
					Intent intent = new Intent(ScenicActivity.this,
							LoginActivity.class);
					sp.edit().putBoolean("comment", true).commit();
					startActivityForResult(intent, 1);
					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(ScenicActivity.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(ScenicActivity.this, "网络异常，请检查网络");
				}
				flag = false;
				view.loadUrl("file:///android_asset/problem.html");
			}

			@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() {
										scenic_webview
												.loadUrl("file:///android_asset/problem.html");
										flag = false;
									}
								});

							}

						}
					}

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

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				flag = false;
				scenic_loadingview.stop();
				scenic_webview.setVisibility(View.VISIBLE);
				scenic_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
		});

		/*
		 * scenic_webview.setWebChromeClient(new WebChromeClient() { public void
		 * onProgressChanged(WebView view, int newProgress) {
		 * 
		 * if (newProgress == 100) { scenic_webview.setVisibility(View.VISIBLE);
		 * scenic_relative.setVisibility(View.GONE); } else {
		 * scenic_relative.setVisibility(View.VISIBLE);
		 * scenic_webview.setVisibility(View.GONE); }
		 * super.onProgressChanged(view, newProgress); } });
		 */
		scenic_webview.loadUrl(url);
		rootView = getWindow().getDecorView();

		// 监听视图树中全局布局发生改变或者视图树中的某个视图的可视状态发生改变
		rootView.getViewTreeObserver().addOnGlobalLayoutListener(
				new ViewTreeObserver.OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						// 获取当前根视图在屏幕上显示的大小
						Rect r = new Rect();
						rootView.getWindowVisibleDisplayFrame(r);
						int screenHeight = rootView.getRootView().getHeight();
						int heightDifference = screenHeight - r.bottom;
						FrameLayout.LayoutParams rl = (FrameLayout.LayoutParams) scenic_layout
								.getLayoutParams();
						rl.setMargins(0, 0, 0, heightDifference);
						// rl.setMargins(0, 863, 0, heightDifference);
						scenic_layout.requestLayout();
					}
				});
	}

	DialogInterface.OnClickListener listenerpower = 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;
			}
		}
	};

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

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

		}

		return false;

	}

	private void collect() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address
				+ "/terminal/scenic/area_favorite";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("userId", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("areaId", id));
			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++) {
					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();
				if (result.equals("000")) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ToastUtil.show(ScenicActivity.this, "收藏成功");
						}
					});
				} else if (result.equals("111")) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ToastUtil.show(ScenicActivity.this, "已经收藏过了");
						}
					});
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ToastUtil.show(ScenicActivity.this, "网络异常");
						}
					});
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					ToastUtil.show(ScenicActivity.this, "网络异常");
				}
			});
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}

	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
						+ phone));
				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);

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

	}

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

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

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.main_leftivback:
			if ((sp.getBoolean("isMyCollect", false))) {
				finish();
				return;
			}
			if ((sp.getBoolean("isloginsuccess", false))) {
				startActivity(MainActivity.class);
				return;
			}
			finish();
			break;

		}
	}

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

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case 1:
			url = scenic_webview.getUrl() + sp.getString("sesskey", "");
			scenic_webview.loadUrl(url);
			break;
		case 2:
			url = scenic_webview.getUrl() + sp.getString("sesskey", "");
			scenic_webview.loadUrl(url);
			if (sp.getBoolean("isloginsuccess", false)) {
				new Thread(new Runnable() {

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

			break;

		}
	}
}
