package com.smart.gtstrvl;

import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.util.Util;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.LoadingView;
import com.example.mountaintravel.view.TitleBarView;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
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;

public class TeamGradeActivity extends BaseActivity implements OnClickListener {
	private WebView team_webview;
	private static final String TAG = "TeamGradeActivity";
	private String url = "";
	private RelativeLayout team_relative;
	private LoadingView team_loadingview;
	LinearLayout linear_team;
	private boolean flag = false;
	public static IWXAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_team_grade);
		initTitleBar("团队成绩", R.drawable.share);
		Variable.className = "TeamGradeActivity";
		team_webview = (WebView) findViewById(R.id.team_webview);
		linear_team = (LinearLayout) findViewById(R.id.linear_team);
		addview();
		WebSettings wSet = team_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		team_webview.getSettings().setDomStorageEnabled(false);
		team_webview.getSettings().setAppCacheEnabled(false);
		Intent intent = getIntent();
		url = intent.getStringExtra("url");
		// 设置 Application Caches 缓存目录
		team_webview.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				team_loadingview.start();
				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(TeamGradeActivity.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(TeamGradeActivity.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;
				team_loadingview.stop();
				team_webview.setVisibility(View.VISIBLE);
				team_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() {
										team_webview
												.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});

							}

						}
					}

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

		});

		team_webview.loadUrl(url);
	}

	public void initTitleBar(String text, int rightIconId) {
		TitleBarView v = (TitleBarView) findViewById(R.id.titleBarView1);
		if (v != null) {
			v.initTitleBar(R.drawable.zuoback, rightIconId, text,
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							if (v.getId() == R.id.left_icon) {
								finish();
							}
							if (v.getId() == R.id.right_icon) {
								if (!isWXAppInstalledAndSupported()) {
									ToastUtil.show(TeamGradeActivity.this,
											"未安装微信客户端");
									return;
								}
								// isWXAppInstalledAndSupported
								if (api == null) {
									api = WXAPIFactory.createWXAPI(
											TeamGradeActivity.this,
											"wxb8f15f96478031e0", false);
								}
								// 将该app注册到微信
								api.registerApp("wxb8f15f96478031e0");
								share2Wx();
							}
						}
					});
		}
	}

	private void share2Wx() {
		WXWebpageObject webpage = new WXWebpageObject();
		webpage.webpageUrl = url + "&shareFlag=1";
		WXMediaMessage msg = new WXMediaMessage(webpage);
		msg.title = "智慧皋亭山－－团队成绩";
		Bitmap thumb = BitmapFactory.decodeResource(this.getResources(),
				R.drawable.app_icon);
		if (thumb == null) {
			// Toast.makeText(context, "图片不能为空", Toast.LENGTH_SHORT).show();
		} else {
			msg.thumbData = Util.bmpToByteArray(thumb, true);
		}
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction("webpage");
		req.message = msg;
		req.scene = SendMessageToWX.Req.WXSceneTimeline;
		api.sendReq(req);

	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	private boolean isWXAppInstalledAndSupported() {
		IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
		msgApi.registerApp("wxb8f15f96478031e0");

		boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
				&& msgApi.isWXAppSupportAPI();

		return sIsWXAppInstalledAndSupported;
	}

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

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

	}

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

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		team_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;
		if (team_webview != null) {
			linear_team.removeView(team_webview);
			team_webview.removeAllViews();
			team_webview.onPause();
			team_webview.destroy();
		}
	}

}
