package com.gh.common.view;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.support.v4.util.ArrayMap;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DialogUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.common.util.FileUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.NetworkUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.PlatformUtils;
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.DownloadManagerActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.entity.ApkEntity;
import com.gh.gamecenter.entity.GameCollectionEntity;
import com.gh.gamecenter.entity.GameEntity;
import com.gh.gamecenter.eventbus.EBDownloadStatus;
import com.gh.gamecenter.eventbus.EBPackage;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.PackageManager;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import de.greenrobot.event.EventBus;

/**
 * 
 * @author 温冠超
 * @email 294299195@qq.com
 * @date 2015-8-12
 * @update 2015-8-12
 * @des 弹出游戏版本下载按钮，点击并添加到下载任务中
 */
public class DownloadDialog {

	private static DownloadDialog instance;

	private Context context;

	private boolean isShow;

	private DownloadDialog(Context context) {
		this.context = context;
		isShow = false;
	}

	public static DownloadDialog getInstance(Context context) {
		if (instance == null) {
			instance = new DownloadDialog(context);
		}
		return instance;
	}

	private DataWatcher dataWatcher = new DataWatcher() {
		@Override
		public void onDataChanged(DownloadEntity downloadEntity) {
			if (downloadEntity.getName().equals(gameEntity.getName())
					&& !"delete".equals(DownloadManager.getInstance(context).getStatus(downloadEntity.getUrl()))) {
				entryMap.put(downloadEntity.getUrl(), downloadEntity);

				Integer location = locationMap.get(downloadEntity.getUrl());
				if (location != null) {
					int position = (int) Math.ceil((location + 1) / (double) (row * column));

					if (position - 1 < adapterMap.size()) {
						adapterMap.get(position - 1).notifyItemChanged(location % (row * column));
					}

					if (collectionAdapterMap != null && position - 1 < collectionAdapterMap.size()){
						if ( collectionAdapterMap.size() >= position - 1 && collectionAdapterMap.size() >= 1){
							collectionAdapterMap.get(position - 1).notifyItemChanged(location % (row * column));
						}
					}
				}
			}
		}
	};

	private PopupWindow popupWindow;

	private ArrayMap<String, Integer> locationMap;
	private ArrayMap<String, DownloadEntity> entryMap;
	private SparseArray<RecyclerViewAdapter> adapterMap;
	private SparseArray<RecyclerViewAdapter> collectionAdapterMap;//存储合集的adapter
	private ArrayMap<String, String> urlMap;

	private List<ApkEntity> gameApk;
	private GameEntity gameEntity;
	private List<GameCollectionEntity> gameCollection;//游戏合集
	private List<ApkEntity> gameCollectionApk; //和合集合并后的apk集合
	private String entrance;
	private String location;
	private LinearLayout linearLayout;
	private ViewPager viewPager;
	private LinearLayout llCollection;
	private ViewPager collectionViewPager;
	private LinearLayout collectionLinearLayout;

	//两个全局变量用来定位收缩集合
	private int colseCollectionPosition;
	private int colseAdapterPosition;

	private int row;
	private int column;

	private List<int[]> collectionPositionlist;//存储集合位置

	public void showPopupWindow(View view, GameEntity gameEntity, String entrance, String location) {

		if (isShow) {
			return;
		}
		isShow = true;

		this.gameEntity = gameEntity;
		this.entrance = entrance;
		this.location = location;

		SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
		row = sp.getInt("download_box_row", 3);
		column = sp.getInt("download_box_column", 3);

		entryMap = new ArrayMap<>();
		List<DownloadEntity> entries = DownloadManager.getInstance(context).getAll();
		for (int i = 0, size = entries.size(); i < size; i++) {
			if (entries.get(i).getName().equals(gameEntity.getName())) {
				entryMap.put(entries.get(i).getUrl(), entries.get(i));
			}
		}

		gameApk = sortApk(new ArrayList<>(gameEntity.getApk()));

		if (gameEntity.getCollection() != null){
			mergeApkCollection(gameEntity);
		}

		// 一个自定义的布局，作为显示的内容
		View contentView = View.inflate(context, R.layout.game_download_dialog, null);

		TextView textView = (TextView) contentView.findViewById(R.id.dialog_title);
		textView.setText(gameEntity.getName());

		int count = gameApk.size();
		int vpHeight;
		if (count <= 3) {
			vpHeight = 80;
		} else if (count <= 6) {
			vpHeight = 140;
		} else {
			vpHeight = 200;
		}

		linearLayout = (LinearLayout) contentView.findViewById(R.id.dialog_ll_hint);
		viewPager = (ViewPager) contentView.findViewById(R.id.dialog_viewPager);
		llCollection = (LinearLayout) contentView.findViewById(R.id.dialog_collection);
		collectionLinearLayout = (LinearLayout) contentView.findViewById(R.id.dialog_ll_collection_hint);
		collectionViewPager = (ViewPager) contentView.findViewById(R.id.dialog_collection_viewPager);
		ViewGroup.LayoutParams layoutParams = viewPager.getLayoutParams();
		layoutParams.height = DisplayUtils.dip2px(context,vpHeight);
		viewPager.setLayoutParams(layoutParams);

		isLoadPlatform = false;

		init(new ArrayList<>(gameApk));

		viewPager.addOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				for (int i = 0, size = linearLayout.getChildCount(); i < size; i++) {
					if (i == position % size) {
						((ImageView) linearLayout.getChildAt(i))
								.setImageResource(R.drawable.oval_hint_up);
					} else {
						((ImageView) linearLayout.getChildAt(i))
								.setImageResource(R.drawable.oval_hint_gray_bg);
					}
				}
			}

			@Override
			public void onPageScrollStateChanged(int state) {

			}

			@Override
			public void onPageScrolled(int position, float positionOffset,
					int positionOffsetPixels) {

			}
		});

		contentView.findViewById(R.id.dialog_ll_bottom).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {

					}
				});

		popupWindow = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, true);

		contentView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				popupWindow.dismiss();
			}
		});
		contentView.setFocusable(true);
		contentView.setFocusableInTouchMode(true);
		contentView.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK
						&& event.getRepeatCount() == 0 && popupWindow != null
						&& popupWindow.isShowing()) {
					popupWindow.dismiss();
				}
				return false;
			}
		});

		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
			@Override
			public void onDismiss() {
				isShow = false;
				EventBus.getDefault().unregister(DownloadDialog.this);
				DownloadManager.getInstance(context).removeObserver(dataWatcher);
			}
		});

		popupWindow.setTouchable(true);
		popupWindow.setFocusable(true);

		// 设置popWindow的显示和消失动画
		popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);

		// 设置好参数之后再show
		popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

		if (!EventBus.getDefault().isRegistered(DownloadDialog.this)) {
			EventBus.getDefault().register(DownloadDialog.this);
		}

		DownloadManager.getInstance(context).addObserver(dataWatcher);
	}

	// 合并ApkCollection
	private void mergeApkCollection(GameEntity game) {
		colseAdapterPosition = -1;
		colseCollectionPosition = -1;
		collectionPositionlist = new ArrayList<>();

		collectionAdapterMap = new SparseArray<>();
		gameCollection = new ArrayList<>();
		gameCollectionApk = new ArrayList<>();
		if (game.getCollection() != null){
			gameCollection = game.getCollection();
		}
		ConcurrentHashMap<String ,Integer> hashMap = new ConcurrentHashMap<>();

		StringBuffer collectionName = new StringBuffer();

		boolean isCollection = false;
		String collectionApkName = null;
		String collectionApkIcon = null;
		String collectionApkColor = null;
		String collectionApkPackage = null;
		ApkEntity saveApk = null;
		int apkPositon = 0;//排序后的位置

		for (int j = 0; j < gameApk.size(); j++) {
			for (GameCollectionEntity gameCollectionEntity : gameCollection){
				for (int i = 0; i < gameCollectionEntity.getPackage().size(); i++){
					if (gameCollectionEntity.getPackage().get(i).equals(gameApk.get(j).getPackageName())){
						isCollection = true;
						collectionApkName = gameCollectionEntity.getName();
						collectionApkIcon = gameCollectionEntity.getIcon();
						collectionApkColor = gameCollectionEntity.getColor();
						saveApk = gameApk.get(j);
					}
				}
			}
			if (isCollection){
				for (String s : hashMap.keySet()) {
					collectionName.append(s);
				}
				if (collectionName.toString().contains(collectionApkName)){
					gameCollectionApk.get(hashMap.get(collectionApkName)).getApkCollection().getSaveApkEntity().add(saveApk);
				}else {
					List<ApkEntity> saveApkList = new ArrayList<>();
					List<String> strings = new ArrayList<>();
					ApkEntity apkEntity = new ApkEntity();
					GameCollectionEntity collectionEntity = new GameCollectionEntity();
					apkEntity.setApkCollection(collectionEntity);
					strings.add(collectionApkPackage);
					saveApkList.add(saveApk);
					collectionEntity.setSaveApkEntity(saveApkList);
					collectionEntity.setName(collectionApkName);
					collectionEntity.setIcon(collectionApkIcon);
					collectionEntity.setColor(collectionApkColor);
					gameCollectionApk.add(apkEntity);
					hashMap.put(collectionApkName,apkPositon);

					apkPositon++;
				}
				isCollection = false;
			}else {
				gameCollectionApk.add(gameApk.get(j));
				apkPositon++;
			}
		}

		gameApk.clear();
		gameApk = gameCollectionApk;

	}

	private boolean isLoadPlatform;

	private void init(List<ApkEntity> apkList) {
		for (int i = 0; i < apkList.size(); i++) {
			String platformName = PlatformUtils.getInstance(context)
					.getPlatformName(apkList.get(i).getPlatform());
			if (platformName == null) {
				apkList.remove(i);
				i--;
				if (!isLoadPlatform) {
					PlatformUtils.getInstance(context).getPlatform();
					isLoadPlatform = true;
				}
			}
		}

		locationMap = new ArrayMap<>();
		adapterMap = new SparseArray<>();
		urlMap = new ArrayMap<>();

		for (int i = 0, size = apkList.size(); i < size; i++) {
			locationMap.put(apkList.get(i).getUrl(), i);
			urlMap.put(apkList.get(i).getPackageName(), apkList.get(i).getUrl());
		}

		linearLayout.removeAllViews();
		int size = (int) Math.ceil(apkList.size() / (double) (row * column));
		if (size > 1) {
			for (int i = 0; i < size; i++) {
				ImageView imageView = new ImageView(context);
				LayoutParams lparams = new LayoutParams(
						DisplayUtils.dip2px(context, 6), DisplayUtils.dip2px(context, 6));
				if (i == 0) {
					lparams.leftMargin = 0;
					imageView.setImageResource(R.drawable.oval_hint_up);
				} else {
					lparams.leftMargin = DisplayUtils.dip2px(context, 9);
					imageView.setImageResource(R.drawable.oval_hint_gray_bg);
				}
				imageView.setLayoutParams(lparams);
				linearLayout.addView(imageView);
			}
		}

		int currentItem = 0;
		if (viewPager != null) {
			currentItem = viewPager.getCurrentItem();
		}
		Utils.log("currentItem = " + currentItem);
		viewPager.setAdapter(new PlatformAdapter(apkList));
		viewPager.setCurrentItem(currentItem);
	}

	private ArrayList<ApkEntity> sortApk(List<ApkEntity> apkList) {
		DownloadEntity downloadEntity;
		List<ApkEntity> doneList = new ArrayList<>();
		List<ApkEntity> updateList = new ArrayList<>();
		List<ApkEntity> installedList = new ArrayList<>();
		List<ApkEntity> pluginList = new ArrayList<>();
		List<ApkEntity> downloadList = new ArrayList<>();
		List<ApkEntity> noPicList = new ArrayList<>();

		for (int i = 0, size = apkList.size(); i < size; i++) {
			String packageName = apkList.get(i).getPackageName();
			if (PackageManager.isInstalled(packageName)) {
				if (PackageManager.isCanUpdate(packageName)) {
					updateList.add(apkList.remove(i));
					size--;
					i--;
				} else if (!PackageUtils.isSignature(context, packageName)) {
					pluginList.add(apkList.remove(i));
					size--;
					i--;
				} else {
					installedList.add(apkList.remove(i));
					size--;
					i--;
				}
			} else {
				downloadEntity = entryMap.get(apkList.get(i).getUrl());
				if (downloadEntity != null) {
					if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
						doneList.add(apkList.remove(i));
					} else {
						downloadList.add(apkList.remove(i));
					}
					size--;
					i--;
				} else {
					String platform = apkList.get(i).getPlatform();
					int id = PlatformUtils.getInstance(context).getPlatformPic(
							platform);
					if (id == 0) {
						String path = PlatformUtils.getInstance(context)
								.getPlatformPicPath(platform);
						if (path == null) {
							noPicList.add(apkList.remove(i));
							size--;
							i--;
						}
					}
				}
			}
		}
		ArrayList<ApkEntity> list = new ArrayList<>();
		list.addAll(doneList);
		list.addAll(updateList);
		list.addAll(installedList);
		list.addAll(pluginList);
		list.addAll(downloadList);
		list.addAll(apkList);
		list.addAll(noPicList);
		return list;
	}

	// 接收安装成功的消息，更新界面
	public void onEvent(EBPackage busFour) {
		String url = urlMap.get(busFour.getPackageName());
		if (url != null) {
			Integer location = locationMap.get(url);
			if ("安装".equals(busFour.getType())) {
				entryMap.remove(url);
				int position = (int) Math.ceil((location + 1) / (double) (row * column));
				adapterMap.get(position - 1).notifyItemChanged(location % (row * column));
				if (collectionAdapterMap != null && collectionAdapterMap.size() >= position - 1 && collectionAdapterMap.size() >= 1){
					collectionAdapterMap.get(position - 1).notifyItemChanged(location % (row * column));
				}
			} else if ("卸载".equals(busFour.getType())) {
				int position = (int) Math.ceil((location + 1) / (double) (row * column));
				adapterMap.get(position - 1).notifyItemChanged(location % (row * column));
				if (collectionAdapterMap != null && collectionAdapterMap.size() >= position - 1 && collectionAdapterMap.size() >= 1){
					collectionAdapterMap.get(position - 1).notifyItemChanged(location % (row * column));
				}
			}
		}
	}

	//接收下载被删除消息
	public void onEvent(EBDownloadStatus status) {
		if ("delete".equals(status.getStatus())) {
			String url = status.getUrl();
			Integer location = locationMap.get(url);
			DownloadManager.getInstance(context).putStatus(url, "delete");
			entryMap.remove(url);
			int position = (int) Math.ceil((location + 1) / (double) (row * column));
			adapterMap.get(position - 1).notifyItemChanged(location % (row * column));
			if (collectionAdapterMap != null && collectionAdapterMap.size() >= position - 1 && collectionAdapterMap.size() >= 1){
				collectionAdapterMap.get(position - 1).notifyItemChanged(location % (row * column));
			}
		}
	}

	// 接收platform数据改变消息，更新界面
	public void onEvent(EBReuse reuse) {
		if ("PlatformChanged".equals(reuse.getType())) {
			DownloadManager.getInstance(context).removeObserver(dataWatcher);
			init(new ArrayList<>(gameApk));
			DownloadManager.getInstance(context).addObserver(dataWatcher);
		}
	}

	private class PlatformAdapter extends PagerAdapter {

		private List<ApkEntity> platforms;

		public PlatformAdapter(List<ApkEntity> list) {
			platforms = list;
		}

		@Override
		public int getCount() {
			return (int) Math.ceil(platforms.size() / (double) (row * column));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {

			RecyclerView recyclerView = new RecyclerView(context);

			int padding = DisplayUtils.dip2px(context, 10);

			recyclerView.setPadding(padding, padding, padding, padding);

			ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			recyclerView.setLayoutParams(params);

			recyclerView.setHasFixedSize(true);
			GridLayoutManager gridLayoutManager = new GridLayoutManager(context, column);
			recyclerView.setLayoutManager(gridLayoutManager);
			recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);

			RecyclerViewAdapter adapter = new RecyclerViewAdapter(platforms, position);

			adapterMap.put(position, adapter);

			recyclerView.setAdapter(adapter);

			container.addView(recyclerView);
			return recyclerView;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
			object = null;
		}

	}

	private class RecyclerViewHolder extends RecyclerView.ViewHolder {

		private TextView download_item_tv_name;
		private TextView download_item_tv_status;
		private TextView download_item_tv_hint;
		private ImageView download_item_open_collection;
		private ImageView download_item_colse_collection;
		private ImageView download_item_iv_pic;
		private ProgressBar download_item_progressbar;

		public RecyclerViewHolder(View convertView) {
			super(convertView);

			download_item_tv_name = (TextView) convertView
					.findViewById(R.id.download_item_tv_name);
			download_item_tv_status = (TextView) convertView
					.findViewById(R.id.download_item_tv_status);
			download_item_progressbar = (ProgressBar) convertView
					.findViewById(R.id.download_item_progressbar);
			download_item_iv_pic = (ImageView) convertView
					.findViewById(R.id.download_item_iv_pic);
			download_item_tv_hint = (TextView) convertView
					.findViewById(R.id.download_item_tv_hint);
			download_item_open_collection = (ImageView) convertView
					.findViewById(R.id.download_item_open_collection);
			download_item_colse_collection = (ImageView) convertView
					.findViewById(R.id.download_item_colse_collection);
		}
	}

	// 显示插件化
	private void showPluginDialog(final ApkEntity apkEntity,
								  final RecyclerViewAdapter adapter,
								  final int location) {
		DialogUtils.showPluginDialog(context, new DialogUtils.ConfiremListener() {
			@Override
			public void onConfirem() {
				Map<String, Object> kv6 = new HashMap<>();
				kv6.put("操作", "点击插件化安装完成");
				DataUtils.onEvent(context, "插件化", gameEntity.getName(), kv6);

				String path = entryMap.get(apkEntity.getUrl()).getPath();
				if (FileUtils.isEmptyFile(path)) {
					Toast.makeText(context, "解析包出错（可能被误删了），请重新下载", Toast.LENGTH_SHORT).show();
					entryMap.remove(apkEntity.getUrl());
					DownloadManager.getInstance(context).cancel(apkEntity.getUrl());
					adapter.notifyItemChanged(location);
				} else {
					context.startActivity(PackageUtils.getUninstallIntent(context, path));
				}
			}
		});
	}

	private class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {

		private List<ApkEntity> platforms;
		private int adapterPosition;
		private int count;


		public RecyclerViewAdapter(List<ApkEntity> list, int p) {
			platforms = list;
			adapterPosition = p;
			if (platforms.size() <= (row * column)) {
				count = platforms.size();
			} else if (platforms.size() - (row * column) * adapterPosition >= (row * column)) {
				count = (row * column);
			} else {
				count = platforms.size() - (row * column) * adapterPosition;
			}
		}

		@Override
		public int getItemCount() {
			return count;
		}

		@SuppressWarnings("deprecation")
		@Override
		public void onBindViewHolder(final RecyclerViewHolder viewHolder, final int position) {

			final ApkEntity apkEntity = platforms.get((row * column) * adapterPosition + position);
			viewHolder.itemView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (apkEntity.getApkCollection() != null){
						if (viewHolder.download_item_open_collection.getVisibility() == View.VISIBLE){
							llCollection.setVisibility(View.VISIBLE);
							showCollectionLayout(apkEntity.getApkCollection());
							viewHolder.download_item_open_collection.setVisibility(View.GONE);
							viewHolder.download_item_colse_collection.setVisibility(View.VISIBLE);
							colseCollectionPosition = viewHolder.getPosition();
							colseAdapterPosition = adapterPosition;
							for (int[] ints : collectionPositionlist) {
								adapterMap.get(ints[0]).notifyItemChanged(ints[1]);
							}
						} else {
							llCollection.setVisibility(View.GONE);
							viewHolder.download_item_open_collection.setVisibility(View.VISIBLE);
							viewHolder.download_item_colse_collection.setVisibility(View.GONE);
						}

					} else if (viewHolder.download_item_tv_status.getVisibility() == View.GONE) {
						//下载游戏
						if (NetworkUtils.isWifiConnected(context)) {
							addDownloadEntry(apkEntity, viewHolder.download_item_tv_status);
						} else {
							DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
								@Override
								public void onConfirem() {
									addDownloadEntry(apkEntity, viewHolder.download_item_tv_status);
								}
							});
						}
					} else {
						String status = viewHolder.download_item_tv_status.getText().toString();
						Utils.log("status = " + status);

						if ("下载中".equals(status)
								|| "插件化下载中".equals(status)
								|| "更新下载中".equals(status)) {
							//打开下载管理界面
							context.startActivity(new Intent(context, DownloadManagerActivity.class));
						} else if ("启动".equals(status)) {
							Map<String, Object> kv = new HashMap<>();
							kv.put("版本", apkEntity.getPlatform());
							DataUtils.onEvent(context, "游戏启动", gameEntity.getName(), kv);

							PackageUtils.launchApplicationByPackageName(context, apkEntity.getPackageName());
						} else if ("安装".equals(status) || "安装更新".equals(status)) {
							install(apkEntity, viewHolder.getPosition());
						} else if ("插件化".equals(status)) {
							if (NetworkUtils.isWifiConnected(context)) {
								plugin(apkEntity);
							} else {
								DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
									@Override
									public void onConfirem() {
										plugin(apkEntity);
									}
								});
							}
						} else if ("安装插件".equals(status)) {
							showPluginDialog(apkEntity, RecyclerViewAdapter.this, viewHolder.getPosition());
						} else if ("更新".equals(status)) {
							if (NetworkUtils.isWifiConnected(context)) {
								update(apkEntity);
							} else {
								DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
									@Override
									public void onConfirem() {
										update(apkEntity);
									}
								});
							}
						}
					}
				}
			});

			if (PackageManager.isInstalled(apkEntity.getPackageName())) {
				viewHolder.download_item_iv_pic.setVisibility(View.GONE);
				viewHolder.download_item_tv_hint.setVisibility(View.GONE);
				viewHolder.download_item_progressbar.setVisibility(View.VISIBLE);
				viewHolder.download_item_tv_name.setVisibility(View.VISIBLE);
				viewHolder.download_item_tv_status.setVisibility(View.VISIBLE);

				int color = Color.parseColor(PlatformUtils.getInstance(context)
						.getPlatformColor(apkEntity.getPlatform()));
				GradientDrawable gradientDrawable = new GradientDrawable();
				gradientDrawable.setColor(Color.WHITE);
				gradientDrawable.setStroke(DisplayUtils.dip2px(context, 1), color);
				viewHolder.itemView.setBackgroundDrawable(gradientDrawable);

				viewHolder.download_item_tv_name.setTextColor(color);

				viewHolder.download_item_tv_name.setText(PlatformUtils
						.getInstance(context).getPlatformName(apkEntity.getPlatform()));
				Drawable[] layers = new Drawable[2];
				GradientDrawable drawable = new GradientDrawable();
				drawable.setColor(0xFFC7C7C7);
				layers[0] = drawable;
				ClipDrawable clipDrawable = new ClipDrawable(new ColorDrawable(
						color), Gravity.LEFT, ClipDrawable.HORIZONTAL);
				layers[1] = clipDrawable;
				LayerDrawable layerDrawable = new LayerDrawable(layers);
				layerDrawable.setId(0, android.R.id.background);
				layerDrawable.setId(1, android.R.id.progress);
				viewHolder.download_item_progressbar.setProgressDrawable(layerDrawable);
				DownloadEntity downloadEntity = DownloadManager.getInstance(
						context).get(apkEntity.getUrl());
				if (downloadEntity == null) {
					viewHolder.download_item_progressbar.setProgress(1000);
					viewHolder.download_item_tv_status.setText("启动");
					if (gameEntity.getTag() != null && gameEntity.getTag().size() != 0
							&& !PackageUtils.isSignature(context, apkEntity.getPackageName())) {
						viewHolder.download_item_tv_status.setText("插件化");
					} else if (PackageManager.isCanUpdate(apkEntity.getPackageName())) {
						viewHolder.download_item_tv_status.setText("更新");
					}
				} else {
					viewHolder.download_item_progressbar.setProgress((int) (downloadEntity.getPercent() * 10));
					if (downloadEntity.isPluggable()) {
						if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
							viewHolder.download_item_tv_status.setText("安装插件");
						} else {
							viewHolder.download_item_tv_status.setText("插件化下载中");
						}
					} else if (downloadEntity.isUpdate()) {
						if (downloadEntity.getStatus().equals(DownloadStatus.done)) {
							viewHolder.download_item_tv_status.setText("安装更新");
						} else {
							viewHolder.download_item_tv_status.setText("更新下载中");
						}
					}
				}
			} else {
				DownloadEntity downloadEntity = entryMap.get(apkEntity.getUrl());
				if (downloadEntity != null) {
					viewHolder.download_item_iv_pic.setVisibility(View.GONE);
					viewHolder.download_item_tv_hint.setVisibility(View.GONE);
					viewHolder.download_item_progressbar.setVisibility(View.VISIBLE);
					viewHolder.download_item_tv_name.setVisibility(View.VISIBLE);
					viewHolder.download_item_tv_status.setVisibility(View.VISIBLE);

					int color = Color.parseColor(PlatformUtils.getInstance(
							context).getPlatformColor(apkEntity.getPlatform()));
					GradientDrawable gradientDrawable = new GradientDrawable();
					gradientDrawable.setColor(Color.WHITE);
					gradientDrawable.setStroke(DisplayUtils.dip2px(context, 1), color);
					viewHolder.itemView.setBackgroundDrawable(gradientDrawable);

					viewHolder.download_item_tv_name.setTextColor(color);

					viewHolder.download_item_tv_name.setText(PlatformUtils
							.getInstance(context).getPlatformName(apkEntity.getPlatform()));
					Drawable[] layers = new Drawable[2];
					GradientDrawable drawable = new GradientDrawable();
					drawable.setColor(0xFFC7C7C7);
					layers[0] = drawable;
					ClipDrawable clipDrawable = new ClipDrawable(new ColorDrawable(
							color), Gravity.LEFT, ClipDrawable.HORIZONTAL);
					layers[1] = clipDrawable;
					LayerDrawable layerDrawable = new LayerDrawable(layers);
					layerDrawable.setId(0, android.R.id.background);
					layerDrawable.setId(1, android.R.id.progress);
					viewHolder.download_item_progressbar.setProgressDrawable(layerDrawable);
					viewHolder.download_item_progressbar.setProgress((int) (downloadEntity.getPercent() * 10));

					DownloadStatus status = downloadEntity.getStatus();
					if (status.equals(DownloadStatus.pause)
							|| status.equals(DownloadStatus.timeout)
							|| status.equals(DownloadStatus.neterror)
							|| status.equals(DownloadStatus.downloading)
							|| status.equals(DownloadStatus.waiting)) {
						viewHolder.download_item_tv_status.setText("下载中");
					} else if (status.equals(DownloadStatus.done)) {
						viewHolder.download_item_tv_status.setText("安装");
					} else if (status.equals(DownloadStatus.cancel)
								|| status.equals(DownloadStatus.hijack)) {
						int id = PlatformUtils.getInstance(context).getPlatformPic(apkEntity.getPlatform());
						if (id != 0) {
							viewHolder.download_item_iv_pic.setVisibility(View.VISIBLE);
							viewHolder.download_item_iv_pic.setImageResource(id);
							viewHolder.download_item_tv_hint.setVisibility(View.GONE);
							viewHolder.download_item_progressbar.setVisibility(View.GONE);
							viewHolder.download_item_tv_name.setVisibility(View.GONE);
							viewHolder.download_item_tv_status.setVisibility(View.GONE);
							viewHolder.itemView.setBackgroundColor(0xffffff);
						} else {
							String path = PlatformUtils.getInstance(context)
									.getPlatformPicPath(apkEntity.getPlatform());
							if (path != null && new File(path).exists()) {
								viewHolder.download_item_iv_pic.setVisibility(View.VISIBLE);
								ImageUtils.getInstance(context).display(
										"file://" + path, viewHolder.download_item_iv_pic);
								viewHolder.download_item_tv_hint.setVisibility(View.GONE);
								viewHolder.download_item_progressbar.setVisibility(View.GONE);
								viewHolder.download_item_tv_name.setVisibility(View.GONE);
								viewHolder.download_item_tv_status.setVisibility(View.GONE);
								viewHolder.itemView.setBackgroundColor(0xffffff);
							} else {
								viewHolder.download_item_tv_hint.setVisibility(View.VISIBLE);
								viewHolder.download_item_tv_hint.setText(
										PlatformUtils.getInstance(context).getPlatformName(apkEntity.getPlatform()));
								viewHolder.download_item_iv_pic.setVisibility(View.GONE);
								viewHolder.download_item_progressbar.setVisibility(View.GONE);
								viewHolder.download_item_tv_name.setVisibility(View.GONE);
								viewHolder.download_item_tv_status.setVisibility(View.GONE);
								viewHolder.itemView.setBackgroundColor(0xffffff);
							}
						}
					}
				} else {
					int id = PlatformUtils.getInstance(context).getPlatformPic(
							apkEntity.getPlatform());
					if (id != 0) {
						viewHolder.download_item_iv_pic.setVisibility(View.VISIBLE);
						viewHolder.download_item_iv_pic.setImageResource(id);
						viewHolder.download_item_tv_hint.setVisibility(View.GONE);
						viewHolder.download_item_progressbar.setVisibility(View.GONE);
						viewHolder.download_item_tv_name.setVisibility(View.GONE);
						viewHolder.download_item_tv_status.setVisibility(View.GONE);
						viewHolder.itemView.setBackgroundColor(0xffffff);
					} else {
						String path = PlatformUtils.getInstance(context)
								.getPlatformPicPath(apkEntity.getPlatform());
						if (path != null) {
							viewHolder.download_item_iv_pic.setVisibility(View.VISIBLE);
							ImageUtils.getInstance(context).display(
									"file://" + path, viewHolder.download_item_iv_pic);
							viewHolder.download_item_tv_hint.setVisibility(View.GONE);
							viewHolder.download_item_progressbar.setVisibility(View.GONE);
							viewHolder.download_item_tv_name.setVisibility(View.GONE);
							viewHolder.download_item_tv_status.setVisibility(View.GONE);
							viewHolder.itemView.setBackgroundColor(0xffffff);
						} else {
							viewHolder.download_item_tv_hint.setVisibility(View.VISIBLE);
							viewHolder.download_item_tv_hint.setText(
									PlatformUtils.getInstance(context).getPlatformName(apkEntity.getPlatform()));
							viewHolder.download_item_iv_pic.setVisibility(View.GONE);
							viewHolder.download_item_progressbar.setVisibility(View.GONE);
							viewHolder.download_item_tv_name.setVisibility(View.GONE);
							viewHolder.download_item_tv_status.setVisibility(View.GONE);
							viewHolder.itemView.setBackgroundColor(0xffffff);
						}
					}
				}
				if (apkEntity.getApkCollection() != null){
					ImageUtils.getInstance(context).display(apkEntity.getApkCollection().getIcon(),viewHolder.download_item_iv_pic);
					viewHolder.download_item_open_collection.setVisibility(View.VISIBLE);

					int[] arrCollectionPosition= {adapterPosition, position};
					collectionPositionlist.add(arrCollectionPosition);

					if (colseCollectionPosition == position && adapterPosition == colseAdapterPosition){
						viewHolder.download_item_open_collection.setVisibility(View.GONE);
						viewHolder.download_item_colse_collection.setVisibility(View.VISIBLE);
					}else {
						viewHolder.download_item_open_collection.setVisibility(View.VISIBLE);
						viewHolder.download_item_colse_collection.setVisibility(View.GONE  );
					}
				}
			}
		}

		//安装游戏
		private void install(ApkEntity apkEntity, int position) {
			DownloadEntity downloadEntity = DownloadManager.getInstance(
					context).get(apkEntity.getUrl());
			if (downloadEntity != null && downloadEntity.isPluggable()) {
				Map<String, Object> kv6 = new HashMap<>();
				kv6.put("操作", "点击安装完成");
				DataUtils.onEvent(context, "插件化", downloadEntity.getName(), kv6);
			}

			final String path = entryMap.get(apkEntity.getUrl()).getPath();
			if (FileUtils.isEmptyFile(path)) {
				Toast.makeText(context, "解析包出错（可能被误删了），请重新下载", Toast.LENGTH_SHORT).show();
				entryMap.remove(apkEntity.getUrl());
				DownloadManager.getInstance(context).cancel(apkEntity.getUrl());
				notifyItemChanged(position);
			} else {
				PackageUtils.launchSetup(context, path);
			}
		}

		//下载可更新游戏
		private void update(ApkEntity apkEntity) {
			Map<String, Object> kv = new HashMap<>();
			kv.put("版本", apkEntity.getPlatform());
			kv.put("状态", "下载开始");
			DataUtils.onEvent(context, "游戏更新", gameEntity.getName(), kv);

			Map<String, Object> map = new HashMap<>();
			map.put("game", gameEntity.getName());
			map.put("game_id", gameEntity.getId());
			map.put("method", "更新");
			map.put("platform", PlatformUtils.getInstance(context)
					.getPlatformName(apkEntity.getPlatform()));
			map.put("status", "开始");
			map.put("location", location);
			map.put("entrance", entrance);
			map.put("btn_status", "更新");
			map.put("network", NetworkUtils.getConnectedType(context));
			DataCollectionManager.onEvent(context, "download", map);

			DownloadManager.createDownload(context, apkEntity, gameEntity, "更新", entrance, location);
		}

		//下载插件化游戏
		private void plugin(ApkEntity apkEntity) {
			String msg = FileUtils.isCanDownload(apkEntity.getSize());
			if (TextUtils.isEmpty(msg)) {
				Map<String, Object> kv = new HashMap<>();
				kv.put("版本", apkEntity.getPlatform());
				kv.put("状态", "下载开始");
				DataUtils.onEvent(context, "游戏下载", gameEntity.getName(), kv);

				Map<String, Object> kv2 = new HashMap<>();
				kv2.put("版本", apkEntity.getPlatform());
				kv2.put("状态", "下载开始");
				kv2.put("位置", entrance + "-开始");
				DataUtils.onEvent(context, "游戏下载位置", gameEntity.getName(), kv2);

				Map<String, Object> kv3 = new HashMap<>();
				kv3.put(entrance, "下载数");
				kv3.put(entrance, "下载开始");
				DataUtils.onEvent(context, "应用数据", gameEntity.getName(), kv3);

				if (entrance.contains("游戏详情")) {
					Map<String, Object> kv5 = new HashMap<>();
					kv5.put("下载", "下载开始");
					kv5.put("下载", apkEntity.getPlatform());
					DataUtils.onEvent(context, "插件数据", gameEntity.getName(), kv5);
				}

				Map<String, Object> kv6 = new HashMap<>();
				kv6.put("下载", "下载开始");
				kv6.put("版本", apkEntity.getPlatform());
				DataUtils.onEvent(context, "插件化", gameEntity.getName(), kv6);

				Map<String, Object> map = new HashMap<>();
				map.put("game", gameEntity.getName());
				map.put("game_id", gameEntity.getId());
				map.put("method", "插件化");
				map.put("platform", PlatformUtils.getInstance(context)
						.getPlatformName(apkEntity.getPlatform()));
				map.put("status", "开始");
				map.put("location", location);
				map.put("entrance", entrance);
				map.put("btn_status", "插件化");
				map.put("network", NetworkUtils.getConnectedType(context));
				DataCollectionManager.onEvent(context, "download", map);

				DownloadManager.createDownload(context, apkEntity, gameEntity, "插件化", entrance, location);
				DownloadManager.getInstance(context).putStatus(apkEntity.getUrl(), "downloading");
			} else {
				Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
			}
		}

		//添加游戏下载
		public void addDownloadEntry(ApkEntity apkEntity, TextView download_item_tv_status) {
			String msg = FileUtils.isCanDownload(apkEntity.getSize());
			if (TextUtils.isEmpty(msg)) {
				Map<String, Object> kv = new HashMap<>();
				kv.put("版本", apkEntity.getPlatform());
				kv.put("状态", "下载开始");
				DataUtils.onEvent(context, "游戏下载", gameEntity.getName(), kv);

				Map<String, Object> kv2 = new HashMap<>();
				kv2.put("版本", apkEntity.getPlatform());
				kv2.put("状态", "下载开始");
				kv2.put("位置", entrance + "-开始");
				DataUtils.onEvent(context, "游戏下载位置", gameEntity.getName(), kv2);

				Map<String, Object> kv3 = new HashMap<>();
				kv3.put(entrance, "下载数");
				kv3.put(entrance, "下载开始");
				DataUtils.onEvent(context, "应用数据", gameEntity.getName(), kv3);

				if (entrance.contains("游戏详情")) {
					Map<String, Object> kv5 = new HashMap<>();
					kv5.put("下载", "下载量");
					kv5.put("下载", apkEntity.getPlatform());
					DataUtils.onEvent(context, "插件数据", gameEntity.getName(), kv5);
				}

				Map<String, Object> map = new HashMap<>();
				map.put("game", gameEntity.getName());
				map.put("game_id", gameEntity.getId());
				map.put("method", "正常");
				map.put("platform", PlatformUtils.getInstance(context)
						.getPlatformName(apkEntity.getPlatform()));
				map.put("status", "开始");
				map.put("location", location);
				map.put("entrance", entrance);
				map.put("btn_status", "下载");
				map.put("network", NetworkUtils.getConnectedType(context));
				DataCollectionManager.onEvent(context, "download", map);

				DownloadManager.createDownload(context, apkEntity, gameEntity, "下载", entrance, location);
				DownloadManager.getInstance(context).putStatus(apkEntity.getUrl(), "downloading");

				download_item_tv_status.setText("0.0%");
			} else {
				Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public int getItemViewType(int position) {
			return position;
		}

		@Override
		public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
			View view = LayoutInflater.from(viewGroup.getContext()).inflate(
					R.layout.game_download_item, viewGroup, false);
			return new RecyclerViewHolder(view);
		}
	}

	private void showCollectionLayout(GameCollectionEntity gameCollectionEntity) {

		int count = gameCollectionEntity.getSaveApkEntity().size();
		int vpHeight = 0;
		if (count <= 3){
			vpHeight = 80;
		}else if (count <= 6){
			vpHeight = 140;
		}else {
			vpHeight = 200;
		}

		ViewGroup.LayoutParams layoutParams = collectionViewPager.getLayoutParams();
		layoutParams.height = DisplayUtils.dip2px(context, vpHeight);
		collectionViewPager.setLayoutParams(layoutParams);

		for (int i = 0, size = gameCollectionEntity.getSaveApkEntity().size(); i < size; i++) {
			locationMap.put(gameCollectionEntity.getSaveApkEntity().get(i).getUrl(), i);
			urlMap.put(gameCollectionEntity.getSaveApkEntity().get(i).getPackageName(), gameCollectionEntity.getSaveApkEntity().get(i).getUrl());
		}

		collectionLinearLayout.removeAllViews();
		int size = (int) Math.ceil(gameCollectionEntity.getSaveApkEntity().size() / (double) (row * column));
		if (size > 1) {
			for (int i = 0; i < size; i++) {
				ImageView imageView = new ImageView(context);
				LayoutParams lparams = new LayoutParams(
						DisplayUtils.dip2px(context, 6), DisplayUtils.dip2px(
						context, 6));
				if (i == 0) {
					lparams.leftMargin = 0;
					imageView.setImageResource(R.drawable.oval_hint_up);
				} else {
					lparams.leftMargin = DisplayUtils.dip2px(context, 9);
					imageView.setImageResource(R.drawable.oval_hint_gray_bg);
				}
				imageView.setLayoutParams(lparams);
				collectionLinearLayout.addView(imageView);
			}
		}

		int currentItem = 0;
		if (viewPager != null) {
			currentItem = viewPager.getCurrentItem();
		}
		viewPager.setCurrentItem(currentItem);

		collectionViewPager.setAdapter(new CollectionPlatformAdapter(gameCollectionEntity.getSaveApkEntity()));

		collectionViewPager.addOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

			}

			@Override
			public void onPageSelected(int position) {
				for (int i = 0, size = collectionLinearLayout.getChildCount(); i < size; i++) {
					if (i == position % size) {
						((ImageView) collectionLinearLayout.getChildAt(i))
								.setImageResource(R.drawable.oval_hint_up);
					} else {
						((ImageView) collectionLinearLayout.getChildAt(i))
								.setImageResource(R.drawable.oval_hint_gray_bg);
					}
				}
			}

			@Override
			public void onPageScrollStateChanged(int i) {

			}
		});
	}
	private class CollectionPlatformAdapter extends PagerAdapter {

		private List<ApkEntity> saveApkEntity;

		public CollectionPlatformAdapter(List<ApkEntity> saveApkEntity) {
			this.saveApkEntity = saveApkEntity;
		}

		@Override
		public int getCount() {
			return (int) Math.ceil(saveApkEntity.size() / (double) (row * column));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {

			RecyclerView recyclerView = new RecyclerView(context);

			int padding = DisplayUtils.dip2px(context, 10);

			recyclerView.setPadding(padding, padding, padding, padding);

			ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			recyclerView.setLayoutParams(params);

			recyclerView.setHasFixedSize(true);
			GridLayoutManager gridLayoutManager = new GridLayoutManager(
					context, column);
			recyclerView.setLayoutManager(gridLayoutManager);
			recyclerView.setOverScrollMode(View.OVER_SCROLL_NEVER);

			RecyclerViewAdapter adapter = new RecyclerViewAdapter(saveApkEntity,
					position);

			collectionAdapterMap.put(position, adapter);
			recyclerView.setAdapter(adapter);

			container.addView(recyclerView);
			return recyclerView;
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {

			return view == object;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
			object = null;
		}

	}

}
