package com.smart.gtstrvl;

import java.io.File;
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.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.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.graphics.Bitmap;
import android.graphics.Rect;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Environment;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
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.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

public class TextActivity extends Activity implements OnClickListener {
	private WebView wView;
	private SharedPreferences sp;
	private TextView text_tv;
	private LoadingView text_loadingview;
	private RelativeLayout text_layout;
	private RelativeLayout text_relative;
	private String strName = "";
	private String phone = "";
	private static final String TAG = "textActivity";
	private String id = "";
	private String imgUrl = "";
	private TextView text_tvtitle;
	private ImageView text_leftivback;
	private boolean flag = true;
	private View rootView;// activity的根视图
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		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.text2_layout);
		} else {
			setContentView(R.layout.text_layout);
		}
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		text_tvtitle = (TextView) findViewById(R.id.text_tvtitle);
		text_leftivback = (ImageView) findViewById(R.id.text_leftivback);
		text_leftivback.setOnClickListener(this);
		Intent intent = getIntent();
		String strCode = intent.getStringExtra("code").trim();
		strName = intent.getStringExtra("name").trim();
		/*if (strName.contains("(")) {
			strName = strName.split("\\(")[0];
		}*/
		text_tvtitle.setText(strName);
		text_tv = (TextView) findViewById(R.id.text_tv);
		wView = (WebView) findViewById(R.id.wv);
		wView.getSettings().setJavaScriptEnabled(true);
		wView.getSettings().setDomStorageEnabled(false);
		wView.getSettings().setAppCacheEnabled(false);
		wView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				text_loadingview.start();
				
				if (url.contains("scenic/area_info?type=ditu")) {
					finish();
				}
				if (url.contains("area_info/phone")) {
					int phoneInt = StringUtils.indexOf(url, "phone=");
					phone = url.substring(phoneInt + 6);
					AlertDialog isExit = new AlertDialog.Builder(
							TextActivity.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);
					final SHARE_MEDIA[] displaylist = new SHARE_MEDIA[] { SHARE_MEDIA.SINA };
					UMImage image = new UMImage(TextActivity.this, imgUrl);
					new ShareAction(TextActivity.this)
							.setDisplayList(displaylist).withMedia(image)
							.withText("我正在" + strName + "，分享一下美景")
							.setListenerList(new UMShareListener() {
								@Override
								public void onResult(SHARE_MEDIA platform) {
									Toast.makeText(TextActivity.this,
											platform + " 分享成功啦",
											Toast.LENGTH_SHORT).show();
								}

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

								@Override
								public void onCancel(SHARE_MEDIA platform) { //
									Toast.makeText(TextActivity.this,
											platform + " 分享取消了",
											Toast.LENGTH_SHORT).show();
								}
							}).open();
					return true;
				}
				if (url.contains("terminal/scenic/area_info?type=favorite")) {

					if (!sp.getBoolean("isloginsuccess", false)) {
						ToastUtil.show(TextActivity.this, "暂未登录");
					} else {
						id = url.substring(url.indexOf("&id=") + 4,
								url.indexOf("&imgUrl"));
						new Thread(new Runnable() {
							@Override
							public void run() {
								collect();
							}
						}).start();
					}
					return true;
				}
				if (url.contains("area_info?isLogin")) {
					AlertDialog isExit = new AlertDialog.Builder(
							TextActivity.this).create();
					isExit.setMessage("未登录，不能评论");
					isExit.setButton("确定", listener2);
					isExit.show();
					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(TextActivity.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(TextActivity.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() {
										wView.loadUrl("file:///android_asset/problem.html");
										flag = false;
									}
								});

							}

						}
					}

				}.start();
				text_relative.setVisibility(View.VISIBLE);
				wView.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;
				text_loadingview.stop();
				wView.setVisibility(View.VISIBLE);
				text_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
		});
		addview();
		text_layout = (RelativeLayout) findViewById(R.id.text_layout);
		// String out_path =
		// Environment.getExternalStorageDirectory().getPath()+ "/" +
		// "gts/create_scenic_area_info";
		// File file = new File(out_path);
		File f = new File(getSDPath() + "/gts/create_scenic_area_info/view/"
				+ strCode + ".html");
		if (isNetworkAvailable(getBaseContext())) {// 网络可用
			wView.setVisibility(View.VISIBLE);
			text_tv.setVisibility(View.GONE);
			wView.loadUrl("http://" + Variable.address
					+ "/terminal/scenic/area_info?code=" + strCode
					+ "&sesskey=" + sp.getString("sesskey", ""));
		} else if (f.exists()) {
			wView.setVisibility(View.VISIBLE);
			text_tv.setVisibility(View.GONE);
			wView.loadUrl("file:///sdcard/gts/create_scenic_area_info/view/"
					+ strCode + ".html");
		} else {
			wView.setVisibility(View.GONE);
			text_tv.setVisibility(View.VISIBLE);
		}
		/*
		 * if (file.exists()) { File f = new File(getSDPath() +
		 * "/gts/create_scenic_area_info/view/" + strCode + ".html"); if
		 * (f.exists()) { wView.setVisibility(View.VISIBLE);
		 * text_tv.setVisibility(View.GONE);
		 * wView.loadUrl("file:///sdcard/gts/create_scenic_area_info/view/" +
		 * strCode + ".html"); } else { wView.setVisibility(View.GONE);
		 * text_tv.setVisibility(View.VISIBLE); } } else {
		 * wView.setVisibility(View.VISIBLE); text_tv.setVisibility(View.GONE);
		 * wView.loadUrl("http://" + Variable.address +
		 * "/terminal/scenic/area_info?code=" + strCode + "&sesskey=" +
		 * sp.getString("sesskey", "")); }
		 */
		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) text_layout
								.getLayoutParams();
						rl.setMargins(0, 0, 0, heightDifference);
						// rl.setMargins(0, 863, 0, heightDifference);
						text_layout.requestLayout();
					}
				});
	}

	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(TextActivity.this, "收藏成功");
						}
					});
				} else if (result.equals("111")) {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ToastUtil.show(TextActivity.this, "已经收藏过了");
						}
					});
				} else {
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							ToastUtil.show(TextActivity.this, "网络异常");
						}
					});
				}

			}

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

				@Override
				public void run() {
					ToastUtil.show(TextActivity.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;
			}
		}
	};

	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);

	}

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

				break;

			}
		}
	};

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

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

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

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

	}

	@SuppressLint("NewApi")
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		flag = false;
		wView.clearCache(true);
		if (wView != null) {
			text_layout.removeView(wView);
			wView.removeAllViews();
			wView.onPause();
			wView.destroy();
		}
	}

	public String getSDPath() {
		File sdDir = null;

		// 判断SD卡是否存在
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED);
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取根目录
		}
		return sdDir.toString();

	}

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {
			// 如果仅仅是用来判断网络连接 ,则可以使用 cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.text_leftivback:
			finish();
			// wView.invalidate();
			break;

		default:
			break;
		}
	}

}
