package com.smart.gtstrvl;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

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 org.json.JSONObject;

import com.example.mountaintravel.base.BaseActivity;
import com.example.mountaintravel.service.MyGPSservice;
import com.example.mountaintravel.util.AesTerminalUtil;
import com.example.mountaintravel.util.BitmapUtil;
import com.example.mountaintravel.util.LoginUtil;
import com.example.mountaintravel.util.MD5Util;
import com.example.mountaintravel.util.MainUtil;
import com.example.mountaintravel.util.StringUtils;
import com.example.mountaintravel.util.ToastUtil;
import com.example.mountaintravel.util.UpdateManager;
import com.example.mountaintravel.variable.Variable;
import com.example.mountaintravel.view.DragViewlayout;
import com.example.mountaintravel.view.LoadingView;
import com.example.mountaintravel.view.MyLinearLayout;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.PowerManager;
import android.provider.Settings;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ActivityManager.RunningServiceInfo;
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.support.v4.widget.SwipeRefreshLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
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.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class MainActivity extends BaseActivity implements OnClickListener {
	private SwipeRefreshLayout swipeLayout;
	private ImageView main_ivleft;
	private ImageView main_ivleft2;
	private boolean iflogin = false;// 我的按钮选择状态
	private boolean ifguide = false;// 导游按钮选择状态
	private boolean iflead = false;// 首页按钮选择状态
	private boolean ifguess = false;// 竞赛按钮选择状态
	private boolean ifvisit = false;// 文创游按钮选择状态
	private WebView main_webview;
	private ImageView maintwo_imageViewhead;
	private TextView main_tv;
	private ImageView main_tvmine;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader;
	private SharedPreferences sp;
	private TextView maintwo_tv;
	private ImageView main_tvlead;
	private ImageView main_tvguide;
	private ImageView main_tvguessing;
	private ImageView main_tvwenchuang;
	private LinearLayout main_menulinear;
	private ImageView main_rightivmenu;
	private ImageView main_rightivadd;
	private String url;
	private String eventId = "";
	private String toapplyid = "";
	private static final String TAG = "MainActivity";
	private MainUtil listenerUtil;
	private RelativeLayout gifrelativeLayout;
	private LoadingView loadingview;
	private UpdateManager mUpdateManager;
	private MyLinearLayout mMainLayout;
	private DragViewlayout mDragLayout;
	private RelativeLayout main_item1, main_item2, main_item3, main_item4,
			main_item5, main_item6;
	private TextView main_item1_tv, main_item2_tv, main_item3_tv,
			main_item4_tv, main_item5_tv, main_item6_tv;
	private RelativeLayout main_menurelative;
	private RelativeLayout main_headrelative;
	boolean has_permission = false;
	boolean has_permission2 = false;
	boolean has_permissionlocation = false;
	boolean has_permissioncall = false;
	private String key = ".5Xf_01KXd352s177Jx3wxXc074poII";
	private SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
	private String time = format.format(new Date());
	private String type = "android";
	private String sign = MD5Util.MD5(time + type + key);
	private boolean flag = false;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
		initTitleBar("首页");
		findview();
		String nick_name = sp.getString("nick_name", "");
		main_tv.setText(nick_name);
		if (nick_name.equals("")) {
			main_tv.setOnClickListener(null);
		} else {
			main_tv.setOnClickListener(this);
		}
		adaptersetdate();// 左菜单栏显示的数据
		Variable.updata = false;
		mUpdateManager = new UpdateManager(this);
		mUpdateManager.getdata();
		if (!sp.getString("url", "").equals("")) {
			loadheadimage();
		}
		changeHeadImage();
		listenerUtil = new MainUtil(MainActivity.this);
		setboolean(false, false, false, false, true);
		listenerUtil.getAppVersionName();
		swipeLayout.setVisibility(View.VISIBLE);
		main_ivleft.setOnClickListener(this);
		main_ivleft2.setOnClickListener(this);
		url = "http://" + Variable.address + "/terminal/index";
		// url="file:///android_asset/loading.html";
		beginweb(main_webview, url);
		main_webview.loadUrl(url);
		if (sp.getBoolean("isloginsuccess", false)) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					String code = "";
					code = LoginUtil.loginByHttpClientGet();
					System.out.println(code + "sds");
					if (!code.equals("4008")) {
						auLogin();
					}
				}
			}).start();
		}
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	/*
	 * 设置头像的点击事件
	 */
	private void changeHeadImage() {
		if (sp.getBoolean("isloginsuccess", false)) {
			maintwo_imageViewhead.setOnClickListener(maintwo_ivlistener);

		} else {
			maintwo_imageViewhead.setOnClickListener(null);
		}
	}

	/*
	 * 更新做菜单选项
	 */
	private void adaptersetdate() {
		if (sp.getBoolean("isloginsuccess", false)) {
			main_item1_tv.setText("登山设备管理");
			main_item2_tv.setText("清除缓存");

			main_item3_tv.setText("检测更新");
			main_item4_tv.setText("紧急求助");
			main_item5_tv.setText("关于");
			main_item6_tv.setText("退出");
		} else {
			main_item1_tv.setText("用户登录");
			main_item2_tv.setText("登山设备管理");
			main_item3_tv.setText("清除缓存");
			main_item4_tv.setText("检测更新");
			main_item5_tv.setText("紧急求助");
			main_item6_tv.setText("关于");
		}

	}

	@SuppressLint("NewApi")
	public void addview() {
		WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Display display = manager.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getRealMetrics(outMetrics);
		gifrelativeLayout = (RelativeLayout) findViewById(R.id.gifrelativeLayout);
		loadingview = new LoadingView(getBaseContext(), outMetrics.widthPixels);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, 6);

		gifrelativeLayout.setOnClickListener(this);

		gifrelativeLayout.addView(loadingview, lp);
	}

	private void findview() {
		mDragLayout = (DragViewlayout) findViewById(R.id.slidingLayout);
		main_menulinear = (LinearLayout) findViewById(R.id.main_menulinear);
		main_menulinear.setOnClickListener(null);
		main_menurelative = (RelativeLayout) findViewById(R.id.main_menurelative);
		main_menurelative.setOnClickListener(null);
		main_headrelative = (RelativeLayout) findViewById(R.id.main_headrelative);
		main_headrelative.setOnClickListener(null);
		mMainLayout = (MyLinearLayout) findViewById(R.id.mll);
		mMainLayout.setDraglayout(mDragLayout);// 设置引用
		main_rightivmenu = (ImageView) findViewById(R.id.main_rightivmenu);
		main_rightivmenu.setOnClickListener(this);
		addview();
		main_item1 = (RelativeLayout) findViewById(R.id.main_item1);
		main_item2 = (RelativeLayout) findViewById(R.id.main_item2);
		main_item3 = (RelativeLayout) findViewById(R.id.main_item3);
		main_item4 = (RelativeLayout) findViewById(R.id.main_item4);
		main_item5 = (RelativeLayout) findViewById(R.id.main_item5);
		main_item6 = (RelativeLayout) findViewById(R.id.main_item6);
		main_item1_tv = (TextView) findViewById(R.id.main_item1_tv);
		main_item2_tv = (TextView) findViewById(R.id.main_item2_tv);
		main_item3_tv = (TextView) findViewById(R.id.main_item3_tv);
		main_item4_tv = (TextView) findViewById(R.id.main_item4_tv);
		main_item5_tv = (TextView) findViewById(R.id.main_item5_tv);
		main_item6_tv = (TextView) findViewById(R.id.main_item6_tv);
		main_item1.setOnClickListener(this);
		main_item2.setOnClickListener(this);
		main_item3.setOnClickListener(this);
		main_item4.setOnClickListener(this);
		main_item5.setOnClickListener(this);
		main_item6.setOnClickListener(this);
		main_tvwenchuang = (ImageView) findViewById(R.id.main_tvwenchuang);
		main_tvwenchuang.setOnClickListener(this);
		main_tvmine = (ImageView) findViewById(R.id.main_tvmine);
		main_ivleft = (ImageView) findViewById(R.id.main_leftivmenu);
		main_ivleft2 = (ImageView) findViewById(R.id.main_leftivback);
		main_tv = (TextView) findViewById(R.id.maintwo_tvnicknanme);
		maintwo_imageViewhead = (ImageView) findViewById(R.id.maintwo_imageViewhead);
		maintwo_imageViewhead.setOnClickListener(maintwo_ivlistener);// 点击换头像
		main_webview = (WebView) findViewById(R.id.main_webtv1);
		WebSettings wSet = main_webview.getSettings();
		wSet.setJavaScriptEnabled(true);
		main_webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
		main_webview.getSettings().setDomStorageEnabled(true);
		main_webview.getSettings().setAppCacheEnabled(true);
		main_tvmine.setOnClickListener(this);
		maintwo_tv = (TextView) findViewById(R.id.maintwo_tv);
		main_tvlead = (ImageView) findViewById(R.id.main_tvlead);
		main_tvguide = (ImageView) findViewById(R.id.main_tvguide);
		main_tvguessing = (ImageView) findViewById(R.id.main_tvguessing);
		main_tvlead.setOnClickListener(this);
		main_tvguide.setOnClickListener(this);
		main_tvguessing.setOnClickListener(this);
		swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
		main_rightivadd = (ImageView) findViewById(R.id.main_rightivadd);
		main_rightivadd.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		loadingview.start();
		super.onResume();
	}

	@Override
	protected void onPause() {
		// 判断屏幕黑屏
		PowerManager pm = (PowerManager) this
				.getSystemService(Context.POWER_SERVICE);
		boolean isScreenOn = pm.isScreenOn();
		if (!isScreenOn && Variable.ifOpen) {
			mDragLayout.close();
		}
		loadingview.stop();
		super.onPause();
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.main_tvmine:
			setboolean(true, false, false, false, false);

			if (sp.getBoolean("isloginsuccess", false)) {
				minelead();
			} else {
				// main_rightivshare.setVisibility(View.GONE);
				main_rightivadd.setVisibility(View.INVISIBLE);
				main_rightivadd.setOnClickListener(null);
				maintwo_tv.setText("我的");
				main_rightivmenu.setVisibility(View.VISIBLE);
				main_rightivmenu.setOnClickListener(this);
				url = "http://" + Variable.address + "/terminal/startevent";
				beginweb(main_webview, url);
				main_webview.loadUrl(url);
			}
			break;

		case R.id.main_tvlead:
			setboolean(false, false, false, false, true);
			url = "http://" + Variable.address + "/terminal/index";
			beginweb(main_webview, url);
			main_webview.loadUrl(url);
			main_rightivmenu.setVisibility(View.INVISIBLE);
			main_rightivmenu.setOnClickListener(null);
			// main_rightivshare.setVisibility(View.GONE);
			main_rightivadd.setVisibility(View.INVISIBLE);
			main_rightivadd.setOnClickListener(null);
			maintwo_tv.setText("首页");
			break;
		case R.id.main_tvguide:
			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(this).create();
					isExit.setMessage("暂未开启位置权限,去打开位置权限?");
					isExit.setButton("确定", listenerpower);
					isExit.setButton2("取消", listenerpower);
					isExit.show();
				} else {
					ToastUtil.show(MainActivity.this, "无位置权限");
				}
			} else if (!has_permission && has_permission2) {
				if (VERSION.SDK_INT >= 23) {
					AlertDialog isExit = new AlertDialog.Builder(this).create();
					isExit.setMessage("暂未开存储存储权限,去打开存储权限?");
					isExit.setButton("确定", listenerpower);
					isExit.setButton2("取消", listenerpower);
					isExit.show();
				} else {
					ToastUtil.show(MainActivity.this, "无存储权限");
				}
			} else if (!has_permission && !has_permission2) {
				if (VERSION.SDK_INT >= 23) {
					AlertDialog isExit = new AlertDialog.Builder(this).create();
					isExit.setMessage("暂未开启权限,去打开权限?");
					isExit.setButton("确定", listenerpower);
					isExit.setButton2("取消", listenerpower);
					isExit.show();
				} else {
					ToastUtil.show(MainActivity.this, "无位置和存储权限");
				}
			} else {
				startActivity(BrowseMapActivity.class);
			}
			break;
		case R.id.main_tvguessing:
			guesslead();
			break;
		case R.id.main_item1:
			if (main_item1_tv.getText().toString().trim().equals("用户登录")) {

				startActivity(LoginActivity.class);

			} else {
				Intent intent2 = new Intent(MainActivity.this,
						DeviceManaActivity.class);
				sp.edit().putString("mydevice", "mydevice").commit();
				startActivityForResult(intent2, 1);

			}

			break;
		case R.id.main_item2:
			if (!sp.getBoolean("isloginsuccess", false)) {
				startActivity(LoginActivity.class);
			} else {
				clearDialog();
			}

			break;
		case R.id.main_item3:
			if (main_item3_tv.getText().toString().trim().equals("清除缓存")) {

				clearDialog();

			} else {
				Variable.updata = true;
				mUpdateManager = new UpdateManager(this);
				mUpdateManager.getdata();
			}

			break;

		case R.id.main_item4:
			if (main_item4_tv.getText().toString().trim().equals("检测更新")) {

				Variable.updata = true;
				mUpdateManager = new UpdateManager(this);
				mUpdateManager.getdata();
			} else {
				new Thread(new Runnable() {

					@Override
					public void run() {
						help();
					}
				}).start();
				PackageManager pkmr = getPackageManager();
				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(this)
								.create();
						isExit.setMessage("暂未开启电话权限,去打开电话权限?");
						isExit.setButton("确定", listenerpower);
						isExit.setButton2("取消", listenerpower);
						isExit.show();
					} else {
						ToastUtil.show(MainActivity.this, "无电话权限");
					}
				} else {
					AlertDialog isExit = new AlertDialog.Builder(
							MainActivity.this).create();
					isExit.setMessage("游客中心  " + "0571-8665-6677");
					isExit.setButton("呼叫", listenerPhone);
					isExit.setButton2("取消", listenerPhone);
					isExit.show();
				}
			}
			break;
		case R.id.maintwo_tvnicknanme:
			startActivity(PinfoActivity.class);

			break;
		case R.id.main_item5:
			if (main_item5_tv.getText().toString().trim().equals("关于")) {
				startActivity(AboutActivity.class);
			} else {
				PackageManager pkmr = getPackageManager();
				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(this)
								.create();
						isExit.setMessage("暂未开启电话权限,去打开电话权限?");
						isExit.setButton("确定", listenerpower);
						isExit.setButton2("取消", listenerpower);
						isExit.show();
					} else {
						ToastUtil.show(MainActivity.this, "无电话权限");
					}
				} else {
					AlertDialog isExit = new AlertDialog.Builder(
							MainActivity.this).create();
					isExit.setMessage("游客中心  " + "0571-8665-6677");
					isExit.setButton("呼叫", listenerPhone);
					isExit.setButton2("取消", listenerPhone);
					isExit.show();
				}
			}
			break;
		case R.id.main_item6:
			if (sp.getBoolean("isloginsuccess", false)) {
				AlertDialog isExit = new AlertDialog.Builder(this).create();
				isExit.setMessage("确定要退出当前用户吗?");
				isExit.setButton("确定", listener);
				isExit.setButton2("取消", listener);
				isExit.show();
			} else {
				startActivity(AboutActivity.class);
			}
			break;
		case R.id.main_rightivmenu:
			if (sp.getBoolean("isloginsuccess", false)) {
				startActivity(PinfoActivity.class);
			} else {
				ToastUtil.show(this, "请先登录");
				startActivity(LoginActivity.class);
			}
			break;

		/*
		 * 添加虚拟赛事
		 */
		case R.id.main_rightivadd:
			/*
			 * String value="哈哈"; tv.loadUrl("javascript:test('"+value+"')");
			 */
			if (sp.getBoolean("isloginsuccess", false)) {
				startActivity(VirtualRoadActivity.class);
			} else {
				ToastUtil.show(this, "请先登录");
				startActivity(LoginActivity.class);
			}
			break;
		case R.id.main_leftivmenu:
			mDragLayout.open();

			break;
		case R.id.main_leftivback:

			if (!maintwo_tv.getText().toString().equals("公告详情")) {
				url = "http://" + Variable.address + "/terminal/index";
				beginweb(main_webview, url);
				main_webview.loadUrl(url);
			} else {
				url = "http://mp.weixin.qq.com/mp/homepage?__biz=MzAxNDMwNjA1Ng==&hid=6&sn=9d1f5557994e70fefbb5361cf7eb1e54#wechat_redirect";
				beginweb(main_webview, url);
				main_webview.loadUrl(url);
			}
			break;
		case R.id.main_tvwenchuang:
			if (!sp.getBoolean("isloginsuccess", false)) {
				ToastUtil.show(this, "请先登录");
			} else {
				PackageManager pkmori = getPackageManager();
				has_permissionlocation = (PackageManager.PERMISSION_GRANTED == pkmori
						.checkPermission(
								"android.permission.ACCESS_FINE_LOCATION",
								"com.smart.gtstrvl"));
				if (!has_permissionlocation) {
					if (VERSION.SDK_INT >= 23) {
						AlertDialog isExit = new AlertDialog.Builder(this)
								.create();
						// 设置对话框消息
						isExit.setMessage("暂未开启位置权限,去打开位置权限?");
						// 添加选择按钮并注册监听
						isExit.setButton("确定", listenerpower);
						isExit.setButton2("取消", listenerpower);
						// 显示对话框
						isExit.show();
					} else {
						ToastUtil.show(MainActivity.this, "无位置权限");
					}
				} else {
					startActivity(OriginalityActivity.class);
				}

			}

			break;

		}

	}

	// 判断服务有没有开启的判断方法

	private boolean isWorked(String className) {
		ActivityManager myManager = (ActivityManager) MainActivity.this
				.getApplicationContext().getSystemService(
						Context.ACTIVITY_SERVICE);
		ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager
				.getRunningServices(300);
		for (int i = 0; i < runningService.size(); i++) {
			if (runningService.get(i).service.getClassName().toString()
					.equals(className)) {
				return true;
			}
		}
		return false;
	}

	private void clearDialog() {
		AlertDialog isExit = new AlertDialog.Builder(this).create();
		// 设置对话框消息
		isExit.setMessage("确定要清除吗");
		// 添加选择按钮并注册监听
		isExit.setButton("确定", listenerclear);
		isExit.setButton2("取消", listenerclear);
		// 显示对话框
		isExit.show();
	}

	// 我的个人中心
	private void minelead() {
		// main_rightivshare.setVisibility(View.GONE);
		main_rightivadd.setVisibility(View.INVISIBLE);
		main_rightivadd.setOnClickListener(null);
		main_rightivmenu.setVisibility(View.VISIBLE);
		main_rightivmenu.setOnClickListener(this);
		maintwo_tv.setText("我的");
		url = "http://" + Variable.address + "/terminal/memberindex?sesskey="
				+ sp.getString("sesskey", "");
		beginweb(main_webview, url);
		main_webview.loadUrl(url);
	};

	private void setboolean(boolean login, boolean guide, boolean guess,
			boolean visit, boolean lead) {
		iflogin = login;
		ifguide = guide;
		ifguess = guess;
		ifvisit = visit;
		iflead = lead;
		listenerUtil.ifclick(iflogin, ifguide, ifguess, ifvisit, iflead);
	}

	private void guesslead() {
		setboolean(false, false, true, false, false);
		url = "http://" + Variable.address + "/terminal/event/introduce_index";
		beginweb(main_webview, url);
		main_webview.loadUrl(url);
		// main_rightivshare.setVisibility(View.GONE);
		main_rightivmenu.setVisibility(View.INVISIBLE);
		main_rightivmenu.setOnClickListener(null);
		main_rightivadd.setVisibility(View.VISIBLE);
		main_rightivadd.setOnClickListener(this);
		maintwo_tv.setText("竞赛");
	}

	@SuppressLint("NewApi")
	private void loadExit() {

		if (isWorked("com.example.mountaintravel.service.MyGPSservice")) {
			Intent stopIntent = new Intent(MainActivity.this,
					MyGPSservice.class);
			stopService(stopIntent);
		}
		sp.edit().putString("parameter", "").commit();
		sp.edit().putString("braceletSn", "").commit();
		sp.edit().putBoolean("bind", false).commit();
		sp.edit().putBoolean("isMyCollect", false).commit();
		sp.edit().putBoolean("comment", false).commit();
		sp.edit().putBoolean("getcode", false).commit();
		sp.edit().putBoolean("isloginsuccess", false).commit();
		sp.edit().putString("userName", "").commit();
		sp.edit().putString("userPass", "").commit();
		Variable.JSESSIONID = "";
		sp.edit().putBoolean("virtualPinfo", false).commit();
		sp.edit().putBoolean("virtual", false).commit();
		sp.edit().putBoolean("apply", false).commit();
		sp.edit().putString("repeaterSn", "").commit();
		sp.edit().putString("toapplyid", "").commit();
		sp.edit().putString("eventId", "").commit();
		sp.edit().putString("sesskey", "").commit();
		sp.edit().putString("url", "").commit();
		sp.edit().putString("sex", "").commit();
		sp.edit().putString("weight", "").commit();
		sp.edit().putString("increased", "").commit();
		sp.edit().putString("userid", "").commit();
		sp.edit().putString("nick_name", "").commit();
		sp.edit().putString("real_name", "").commit();
		sp.edit().putBoolean("iferr11", false).commit();
		sp.edit().putBoolean("iferr10", false).commit();
		sp.edit().putBoolean("geturl", false).commit();
		sp.edit().putBoolean("geturlpager", false).commit();
		listenerUtil.ifloginorfasle(iflogin, ifguide, ifguess);
		adaptersetdate();
		if (iflogin) {
			url = "http://" + Variable.address + "/terminal/startevent";
			beginweb(main_webview, url);
			main_webview.loadUrl(url);
		}

		String nick_name = sp.getString("nick_name", "");
		main_tv.setText(nick_name);

		main_tv.setOnClickListener(null);
		maintwo_imageViewhead.setImageDrawable(getResources().getDrawable(
				R.drawable.head)); // 不会变形
		maintwo_imageViewhead.setOnClickListener(null);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	private void beginweb(final WebView tv, String url) {
		ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(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) {
			tv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		}
		tv.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// 我的界面点立即申请捕获到申请的赛事的id
				ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(MainActivity.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(MainActivity.this, "网络异常，请检查网络");
					return true;
				}
				loadingview.start();
				Log.d(TAG, url);

				if (url.contains("terminal/toapply")
						&& !url.contains("terminal/toapplyevent")) {
					int a = StringUtils.indexOf(url, "id=");
					toapplyid = url.substring(a + 3);
					sp.edit().putString("toapplyid", toapplyid).commit();
				}
				listenerUtil.listenerurlshould(url);
				if (sp.getBoolean("geturl", true)) {
					sp.edit().putBoolean("geturl", false).commit();
					return true;
				} else if (url.contains("event/introduce_index")) {
					guesslead();
				} else if (url.contains("error?err=8")) {
					url = "http://" + Variable.address
							+ "/terminal/memberindex?sesskey="
							+ sp.getString("sesskey", "");
					beginweb(tv, url);
					tv.loadUrl(url);
					ToastUtil.show(MainActivity.this, "报名成功，等待审核");
					startActivity(GameListActivity.class);
					return true;
				} else if (url.contains("scenic/area_info?id")) {
					try {
						url = java.net.URLDecoder.decode(url, "utf-8");
						Intent intent = new Intent(MainActivity.this,
								ScenicActivity.class);
						intent.putExtra("scenic", url);
						startActivity(intent);
						return true;
					} catch (UnsupportedEncodingException e1) {

						e1.printStackTrace();
						return true;

					}
				} else if (url.contains("member/area_favorite_list")) {

					startActivity(MyCollectActivity.class);
					return true;
				} else if (url.contains("/event/event_info")) {

					int a = StringUtils.indexOf(url, "eventId=");
					eventId = url.substring(a + 8);
					sp.edit().putString("eventId", eventId).commit();
					startActivity(EventInfoActivity.class);
					return true;
				}
				/*
				 * 检测到退出
				 */
				else if (url.contains("terminal/loginout")) {
					AlertDialog isExit = new AlertDialog.Builder(
							MainActivity.this).create();
					isExit.setMessage("确定要退出当前用户吗?");
					isExit.setButton("确定", listener);
					isExit.setButton2("取消", listener);
					isExit.show();
					return true;
				}
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				flag = false;
				tv.loadUrl("file:///android_asset/loading.html");

			}

			@Override
			public void onPageFinished(WebView view, String url) {
				flag = false;
				loadingview.stop();
				swipeLayout.setRefreshing(false);
				tv.setVisibility(View.VISIBLE);
				gifrelativeLayout.setVisibility(View.INVISIBLE);
				gifrelativeLayout.setOnClickListener(null);
				swipeLayout.setVisibility(View.VISIBLE);
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				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) {
								e.printStackTrace();
							}
							if (i > 60) {
								runOnUiThread(new Runnable() {
									public void run() {
										tv.loadUrl("file:///android_asset/loading.html");
										flag = false;
									}
								});

							}

						}
					}

				}.start();
				if (!swipeLayout.isRefreshing())
					tv.setVisibility(View.GONE);

				gifrelativeLayout.setVisibility(View.VISIBLE);
				gifrelativeLayout.setOnClickListener(null);
				swipeLayout.setVisibility(View.INVISIBLE);
				swipeLayout.setOnClickListener(null);
				super.onPageStarted(view, url, favicon);
				Log.d(TAG, url + "我是");
				if (url.contains("success?suc=1")
						|| url.contains("success?suc=2")
						|| url.contains("success?suc=4")
						|| url.contains("success?suc=5")) {
					ToastUtil.show(MainActivity.this, "申请成功");
					minelead();
					startActivity(GameListActivity.class);
					return;
				}
				listenerUtil.listenerurlpager(url);

				if (sp.getBoolean("geturlpager", true)) {
					sp.edit().putBoolean("geturlpager", false).commit();
					return;
				}
				if (url.contains("terminal/addeventsucess")) {

					startActivity(GameListActivity.class);
					return;
				}
			}
		});

		swipeLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
					@Override
					public void onRefresh() {
						ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(MainActivity.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) {
							tv.getSettings().setCacheMode(
									WebSettings.LOAD_DEFAULT);
						}
						// TODO

						if (maintwo_tv.getText().toString().equals("首页")) {
							tv.loadUrl("http://" + Variable.address
									+ "/terminal/index");
						}
						if (maintwo_tv.getText().toString().equals("竞赛")) {
							tv.loadUrl("http://" + Variable.address
									+ "/terminal/event/introduce_index");
						}
						if (maintwo_tv.getText().toString().equals("我的")) {
							tv.loadUrl("http://" + Variable.address
									+ "/terminal/startevent");
						}
						if (maintwo_tv.getText().toString().equals("我的个人中心")) {
							tv.loadUrl("http://" + Variable.address
									+ "/terminal/memberindex?sesskey="
									+ sp.getString("sesskey", ""));
						}
						if (maintwo_tv.getText().toString().equals("景区详情")) {
							tv.loadUrl("http://" + Variable.address
									+ "/terminal/scenic/introduce_index");
						}
						if (maintwo_tv.getText().toString().equals("公告列表")) {
							tv.loadUrl("http://mp.weixin.qq.com/mp/homepage?__biz=MzAxNDMwNjA1Ng==&hid=6&sn=9d1f5557994e70fefbb5361cf7eb1e54#wechat_redirect");
						}

					}
				});
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		String nick_name = sp.getString("nick_name", "");
		main_tv.setText(nick_name);

		main_tv.setOnClickListener(this);
		maintwo_imageViewhead.setOnClickListener(maintwo_ivlistener);// 头像点击事件
		/*
		 * 设置头像加载
		 */
		if (!sp.getString("url", "").equals("")) {
			loadheadimage();
		}
		listenerUtil.ifloginorfasle(iflogin, ifguide, ifguess);
		adaptersetdate();
		changeHeadImage();

		if (sp.getBoolean("isloginsuccess", false) && !ifguess && iflogin) {
			url = "http://" + Variable.address
					+ "/terminal/memberindex?sesskey="
					+ sp.getString("sesskey", "");
			beginweb(main_webview, url);
			main_webview.loadUrl(url);
			return;
		}
		if (!sp.getBoolean("isloginsuccess", false) && !ifguess && iflogin) {
			url = "http://" + Variable.address
					+ "/terminal/startevent?sesskey="
					+ sp.getString("sesskey", "");
			beginweb(main_webview, url);
			main_webview.loadUrl(url);
			return;
		}
		/*
		 * if (tv.getUrl().contains("scenic/area_info?id")) { String url =
		 * tv.getUrl(); if (!sp.getBoolean("comment", false)) { new Thread(new
		 * Runnable() { public void run() { collect(); } }).start(); }
		 * 
		 * String value = sp.getString("sesskey", "");
		 * tv.loadUrl("javascript:appLoginOpenWeb('" + value + "')");
		 * 
		 * url = url + sp.getString("sesskey", ""); beginweb(tv, url);
		 * tv.loadUrl(url); }
		 */

	}

	@SuppressLint("NewApi")
	private void loadheadimage() {
		if (!sp.getString("url", "").contains("face")) {
			ImageSize mImageSize = new ImageSize(200, 200);
			imageLoader = ImageLoader.getInstance();
			imageLoader.init(ImageLoaderConfiguration
					.createDefault(MainActivity.this));
			options = new DisplayImageOptions.Builder()
					.showStubImage(R.drawable.head)
					.showImageForEmptyUri(R.drawable.head)
					.showImageOnFail(R.drawable.head).cacheInMemory(true)
					.displayer(new RoundedBitmapDisplayer(100))
					.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565)
					.build();

			imageLoader.loadImage(sp.getString("url", ""), mImageSize, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
							Bitmap headBitmap = BitmapUtil
									.toRoundBitmap(loadedImage);
							maintwo_imageViewhead.setImageBitmap(headBitmap);
							maintwo_imageViewhead
									.setScaleType(ScaleType.FIT_XY);
						}
					});
			maintwo_imageViewhead.setScaleType(ScaleType.FIT_XY);
		} else {
			maintwo_imageViewhead.setBackground(getResources().getDrawable(
					R.drawable.head));
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		sp.edit().putString("parameter", "").commit();
		sp.edit().putBoolean("getcode", false).commit();
		flag = false;
	}

	/*
	 * (non-Javadoc) 返回键遇到以下界面会提示退出
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (maintwo_tv.getText().toString().equals("首页")
					|| maintwo_tv.getText().toString().equals("竞赛")
					|| maintwo_tv.getText().toString().equals("我的")
					|| maintwo_tv.getText().toString().equals("我的个人中心")) {
				if (main_webview != null) {
					swipeLayout.removeView(main_webview);
					main_webview.removeAllViews();
					main_webview.onPause();
					main_webview.destroy();
				}
				finish();
				return true;
			}
		}

		if (keyCode == KeyEvent.KEYCODE_BACK && main_webview.canGoBack()) {
			if (!maintwo_tv.getText().toString().equals("公告详情")) {
				url = "http://" + Variable.address + "/terminal/index";
				beginweb(main_webview, url);
				main_webview.loadUrl(url);
				return true;
			} else {
				url = "http://mp.weixin.qq.com/mp/homepage?__biz=MzAxNDMwNjA1Ng==&hid=6&sn=9d1f5557994e70fefbb5361cf7eb1e54#wechat_redirect";
				beginweb(main_webview, url);
				main_webview.loadUrl(url);
				return true;
			}

		}
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 创建退出对话框
			if (main_webview != null) {
				swipeLayout.removeView(main_webview);
				main_webview.removeAllViews();
				main_webview.onPause();
				main_webview.destroy();
			}
			finish();
		}
		return false;
	}

	/** 监听对话框里面的button点击事件 */
	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		@SuppressLint("NewApi")
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				loadExit();
				changeHeadImage();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};
	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 void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case 1:
			main_webview.loadUrl(main_webview.getUrl());
			break;

		}
	}

	DialogInterface.OnClickListener listenerclear = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				main_webview.clearCache(true);
				ToastUtil.show(MainActivity.this, "清除成功");
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;

			}
		}
	};
	View.OnClickListener maintwo_ivlistener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			startActivity(ChangeHeadActivity.class);
		}
	};
	DialogInterface.OnClickListener listenerPhone = 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:"
						+ "0571-8665-6677"));
				startActivity(intent);
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框

				break;
			}
		}
	};

	private void auLogin() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/login";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("type", type));
			parameters.add(new BasicNameValuePair("time", time));
			parameters.add(new BasicNameValuePair("sign", sign));
			parameters.add(new BasicNameValuePair("name", sp.getString(
					"userName", "")));
			parameters.add(new BasicNameValuePair("login_type", "2"));
			parameters.add(new BasicNameValuePair("pwds", sp.getString(
					"userPass", "")));
			parameters.add(new BasicNameValuePair("origin", "phone"));
			// 创建传递参数封装 实体对象
			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++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					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();
				JSONObject json = new JSONObject(result);
				String status = json.getString("status");
				if (status.equals("9002")) {
					sp.edit().putString("sesskey", json.getString("sesskey"))
							.commit();
					Map<String, Object> map = AesTerminalUtil
							.gtsApiAesDecryptToMap(json.getString("sesskey"));
					sp.edit()
							.putString("nick_name",
									(String) map.get("nick_name")).commit();
				} else {
					runOnUiThread(new Runnable() {
						public void run() {
							loadExit();
						}
					});

				}
			} else {
				runOnUiThread(new Runnable() {
					public void run() {
						loadExit();
					}
				});

			}

		} catch (Exception e) {
			runOnUiThread(new Runnable() {
				public void run() {
					loadExit();
				}
			});

			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}
	}

	private void help() {
		DefaultHttpClient client = new DefaultHttpClient();
		String uri = "http://" + Variable.address + "/terminal/userSeekHelp";
		HttpPost httpPost = new HttpPost(uri);
		try {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			// 往这个集合中添加你要传递的参数
			parameters.add(new BasicNameValuePair("userId", sp.getString(
					"userid", "")));
			parameters.add(new BasicNameValuePair("user_name", sp.getString(
					"real_name", "")));
			parameters.add(new BasicNameValuePair("axisX", Variable.myPointX));
			parameters.add(new BasicNameValuePair("axisY", Variable.myPointY));
			// 创建传递参数封装 实体对象
			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++) {
					// 这里是读取Cookie['PHPSESSID']的值存在静态变量中，保证每次都是同一个值
					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();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 6. 释放连接。无论执行方法是否成功，都必须释放连接
			client.getConnectionManager().shutdown();
		}

	}
}
