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.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 MyGradeActivity extends BaseActivity implements OnClickListener {
	private WebView webView;
	private String url = "";
	private SharedPreferences sp;
	LinearLayout mygrade_layout;
	private RelativeLayout mygrade_relative;
	private LoadingView mygrade_loadingview;
	private static final String TAG = "MyGradeActivity";
	private boolean flag = false;
	public static IWXAPI api;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_grade);
		initTitleBar("赛事成绩", R.drawable.share);
		Variable.className = "MyGradeActivity";
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		Intent intent = getIntent();
		String eventId = intent.getStringExtra("eventId");
		url = "http://" + Variable.address + "/wap/event_repeater_ranking?"
				+ "&eventId=" + eventId + "&userId="
				+ sp.getString("userid", "-1");
		webView = (WebView) findViewById(R.id.mygrade_web);
		mygrade_layout = (LinearLayout) findViewById(R.id.mygrade_layout);
		addview();
		WebSettings wSet = webView.getSettings();
		wSet.setJavaScriptEnabled(true);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.d(TAG, url);
				mygrade_loadingview.start();
				if (url.contains("wap/event_team_user_repeater_ranking")) {
					Intent intent = new Intent(MyGradeActivity.this,
							TeamGradeActivity.class);
					intent.putExtra("url", url);
					startActivity(intent);
					return true;
				}
				if (url.contains("wap/event_repeater_ranking_user_info")) {
					Intent intent = new Intent(MyGradeActivity.this,
							SportInfoActivity.class);
					intent.putExtra("url", url);
					startActivity(intent);
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			@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++;
							try {
								Thread.sleep(1000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (i > 60) {
								runOnUiThread(new Runnable() {
									public void run() {
										webView.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});

							}

						}
					}

				}.start();
				mygrade_relative.setVisibility(View.VISIBLE);
				webView.setVisibility(View.GONE);
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				// TODO Auto-generated method stub
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag = false;
				view.loadUrl("file:///android_asset/loading.html");
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				flag = false;
				mygrade_loadingview.stop();
				webView.setVisibility(View.VISIBLE);
				mygrade_relative.setVisibility(View.GONE);
				super.onPageFinished(view, url);
			}
		});
		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(MyGradeActivity.this,
											"未安装微信客户端");
									return;
								}
								// isWXAppInstalledAndSupported
								if (api == null) {
									api = WXAPIFactory.createWXAPI(
											MyGradeActivity.this,
											"wxb8f15f96478031e0", false);
								}
								// 将该app注册到微信
								api.registerApp("wxb8f15f96478031e0");
								share2Wx();
							}
						}
					});
		}
	}

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

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

		return sIsWXAppInstalledAndSupported;
	}

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

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

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

	}

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

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.my_grade, menu);
		return true;
	}

	@SuppressLint("NewApi")
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Variable.className = "MyGradeActivity";
		flag = false;
		if (webView != null) {
			mygrade_layout.removeView(webView);
			webView.removeAllViews();
			webView.onPause();
			webView.destroy();
		}

	}

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

	}

}
