package com.gh.gamecenter;

import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.gh.base.AppController;
import com.gh.base.BaseFragmentActivity;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DeviceUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.MD5Utils;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
import com.gh.common.util.RandomUtils;
import com.gh.common.util.RunningUtils;
import com.gh.common.util.SpeedUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.TokenUtils;
import com.gh.common.util.TrafficUtils;
import com.gh.common.util.Utils;
import com.gh.download.DataWatcher;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.db.info.ConcernInfo;
import com.gh.gamecenter.db.info.GameInfo;
import com.gh.gamecenter.db.info.SuspectedGameInfo;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.AppEntity;
import com.gh.gamecenter.entity.GameDigestEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.entity.GameUpdateEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBShowDialog;
import com.gh.gamecenter.eventbus.EBSkip;
import com.gh.gamecenter.eventbus.EBTopStatus;
import com.gh.gamecenter.eventbus.EBUISwitch;
import com.gh.gamecenter.game.GameFragment;
import com.gh.gamecenter.manager.ConcernManager;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.FilterManager;
import com.gh.gamecenter.manager.GameManager;
import com.gh.gamecenter.manager.PackageManager;
import com.gh.gamecenter.manager.SuspectedGameManager;
import com.gh.gamecenter.news.NewsFragment;
import com.gh.gamecenter.personal.PersonalFragment;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import de.greenrobot.event.EventBus;

/**
 *
 * @author 温冠超
 * @email 294299195@qq.com
 * @update 2015-8-11
 * @des 项目的主Activity，3个Fragment都嵌入在这里。
 */
public class MainActivity extends BaseFragmentActivity implements OnClickListener {

	public static final String TAG = MainActivity.class.getSimpleName();

	public static String searchHint;

	private GameFragment gameFragment;
	private NewsFragment newsFragment;
	private PersonalFragment personalFragment;
	private LinearLayout home1Layout;
	private LinearLayout home2Layout;
	private LinearLayout home3Layout;
	private ImageView home1Image;
	private ImageView home2Image;
	private ImageView home3Image;
	private TextView home1Title;
	private TextView home2Title;
	private TextView home3Title;

	private AppEntity appEntity;
	private SharedPreferences sp;
	private ConcernManager concernManager;

	private int currentTab;

	private boolean isDestroy = false;
	private boolean isShowDownload = false;
	private boolean isNewFirstLaunch;

	private Handler handler = new Handler();

	// 黄壮华 添加观察者 修改2015/8/15
	private DataWatcher dataWatcher = new DataWatcher() {
		@Override
		public void onDataChanged(DownloadEntity downloadEntity) {
			// 链接被劫持
			if (DownloadStatus.hijack.equals(downloadEntity.getStatus())) {
				processHijack(downloadEntity);
				return;
			}
			if (downloadEntity.getName().contains("光环助手") && isShowDownload) {
				processGhAssistDownload(downloadEntity);
			}
			if (DownloadStatus.done.equals(downloadEntity.getStatus())) {
				if (downloadEntity.getName().contains("光环助手")) {
					DataUtils.onEvent(MainActivity.this, "软件更新", "下载完成");
					startActivity(PackageUtils.getInstallIntent(downloadEntity.getPath()));
					if (appEntity != null && appEntity.isIs_force()) {
						finish();
					}
				} else {
					statDoneEvent(downloadEntity);

					if (RunningUtils.isApplicationBroughtToBackground(getApplicationContext())) {
						// 应用程序在后台，如果是插件化下载，则弹出notification提示用户
						if (downloadEntity.isPluggable()) {
							String path = downloadEntity.getPath();
							String platform = PlatformUtils.getInstance(getApplicationContext())
									.getPlatformName(downloadEntity.getPlatform());
							String title = downloadEntity.getName() + " - " + platform;

							Intent intent = new Intent();
							intent.putExtra("path", path);
							intent.setAction("com.gh.gamecenter.UNINSTALL");
							PendingIntent pendingIntent = PendingIntent.getBroadcast(
									MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
							Notification notification = new NotificationCompat.Builder(MainActivity.this)
									.setSmallIcon(R.drawable.logo)
									.setTicker(title)
									.setContentTitle(title)
									.setContentText("下载完成，点击继续插件化。")
									.setContentIntent(pendingIntent)
									.build();
							notification.defaults = Notification.DEFAULT_SOUND;// 添加系统默认声音
							notification.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时，通知将被清除。
							NotificationManager notificationManager = (NotificationManager) getSystemService(
									Context.NOTIFICATION_SERVICE);
							notificationManager.notify(((int) System.currentTimeMillis() / 1000), notification);
						}
					} else {
						String platform = PlatformUtils.getInstance(getApplicationContext())
								.getPlatformName(downloadEntity.getPlatform());
						if (platform != null) {
							if (downloadEntity.isPluggable()) {
								// 弹出插件化提示框
								EventBus.getDefault().post(new EBShowDialog("plugin", downloadEntity.getPath()));
							} else if (platform.equals("官方版")) {
								toast(downloadEntity.getName() + " - 下载完成");
							} else {
								toast(downloadEntity.getName() + " - " + platform + " - 下载完成");
							}
						} else {
							toast(downloadEntity.getName() + " - 下载完成");
						}
						if (!downloadEntity.isPluggable()) {
							// 是否是自动安装
							if (sp.getBoolean("autoinstall", true)) {
								if (FileUtils.isEmptyFile(downloadEntity.getPath())) {
									toast("解析包出错（可能被误删了），请重新下载");
									DownloadManager.getInstance(MainActivity.this).cancel(downloadEntity.getUrl());
								} else {
									if (PackageUtils.isCanLaunchSetup(getApplicationContext(), downloadEntity.getPath())) {
										startActivity(PackageUtils.getInstallIntent(downloadEntity.getPath()));
									} else {
										// 弹出卸载提示框
										EventBus.getDefault().post(new EBShowDialog("plugin", downloadEntity.getPath()));
									}
								}
							}
						}
					}

					// 统计下载完成
					uploadData(downloadEntity.getGameId(), downloadEntity.getPlatform());
				}
			}
		}
	};

	// 统计下载
	private void uploadData(String id, String platform) {
		HashMap<String, String> params = new HashMap<>();
		params.put("game", id);
		params.put("platform", platform);
		JSONObject jsonObject = new JSONObject(params);
		JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(Method.POST,
				Config.HOST + "v2/stat/download", jsonObject.toString(), null, null);
		AppController.addToRequestQueue(request, TAG);
	}

	// 统计下载完成事件
	private void statDoneEvent(DownloadEntity downloadEntity) {
		Map<String, Object> kv1 = new HashMap<>();
		kv1.put("版本", downloadEntity.getPlatform());
		kv1.put("状态", "下载完成");
		if (downloadEntity.isUpdate()) {
			DataUtils.onEvent(MainActivity.this, "游戏更新", downloadEntity.getName(), kv1);
		} else {
			DataUtils.onEvent(MainActivity.this, "游戏下载", downloadEntity.getName(), kv1);
		}

		Map<String, Object> kv2 = new HashMap<>();
		kv2.put("版本", downloadEntity.getPlatform());
		kv2.put("状态", "下载完成");
		kv2.put("位置", downloadEntity.getEntrance());
		DataUtils.onEvent(MainActivity.this, "游戏下载位置", downloadEntity.getName(), kv2);

		if (downloadEntity.isPluggable()) {
			Map<String, Object> kv3 = new HashMap<>();
			kv3.put("下载", "下载完成");
			kv3.put("版本", downloadEntity.getPlatform());
			kv3.put("位置", downloadEntity.getEntrance());
			DataUtils.onEvent(MainActivity.this, "插件化", downloadEntity.getName(), kv3);
		}

		Map<String, Object> map = new HashMap<>();
		map.put("game", downloadEntity.getName());
		map.put("game_id", downloadEntity.getGameId());
		if (downloadEntity.isPluggable()) {
			map.put("method", "插件化");
			map.put("btn_status", "插件化");
		} else if (downloadEntity.isUpdate()) {
			map.put("method", "更新");
			map.put("btn_status", "更新");
		} else {
			map.put("method", "正常");
			map.put("btn_status", "下载");
		}
		map.put("platform", PlatformUtils.getInstance(getApplicationContext())
				.getPlatformName(downloadEntity.getPlatform()));
		map.put("status", "完成");
		map.put("entrance", downloadEntity.getEntrance());
		map.put("location", downloadEntity.getLocation());
		map.put("network", NetworkUtils.getConnectedType(MainActivity.this));
		DataCollectionManager.onEvent(MainActivity.this, "download", map);
	}

	private void processHijack(DownloadEntity downloadEntity) {
		// 删除任务
		downloadEntity.setStatus(DownloadStatus.cancel);
		DownloadManager.getInstance(getApplicationContext()).cancel(downloadEntity.getUrl());
		// 弹出提示框
		EventBus.getDefault().post(new EBShowDialog("hijack"));
		// 记录链接被劫持
		Map<String, Object> map = new HashMap<>();
		map.put("url", downloadEntity.getUrl());
		map.put("game", downloadEntity.getName());
		map.put("game_id", downloadEntity.getGameId());
		map.put("platform", downloadEntity.getPlatform());
		DataCollectionManager.onEvent(MainActivity.this, "hijack", map);
		// 上传劫持log
		uploadHijackLog(new HashMap<>(map));
	}

	private void uploadHijackLog(Map<String, Object> map) {
		String version = PackageUtils.getVersion(this);
		String user = DeviceUtils.getDeviceID(this);
		String channel = (String) PackageUtils.getMetaData(this,
				getPackageName(), "TD_CHANNEL_ID");
		map.put("version", version);
		map.put("user", user);
		map.put("channel", channel);
		String url = "http://data.ghzhushou.com/api/v1d0/log";
		Map<String, String> params = new HashMap<>();
		params.put("topic", "hijack");
		params.put("source", "GH-ASSIST-Client");
		params.put("time", String.valueOf(Utils.getTime(this)));
		params.put("content", new JSONObject(map).toString());
		StringExtendedRequest request = new StringExtendedRequest(Method.POST, url, null, null);
		request.setParams(params);
		request.setShouldCache(false);
		AppController.addToRequestQueue(request, TAG);
	}

	/*
	 * 黄壮华 按连续按返回键两次才退出应用
	 */
	private long[] mHits = new long[2];

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
			mHits[mHits.length - 1] = SystemClock.uptimeMillis();
			if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
				finish();
			} else {
				toast("再按一次就退出光环助手了哦");
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("currentTab", currentTab);
	}

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

		// 初始化gameMap
		DownloadManager.getInstance(this).initGameMap();

		View contentView = View.inflate(this, R.layout.activity_main, null);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTheme(R.style.AppTheme);
			setTranslucentStatus(true);
		}
		setContentView(contentView);

		initViews();
		if (savedInstanceState != null) {
			currentTab = savedInstanceState.getInt("currentTab");
		} else {
			currentTab = 0;
		}
		setTabSelection(currentTab);

		sp = getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
		concernManager = new ConcernManager(getApplicationContext());

		getSearchHints();

		isNewFirstLaunch = sp.getBoolean("isNewFirstLaunch", true);
		if (!isNewFirstLaunch && sp.getBoolean("autoupdate", true)) {
			// 检查助手更新
			checkUpdate();
		}
		if (isNewFirstLaunch) {
			getPluginUpdate();
			sp.edit().putBoolean("isNewFirstLaunch", false).apply();
		}

		// 获取免责声明
		getDisclaimer(isNewFirstLaunch);

		// 初始化PlatformUtils
		PlatformUtils.getInstance(getApplicationContext());

		// 解决助手奔溃后导致的下载状态保留问题
		DownloadManager.getInstance(this).checkAll();

		// 添加观察者
		DownloadManager.getInstance(this).addObserver(dataWatcher);

//		//检查是否存在更新的dex包
//		checkHotfix();

		// 检查是否有权限读取应用列表
		checkPermission();

		if (isNewFirstLaunch || TokenUtils.getDeviceId(this) == null) {
			new Thread(){
				@Override
				public void run() {
				// 注册设备
					TokenUtils.register(MainActivity.this);
				}
			}.start();
		}

		// 执行跳转事件
		handler.postDelayed(runnable, 500);

		Log.e("TD_CHANNEL_ID", (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID"));
	}

	private void initViews() {
		home1Layout = (LinearLayout) findViewById(R.id.main_ll_game);
		home2Layout = (LinearLayout) findViewById(R.id.main_ll_news);
		home3Layout = (LinearLayout) findViewById(R.id.main_ll_personal);
		home1Image = (ImageView) findViewById(R.id.main_iv_game);
		home2Image = (ImageView) findViewById(R.id.main_iv_news);
		home3Image = (ImageView) findViewById(R.id.main_iv_personal);
		home1Title = (TextView) findViewById(R.id.main_tv_game);
		home2Title = (TextView) findViewById(R.id.main_tv_news);
		home3Title = (TextView) findViewById(R.id.main_tv_personal);
		home1Layout.setOnClickListener(this);
		home2Layout.setOnClickListener(this);
		home3Layout.setOnClickListener(this);
	}

	private void checkPermission() {
		ArrayList<String> list = PackageUtils.getAllPackageName(getApplicationContext());
		if (list.isEmpty()) {
			// 无权限获取应用列表
			Spanned content = Html.fromHtml("请前往系统权限设置，把“" +
					"<font color='#ff0000'>读取应用列表</font>”选择为打开" +
					"“<font color='#ff0000'>允许</font>”，否则光环助手将无法帮您安装插件加速版的游戏");
			DialogUtils.showWarningDialog(this, "提示", content, "忽略", "去开启",
					new DialogUtils.ConfiremListener() {
						@Override
						public void onConfirem() {
							// 跳转应用信息界面
							Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							Uri uri = Uri.fromParts("package", getPackageName(), null);
							intent.setData(uri);
							startActivityForResult(intent, 0x123);
						}
					}, null);
		} else {
			getInstalledListFromServer(list);
		}
	}

	private int iCount;

	private void addInstalledCount() {
		synchronized (MainActivity.class) {
			iCount++;
		}
	}

	// 获取已安装游戏
	private void getInstalledListFromServer(ArrayList<String> list) {
		PackageManager manager = new PackageManager(getApplicationContext());
		manager.initInstalledMap(list);

		final int size = list.size();
		iCount = 0;
		for (int i = 0; i < size; i++) {
			final String packageName = list.get(i);
			JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
					Config.HOST + "v1d45/support/package/" + packageName + "/game/digest",
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							if (response.length() != 0) {
								Gson gson = new Gson();
								GameDigestEntity gameDigestEntity = gson.fromJson(
										response.toString(), GameDigestEntity.class);
								GameInfo gameInfo = new GameInfo();
								gameInfo.setId(gameDigestEntity.getId());
								gameInfo.setPackageName(packageName);
								concernManager.updateByEntity(gameInfo);
							}
							addInstalledCount();
							if (iCount == size) {
								updateConcern();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							addInstalledCount();
							if (iCount == size) {
								updateConcern();
							}
						}
					});
			AppController.addToRequestQueue(request, TAG);
		}
	}

	private int cCount;

	private void addConcernCount() {
		synchronized (MainActivity.class) {
			cCount++;
		}
	}

	private void updateConcern() {
		// 移除疑似游戏数据库中所有数据
		SuspectedGameManager suspectedGameManager = new SuspectedGameManager(getApplicationContext());
		suspectedGameManager.deleteAll();

		ArrayList<String> concernIdList = new ArrayList<>();
		for (ConcernInfo entity : concernManager.getAllConcern()) {
			concernIdList.add(entity.getId());
		}
		if (concernIdList.isEmpty()) {
			update();
		} else {
			final int size = concernIdList.size();
			cCount = 0;
			for (int i = 0; i < size; i++) {
				JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
						Config.HOST + "v2d0/game/" + concernIdList.get(i) + "/digest",
						new Response.Listener<JSONObject>() {
							@Override
							public void onResponse(JSONObject response) {
								Gson gson = new Gson();
								GameEntity gameEntity = gson.fromJson(response.toString(), GameEntity.class);
								ConcernInfo concernInfo = concernManager.findConcernById(gameEntity.getId());
								if (concernInfo != null && gameEntity.getApk() != null
										&& gameEntity.getApk().size() != 0) {
									HashMap<String, Boolean> packageNames = new HashMap<>();
									String packageName;
									for (int i = 0, size = gameEntity.getApk().size(); i < size; i++) {
										packageName = gameEntity.getApk().get(i).getPackageName();
										if (PackageManager.isInstalled(packageName)) {
											packageNames.put(packageName, true);
										} else {
											packageNames.put(packageName, false);
										}
									}
									concernInfo.setTime(System.currentTimeMillis());
									concernInfo.setPackageNames(packageNames);
									concernManager.updateByConcern(concernInfo);
								}
								if (isNewFirstLaunch) {
									//默认安装即为关注
									if (!concernManager.isConcern(gameEntity.getId())) {
										concernManager.addByEntity(gameEntity);
									}
								}
								addConcernCount();
								if (cCount == size) {
									update();
								}
							}
						}, new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								addConcernCount();
								if (cCount == size) {
									update();
								}
							}
						});
				AppController.addToRequestQueue(request, TAG);
			}
		}
	}

	/*
	 * 更新关注列表数据
	 */
	private void update() {
		new Thread(){
			@Override
			public void run() {
				TrafficUtils spy = TrafficUtils.getInstance(getApplicationContext(), true);
				List<ConcernInfo> concernList = concernManager.getAllConcern();
				for (ConcernInfo concernEntity : concernList) {
					concernEntity.setTime(System.currentTimeMillis());
					int quantity = 0;
					HashMap<String, Boolean> packageNames = new HashMap<>();
					for (String packageName : concernEntity.getPackageNames().keySet()) {
						if (PackageManager.isInstalled(packageName)) {
							quantity++;
							packageNames.put(packageName, true);
						} else {
							packageNames.put(packageName, false);
						}
					}
					concernEntity.setPackageNames(packageNames);
					concernEntity.setInstalled(quantity > 0);
					concernEntity.setInstalledQuantity(quantity);
					String tag = null;
					int weight = 0;
					if (concernEntity.isConcern() && concernEntity.isInstalled()) {
						tag = "已关注,已安装";
						weight = 2;
					} else if (concernEntity.isConcern()
							&& !concernEntity.isInstalled()) {
						tag = "已关注";
						weight = 1;
					} else if (!concernEntity.isConcern()
							&& concernEntity.isInstalled()) {
						tag = "已安装";
						weight = 1;
					}
					concernEntity.setTag(tag);
					long traffic = spy.getTraffic(new ArrayList<>(concernEntity.getPackageNames().keySet()));
					concernEntity.setTraffic(traffic);
					if (traffic > 0) {
						weight++;
					}
					concernEntity.setWeight(weight);
					if (weight == 0) {
						concernManager.deleteConcern(concernEntity.getId());
					} else {
						concernManager.updateByConcern(concernEntity);
					}
				}

				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						ArrayList<String> concernList = new ArrayList<>();
						for (ConcernInfo entity : concernManager.getAllConcern()) {
							if (entity.isConcern()) {
								concernList.add(entity.getGameName());
							}
						}
						Map<String, Object> map = new HashMap<>();
						map.put("type", Build.MODEL);
						map.put("system", Build.VERSION.SDK_INT + "=" + Build.VERSION.RELEASE);
						map.put("install", PackageManager.getInstalledList());
						map.put("concern", concernList);
						DataCollectionManager.upsert(MainActivity.this, "user", map);
					}
				}, 1000);

				// 检查游戏更新
				checkGameUpdate();

				// 检查可插件化游戏
				checkGamePlugin();
			}
		}.start();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 0x123) {
			ArrayList<String> list = PackageUtils.getAllPackageName(getApplicationContext());
			if (list.isEmpty()) {
				toast("读取应用列表失败");
			} else {
				getInstalledListFromServer(list);
			}
		}
	}

	private void checkGameUpdate() {
		ArrayList<String> list = new ArrayList<>();
		List<ConcernInfo> infos = concernManager.getInstalledGame();
		for (ConcernInfo info : infos) {
			for (String packageName : info.getPackageNames().keySet()) {
				if (info.getPackageNames().get(packageName)) {
					list.add(packageName);
				}
			}
		}

		Comparator<String> comparator = new Comparator<String>() {
			@Override
			public int compare(String lhs, String rhs) {
				return lhs.compareTo(rhs);
			}
		};
		Collections.sort(list, comparator);

		StringBuilder builder = new StringBuilder();
		String packages;
		PackageManager.clearUpdateList();
		for (int i = 0, sizei = (list.size() / 10) + 1; i < sizei; i++) {
			builder.delete(0, builder.length());
			for (int j = i * 10, sizej = (i + 1) * 10 > list.size() ? list
					.size() : (i + 1) * 10; j < sizej; j++) {
				builder.append(list.get(j));
				builder.append("-");
			}
			if (builder.length() != 0) {
				packages = builder.substring(0, builder.length() - 1);
				JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
						Config.HOST + "v1d45/support/package/update?package=" + packages,
                    new Response.Listener<JSONArray>() {
						@Override
						public void onResponse(JSONArray response) {
							if (response.length() != 0) {
								Gson gson = new Gson();
								Type listType = new TypeToken<ArrayList<GameUpdateEntity>>() {}.getType();
								ArrayList<GameUpdateEntity> games = gson.fromJson(response.toString(), listType);
								GameUpdateEntity gameUpdateEntity;
								for (int i = 0; i < games.size(); i++) {
									gameUpdateEntity = games.get(i);
									// 判断是否gh_version是否相同
									String gh_version = (String) PackageUtils.getMetaData(
											MainActivity.this, gameUpdateEntity.getPackageName(), "gh_version");
									if (gh_version != null) {
										gh_version = gh_version.substring(2);
										// 判断gh_version是否相同
										if (gh_version.equals(gameUpdateEntity.getGhVersion())) {
											// 判断version是否相同
											String version = PackageUtils.getVersionByPackage(
													MainActivity.this, gameUpdateEntity.getPackageName());
											if (version != null && version.equals(gameUpdateEntity.getVersion())) {
												// 版本相同,无需显示插件更新,继续查看是否有可更新的游戏包
												games.remove(i);
												i--;
											}
										}
									} else {
										games.remove(i);
										i--;
									}
								}
								PackageManager.addUpdateList(games);

								EventBus.getDefault().post(new EBDownloadStatus("update"));
							}
						}
					}, null);
				AppController.addToRequestQueue(request, TAG);
			}
		}
	}

	private int count;

	private void addCount() {
		synchronized (MainActivity.class) {
			count++;
		}
	}

	private void checkGamePlugin() {
		List<ConcernInfo> infos = concernManager.getInstalledGame();
		final int size = infos.size();
		final List<GameEntity> list = new ArrayList<>();
		count = 0;
		for (ConcernInfo info : infos) {
			JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
					TimestampUtils.addTimestamp(Config.HOST + "v2d0/game/" + info.getId() + "/digest",
							Constants.GAME_CD),
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							Gson gson = new Gson();
							GameEntity gameEntity = gson.fromJson(response.toString(), GameEntity.class);
							list.add(gameEntity);
							addCount();
							if (count == size) {
								processPluginData(list);
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							addCount();
							if (count == size) {
								processPluginData(list);
							}
						}
					});
			AppController.addToRequestQueue(request, TAG);
		}
	}

	private void processPluginData(List<GameEntity> list) {
		if (list == null || list.isEmpty()) {
			return;
		}
		List<ConcernInfo> infos = concernManager.getInstalledGame();
		HashMap<String, Boolean> map;
		GameEntity gameEntity;
		for (ConcernInfo info : infos) {
			for (int i = 0, size = list.size(); i < size; i++) {
				gameEntity = list.get(i);
				if (gameEntity.getId().equals(info.getId())
						&& gameEntity.getTag() != null && gameEntity.getTag().size() != 0
						&& gameEntity.getApk() != null) {
					map = info.getPackageNames();
					for (String key : map.keySet()) {
						if (map.get(key) && !PackageUtils.isSignature(this, key)) {
							for (ApkEntity apkEntity : gameEntity.getApk()) {
								if (apkEntity.getPackageName().equals(key)) {
									GameUpdateEntity gameUpdateEntity = new GameUpdateEntity();
									gameUpdateEntity.setId(gameEntity.getId());
									gameUpdateEntity.setIcon(gameEntity.getIcon());
									gameUpdateEntity.setName(gameEntity.getName());
									gameUpdateEntity.setPackageName(apkEntity.getPackageName());
									gameUpdateEntity.setSize(apkEntity.getSize());
									gameUpdateEntity.setVersion(apkEntity.getVersion());
									gameUpdateEntity.setGhVersion(apkEntity.getGhVersion());
									gameUpdateEntity.setUrl(apkEntity.getUrl());
									gameUpdateEntity.setPlatform(apkEntity.getPlatform());
									gameUpdateEntity.setEtag(apkEntity.getEtag());
									gameUpdateEntity.setPluggable(true);
									gameUpdateEntity.setTag(gameEntity.getTag());
									gameUpdateEntity.setBrief(gameEntity.getBrief());

									PackageManager.addUpdate(gameUpdateEntity);
									break;
								}
							}
							GameManager manager = new GameManager(this);
							manager.addOrUpdate(gameEntity.getApk(), gameEntity.getId(), gameEntity.getName());
						}
					}
					break;
				}
			}
		}
		EventBus.getDefault().post(new EBDownloadStatus("plugin"));
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus) {
			FrameLayout main_content = (FrameLayout) findViewById(R.id.main_content);
			if (main_content.getPaddingBottom() == 0) {
				main_content.setPadding(0, 0, 0, findViewById(R.id.main_ll_bottom).getHeight());
			}
		}
	}

	private void checkHotfix() {
        String version = PackageUtils.getVersion(getApplicationContext());
        String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID");
        String url = "http://api.ghzhushou.com/v1d45/hotfix?channel=" + TD_CHANNEL_ID + "&version=" + version;
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
				new Response.Listener<JSONArray>() {
		            @Override
		            public void onResponse(JSONArray response) {
		                Utils.log("hotfix = " + response.toString());
		                try {
		                    for (int i = 0; i < response.length(); i++) {
		                        JSONObject jsonObject = response.getJSONObject(i);
		                        String clazz = jsonObject.getString("class");
		                        final String url = jsonObject.getString("url");
		                        String fileName = url.substring(url.lastIndexOf("/"));
		                        File directory = new File(getFilesDir().getAbsolutePath() + File.separator + "hotfix");
		                        if (!directory.exists() || !directory.isDirectory()) {
		                            directory.mkdirs();
		                        }
		                        File file = new File(directory.getAbsolutePath() + File.separator + fileName);
		                        if (file.exists()) {
		                            break;
		                        }
		                        //下载文件
		                        final String savePath = file.getAbsolutePath();
		                        new Thread(){
		                            @Override
		                            public void run() {
		                                try {
		                                    FileUtils.downloadFile(url, savePath);
		                                } catch (IOException e) {
		                                    e.printStackTrace();
		                                }
		                                Utils.log(savePath + " download success");
		                            }
		                        }.start();
		                        //存储class
		                        sp.edit().putString(file.getName(),clazz).apply();
		                    }
		                } catch (JSONException e) {
		                    e.printStackTrace();
		                }
		            }
		        }, null);
        AppController.addToRequestQueue(request, TAG);
	}

	// 获取免责声明
	private void getDisclaimer(final boolean isFirst) {
		JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
				Config.HOST + "v2/disclaimer",
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						if (!isDestroy) {
							try {
								boolean isShow = response.getBoolean("isShow");
								sp.edit().putBoolean("isShowDisclaimer", isShow).apply();
								if (isShow) {
									String content = response.getString("content");
									sp.edit().putString("disclaimer", content).apply();
									if (isFirst) {
										DialogUtils.showDisclaimerDialog(MainActivity.this, content);
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				}, null);
		AppController.addToRequestQueue(request, TAG);
	}

	private Class<?> intentClass(String to) {
		try {
			return Class.forName("com.gh.gamecenter." + to);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			if (getIntent() != null && getIntent().getExtras() != null) {
				String to = getIntent().getExtras().getString("to");
				if(!TextUtils.isEmpty(to)){
					Class<?> clazz = intentClass(to);
					if (clazz != null) {
						Intent toIntent = new Intent(MainActivity.this, clazz);
						if ("NewsDetailActivity".equals(to)) {
							toIntent.putExtra("newsId", getIntent().getExtras().getString("newsId"));
							toIntent.putExtra("entrance", getIntent().getExtras().getString("entrance"));
						} else if("DownloadManagerActivity".equals(to)) {
							toIntent.putExtra("packageName" , getIntent().getExtras().getString("packageName"));
							toIntent.putExtra("currentItem" , 1);
						} else if ("GameDetailActivity".equals(to)) {
							toIntent.putExtra("gameId", getIntent().getExtras().getString("gameId"));
							toIntent.putExtra("entrance", getIntent().getExtras().getString("entrance"));
						} else if ("SubjectActivity".equals(to)) {
							toIntent.putExtra("id", getIntent().getExtras().getString("id"));
							toIntent.putExtra("name", getIntent().getExtras().getString("name"));
							toIntent.putExtra("order", getIntent().getExtras().getBoolean("order"));
						} else if ("ViewImageActivity".equals(to)) {
							toIntent.putExtra("urls" , getIntent().getExtras().getStringArrayList("urls"));
							toIntent.putExtra("current" , getIntent().getExtras().getInt("current",0));
							toIntent.putExtra("ScaleType" , getIntent().getExtras().getString("ScaleType"));
						}
						startActivity(toIntent);
					}
				} else {
					String from = getIntent().getStringExtra("from");
					if (!TextUtils.isEmpty(from)) {
						if (from.equals("plugin")) {
							String packageName = getIntent().getStringExtra("packageName");
							Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class);
							intent.putExtra("currentItem", 1);
							intent.putExtra("packageName", packageName);
							startActivity(intent);
						} else if (from.equals("mipush_news")) {
							Intent intent = new Intent(MainActivity.this, NewsDetailActivity.class);
							intent.putExtra("entrance", "小米推送");
							intent.putExtra("entity", getIntent().getSerializableExtra("entity"));
							startActivity(intent);
						} else if (from.equals("mipush_new_game")) {
							Intent intent = new Intent(MainActivity.this, GameDetailActivity.class);
							intent.putExtra("entrance", "小米推送");
							startActivity(intent);
						} else if (from.equals("mipush_plugin")) {
							Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class);
							intent.putExtra("currentItem", 1);
							intent.putExtra("isPushIntent", true);
							startActivity(intent);
						} else if (from.equals("plugin_install")) {
							Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class);
							intent.putExtra("currentItem", 0);
							intent.putExtra("path", getIntent().getStringExtra("path"));
							startActivity(intent);
						}
					}
				}
			}
		}
	};

	private void getSearchHints() {
		final String url = Config.HOST + "v1d45/search/game/default";
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(url,
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						if (!isDestroy && response.length() != 0) {
							Type listType = new TypeToken<ArrayList<String>>() {}.getType();
							Gson gson = new Gson();
							List<String> searchHintList = gson.fromJson(response.toString(), listType);
							if (searchHintList != null && searchHintList.size() != 0) {
								if (searchHintList.size() == 1) {
									searchHint = searchHintList.get(0);
								} else {
									searchHint = searchHintList.get(RandomUtils.nextInt(searchHintList.size()));
								}
								EventBus.getDefault().post(new EBTopStatus("搜索", searchHintList.get(0)));
							}
						}
					}
				}, null);
		AppController.addToRequestQueue(request, TAG);
	}

	private void checkUpdate() {
		String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(this, getPackageName(), "TD_CHANNEL_ID");
		String url = Config.HOST + "v2/version?version_name=" + PackageUtils.getVersion(getApplicationContext())
				+ "&channel=" + TD_CHANNEL_ID;
		JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(url,
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						if (!isDestroy && response.length() != 0) {
							Gson gson = new Gson();
							appEntity = gson.fromJson(response.toString(), AppEntity.class);

							float version = Float.valueOf(appEntity.getVersion());
							float currentVersion = Float.valueOf(PackageUtils.getVersion(getApplicationContext()));
							if (version > currentVersion) {
								// 光环助手 有更新
								GameUpdateEntity game = new GameUpdateEntity();
								game.setName("光环助手V" + appEntity.getVersion());
								game.setPackageName(getPackageName());
								game.setSize(appEntity.getSize());
								game.setVersion(appEntity.getVersion());
								game.setUrl(appEntity.getUrl());
								game.setPlatform("官方版");
								PackageManager.addUpdate(0, game);

								String updateMD5 = MD5Utils.getUpdateMD5(appEntity.getUrl(), appEntity.getContent());
								if (appEntity.isIs_force()) {
									// 强制更新
									showUpdateDialog(updateMD5);
								} else {
									// 非强制更新
									if ("EVERY_TIME_OPEN".equals(appEntity.getAlet_type())) {
										// 每次都提示
										showUpdateDialog(updateMD5);
									} else {
										// 一天提示一次
										String showUpdateTime = sp.getString("show_update_tiem", null);
										SimpleDateFormat format = new SimpleDateFormat(
												"yyyy-MM-dd", Locale.getDefault());
										String today = format.format(new Date());
										if (!today.equals(showUpdateTime)) {
											sp.edit().putString("show_update_tiem", today).apply();
											showUpdateDialog(updateMD5);
										}
									}
								}
							}
						}
					}
				}, null);
		AppController.addToRequestQueue(request, TAG);
	}

	private void showUpdateDialog(final String md5) {
		final Dialog updateDialog = new Dialog(this);
		View view = View.inflate(this, R.layout.app_update_hint_dialog, null);

		TextView content = (TextView) view.findViewById(R.id.updeta_content);
		content.setText(Html.fromHtml(appEntity.getContent()));

		TextView versison = (TextView) view.findViewById(R.id.update_app_version);
		versison.setText(String.format("光环助手V%s更新内容：",appEntity.getVersion()));

		TextView size = (TextView) view.findViewById(R.id.update_app_size);
		size.setText(String.format("大小：%s", appEntity.getSize()));

		view.findViewById(R.id.update_cannel).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						if (appEntity.isIs_force()) {
							finish();
						} else {
							updateDialog.dismiss();
						}
					}
				});

		view.findViewById(R.id.updeta_confirm).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {
						updateDialog.dismiss();
						String path = FileUtils.getDownloadPath(MainActivity.this,
								"光环助手V" + appEntity.getVersion() + "_" + md5 + ".apk");
						File file = new File(path);
						if (file.exists() && file.length() > 0) {
							startActivity(PackageUtils.getInstallIntent(path));
						} else {
							DataUtils.onEvent(MainActivity.this, "软件更新", "下载开始");
							showDownloadDialog(md5);
						}
					}
				});

		if (appEntity.isIs_force()) {
			updateDialog.setCanceledOnTouchOutside(false);
			updateDialog.setCancelable(false);
		}
		updateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		updateDialog.setContentView(view);
		updateDialog.show();
	}

	private Dialog dialog;
	private ProgressBar app_pb_progress;
	private TextView app_tv_speed;
	private TextView app_tv_percent;
	private TextView app_tv_cancel;

	private void showDownloadDialog(String md5) {
		dialog = new Dialog(this);

		View view = View.inflate(this, R.layout.app_updating_dialog, null);

		app_pb_progress = (ProgressBar) view.findViewById(R.id.app_pb_progress);
		app_tv_speed = (TextView) view.findViewById(R.id.app_tv_speed);
		app_tv_percent = (TextView) view.findViewById(R.id.app_tv_percent);

		app_tv_cancel = (TextView) view.findViewById(R.id.app_tv_cancel);
		app_tv_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DownloadManager.getInstance(getApplicationContext()).cancel(appEntity.getUrl());
				if (appEntity.isIs_force()) {
					finish();
				} else {
					dialog.dismiss();
					isShowDownload = false;
				}
			}
		});

		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.closeOptionsMenu();
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(view);
		dialog.show();

		isShowDownload = true;

		String path = FileUtils.getDownloadPath(MainActivity.this,
				"光环助手V" + appEntity.getVersion() + "_" + md5 + ".apk");
		File file = new File(path);
		if (file.exists()) {
			file.delete();
		}

		DownloadEntity downloadEntity = new DownloadEntity();
		downloadEntity.setUrl(appEntity.getUrl());
		downloadEntity.setName("光环助手V" + appEntity.getVersion());
		downloadEntity.setPath(path);
		downloadEntity.setPlatform("官方版");
		downloadEntity.setPackageName(getPackageName());
		DownloadManager.getInstance(getApplicationContext()).cancel(downloadEntity.getUrl(), false);
		DownloadManager.getInstance(getApplicationContext()).pauseAll();
		DownloadManager.getInstance(getApplicationContext()).add(downloadEntity);
	}

	private void processGhAssistDownload(DownloadEntity downloadEntity) {
		app_tv_speed.setText(String.format("%s(剩%s)", SpeedUtils.getSpeed(downloadEntity.getSpeed()),
				SpeedUtils.getRemainTime(downloadEntity.getSize(),
						downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
		app_pb_progress.setProgress((int) (downloadEntity.getPercent() * 10));
		app_tv_percent.setText(downloadEntity.getPercent() + "%");
		if (DownloadStatus.done.equals(downloadEntity.getStatus())) {
			DownloadManager.getInstance(getApplicationContext()).cancel(downloadEntity.getUrl(), false);
			dialog.dismiss();
			isShowDownload = false;
		}
	}

	// 获取META-INF中的plugin_update 文件，判断是否从游戏插件中下载的app，是则获取游戏id，启动游戏更新，下载该游戏
	private void getPluginUpdate() {
		ApplicationInfo appinfo = getApplicationInfo();
		String sourceDir = appinfo.sourceDir;
		ZipFile zipfile = null;
		try {
			zipfile = new ZipFile(sourceDir);
			Enumeration<?> entries = zipfile.entries();
			while (entries.hasMoreElements()) {
				ZipEntry entry = ((ZipEntry) entries.nextElement());
				String entryName = entry.getName();
				if (entryName.contains("gh_assist")) {
					String packageName = entryName.substring(entryName.lastIndexOf("_") + 1);
					Intent intent = new Intent(MainActivity.this, DownloadManagerActivity.class);
					intent.putExtra("currentItem", 1);
					intent.putExtra("packageName", packageName);
					startActivity(intent);
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (zipfile != null) {
				try {
					zipfile.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		final int id = v.getId();
		if (id == R.id.main_ll_game) {
			EventBus.getDefault().post(new EBUISwitch("MainActivity", 0));
			setTabSelection(0);
		} else if (id == R.id.main_ll_news) {
			EventBus.getDefault().post(new EBUISwitch("MainActivity", 1));
			setTabSelection(1);
		} else if (id == R.id.main_ll_personal) {
			EventBus.getDefault().post(new EBUISwitch("MainActivity", 2));
			setTabSelection(2);
		}
	}

	private void setTabSelection(int index) {
		clearSelection();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		hideFragments(transaction);
		switch (index) {
			case 0:
				home1Image.setImageResource(R.drawable.home1_selected);
				home1Title.setTextColor(getResources().getColor(R.color.theme));
				if (gameFragment == null) {
					List<Fragment> list = getSupportFragmentManager().getFragments();
					if (list != null) {
						for (Fragment fragment : list) {
							if (fragment.getClass().equals(GameFragment.class)) {
								gameFragment = (GameFragment) fragment;
								transaction.show(gameFragment);
								break;
							}
						}
					}
					if (gameFragment == null) {
						gameFragment = new GameFragment();
						transaction.add(R.id.main_content, gameFragment);
					}
				} else {
					transaction.show(gameFragment);
				}
				currentTab = 0;
				break;
			case 1:
				home2Image.setImageResource(R.drawable.home2_selected);
				home2Title.setTextColor(getResources().getColor(R.color.theme));
				if (newsFragment == null) {
					List<Fragment> list = getSupportFragmentManager().getFragments();
					if (list != null) {
						for (Fragment fragment : list) {
							if (fragment.getClass().equals(NewsFragment.class)) {
								newsFragment = (NewsFragment) fragment;
								transaction.show(newsFragment);
								break;
							}
						}
					}
					if (newsFragment == null) {
						newsFragment = new NewsFragment();
						transaction.add(R.id.main_content, newsFragment);
					}
				} else {
					transaction.show(newsFragment);
				}
				currentTab = 1;
				break;
			case 2:
				home3Image.setImageResource(R.drawable.home3_selected);
				home3Title.setTextColor(getResources().getColor(R.color.theme));
				if (personalFragment == null) {
					List<Fragment> list = getSupportFragmentManager().getFragments();
					if (list != null) {
						for (Fragment fragment : list) {
							if (fragment.getClass().equals(PersonalFragment.class)) {
								personalFragment = (PersonalFragment) fragment;
								transaction.show(personalFragment);
								break;
							}
						}
					}
					if (personalFragment == null) {
						personalFragment = new PersonalFragment();
						transaction.add(R.id.main_content, personalFragment);
					}
				} else {
					transaction.show(personalFragment);
				}
				currentTab = 2;
				break;
			default:
				break;
		}
		transaction.commit();
	}

	/**
	 * 清除掉所有的选中状态。
	 */
	private void clearSelection() {
		home1Image.setImageResource(R.drawable.home1_unselected);
		home2Image.setImageResource(R.drawable.home2_unselected);
		home3Image.setImageResource(R.drawable.home3_unselected);
		home1Title.setTextColor(getResources().getColor(R.color.title));
		home2Title.setTextColor(getResources().getColor(R.color.title));
		home3Title.setTextColor(getResources().getColor(R.color.title));
	}

	/**
	 * 将所有的Fragment都置为隐藏状态。
	 */
	private void hideFragments(FragmentTransaction transaction) {
		if (personalFragment != null) {
			transaction.hide(personalFragment);
		}
		if (gameFragment != null) {
			transaction.hide(gameFragment);
		}
		if (newsFragment != null) {
			transaction.hide(newsFragment);
		}

		List<Fragment> list = getSupportFragmentManager().getFragments();
		if (list != null) {
			for (Fragment fragment : list) {
				transaction.hide(fragment);
			}
		}
	}

	public void onEventMainThread(EBSkip skip) {
		if ("GameFragment".equals(skip.getType())) {
			home1Layout.performClick();
			EventBus.getDefault().post(new EBSkip("MainActivity", skip.getCurrentItem()));
		}
	}

	public void onEventMainThread(EBPackage busFour) {
		String packageName = busFour.getPackageName();
		if ("安装".equals(busFour.getType())) {
			// 添加进已安装map中
			PackageManager.addInstalled(packageName);
		} else if ("卸载".equals(busFour.getType())) {
			// 删除map中数据
			PackageManager.removeInstalled(packageName);
		}
		DownloadEntity mDownloadEntity = null;
		for (DownloadEntity downloadEntity : DownloadManager.getInstance(
				getApplicationContext()).getAll()) {
			if (packageName.equals(downloadEntity.getPackageName())) {
				mDownloadEntity = downloadEntity;
				break;
			}
		}
		if (mDownloadEntity != null) {
			if ("安装".equals(busFour.getType())) {
				if (mDownloadEntity.isPluggable()) {
					Map<String, Object> kv6 = new HashMap<>();
					kv6.put("安装或卸载", "安装完成");
					DataUtils.onEvent(this, "插件化", mDownloadEntity.getName(), kv6);
				}

				if (!mDownloadEntity.isPlugin() // 不是插件游戏，自己删除数据库数据和安装包
						|| PackageUtils.isSignature(this, packageName)) {// 是插件游戏，判断签名是否相同，是才删除数据库数据和安装包
					DownloadManager.getInstance(getApplicationContext()).cancel(
							mDownloadEntity.getUrl(), sp.getBoolean("autodelete", true));
				}

			} else if ("卸载".equals(busFour.getType())) {
				Map<String, Object> kv6 = new HashMap<>();
				kv6.put("安装或卸载", "卸载完成");
				DataUtils.onEvent(this, "插件化", mDownloadEntity.getName(), kv6);

				startActivity(PackageUtils.getInstallIntent(mDownloadEntity.getPath()));
			}
		}
		if ("安装".equals(busFour.getType())) {
			GameManager gameManager = new GameManager(getApplicationContext());
			GameInfo gameEntity = gameManager.findGame(packageName);
			if (gameEntity != null) {
				concernManager.updateByEntity(gameEntity);
			} else {
				FilterManager filterManager = new FilterManager(
						getApplicationContext());
				if (!filterManager.isFilter(packageName)) {
					SuspectedGameManager suspectedGameManager = new SuspectedGameManager(
							getApplicationContext());
					suspectedGameManager.addGame(new SuspectedGameInfo(
							packageName, System.currentTimeMillis()));
				}
			}
		} else if ("卸载".equals(busFour.getType())) {
			FilterManager filterManager = new FilterManager(
					getApplicationContext());
			if (!filterManager.isFilter(packageName)) {
				SuspectedGameManager suspectedGameManager = new SuspectedGameManager(
						getApplicationContext());
				suspectedGameManager.deleteSuspectedGame(packageName);

				concernManager.updateByPackageName(packageName);
			}
		}
		if ("卸载".equals(busFour.getType())) {
			ArrayList<GameUpdateEntity> list = PackageManager.getUpdateList();
			GameUpdateEntity game;
			int index = -1;
			for (int i = 0, size = list.size(); i < size; i++) {
				game = list.get(i);
				if (!game.isPluggable()) {
					continue;
				}
				if (game.getPackageName().equals(packageName)) {
					index = i;
					break;
				}
			}
			if (index != -1) {
				PackageManager.removeUpdateList(packageName);
			}
		}

		if ("安装".equals(busFour.getType())) {
			// 安装后关注游戏
			JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
					Config.HOST + "v1d45/support/package/" + packageName + "/game/digest",
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							if (response.length() != 0) {
								Gson gson = new Gson();
								GameDigestEntity gameDigestEntity = gson.fromJson(
										response.toString(), GameDigestEntity.class);
								concernGame(gameDigestEntity.getId());
							}
						}
					}, null);
			AppController.addToRequestQueue(request, TAG);
		}

		Map<String, Object> map = new HashMap<>();
		map.put("type", busFour.getType());
		map.put("packageName", busFour.getPackageName());
		DataCollectionManager.onEvent(this, "inorunstall", map);
	}

	private void concernGame(String id) {
		if (!concernManager.isConcern(id)) {
			JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
					Config.HOST + "v2d0/game/" + id + "/digest",
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							Gson gson = new Gson();
							GameEntity gameEntity = gson.fromJson(response.toString(), GameEntity.class);
							concernManager.addByEntity(gameEntity);
						}
					}, null);
			AppController.addToRequestQueue(request, TAG);
		}
	}

	@Override
	public void finish() {
		// 上传数据
		DataCollectionManager.getInstance(getApplicationContext()).statClickData();
		super.finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isDestroy = true;
		AppController.canclePendingRequests(TAG);
		DownloadManager.getInstance(this).removeObserver(dataWatcher);
		gameFragment = null;
		personalFragment = null;
		home1Layout = null;
		home2Layout = null;
		home3Layout = null;
		home1Image = null;
		home2Image = null;
		home3Image = null;
		home1Title = null;
		home2Title = null;
		home3Title = null;
		sp = null;
		dialog = null;
		app_pb_progress = null;
		app_tv_speed = null;
		app_tv_percent = null;
		app_tv_cancel = null;
		appEntity = null;
		handler = null;
		dataWatcher = null;
	}
}
