package com.gh.gamecenter.download;

import android.content.Context;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.gh.common.constant.Constants;
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.SpeedUtils;
import com.gh.common.view.CardLinearLayout;
import com.gh.common.view.CardRelativeLayout;
import com.gh.download.DownloadEntity;
import com.gh.download.DownloadManager;
import com.gh.download.DownloadStatus;
import com.gh.gamecenter.R;
import com.gh.gamecenter.eventbus.EBDownloadChanged;
import com.gh.gamecenter.manager.PackageManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by LGT on 2016/8/15.
 */
public class GameDownloadAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;

    private RecyclerView downloadmanager_rv_show;
	private LinearLayout downloadmanager_tv_none;

    private List<DownloadEntity> downloadingList;
    private List<DownloadEntity> doneList;

	private ArrayMap<String, Integer> locationMap;
    private ArrayMap<String, String> statusMap;
	private ArrayList<String> deleteList;

    public GameDownloadAdapter(Context context,
                               RecyclerView recyclerView,
                               LinearLayout textView,
                               ArrayMap<String, Integer> lMap,
                               ArrayMap<String, String> sMap,
                               ArrayList<String> dList) {

        this.context = context;

        downloadmanager_rv_show = recyclerView;
	    downloadmanager_tv_none = textView;

	    locationMap = lMap;
        statusMap = sMap;
	    deleteList = dList;

        downloadingList = new ArrayList<>();
        doneList = new ArrayList<>();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == 0) {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.downloadmanager_item_head, parent, false);
            return new DownloadHeadViewHolder(view);
        } else {
            View view = LayoutInflater.from(parent.getContext()).inflate(
                    R.layout.fm_downloadmanager_item, parent, false);
            return new GameDownloadViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof GameDownloadViewHolder) {
            final GameDownloadViewHolder viewHolder = (GameDownloadViewHolder) holder;

            final DownloadEntity downloadEntity;
            if (doneList.size() != 0 && position > 0 && position <= doneList.size()) {
                downloadEntity = doneList.get(position - 1);

//                // 第一个
//                if (position == 1) {
//                    ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
//                } else {
//                    ((CardLinearLayout) holder.itemView).setmTop(0);
//                }

                // 最后一个
                if (position == doneList.size()) {
                    ((CardLinearLayout) holder.itemView).setBottom(true);
                    ((CardLinearLayout) holder.itemView).setmBottom(0);
                } else {
                    ((CardLinearLayout) holder.itemView).setBottom(false);
                    ((CardLinearLayout) holder.itemView).setmBottom(DisplayUtils.dip2px(context, 8));
                }
            } else if (doneList.isEmpty()) {
                downloadEntity = downloadingList.get(position - 1);
//                // 第一个
//                if (position == 1) {
//                    ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
//                } else {
//                    ((CardLinearLayout) holder.itemView).setmTop(0);
//                }

                // 最后一个
                if (position == downloadingList.size()) {
                    ((CardLinearLayout) holder.itemView).setBottom(true);
                } else {
                    ((CardLinearLayout) holder.itemView).setBottom(false);
                }
            } else {
                downloadEntity = downloadingList.get(position - doneList.size() - 2);

//                // 第一个
//                if (position - doneList.size() - 2 == 0) {
//                    ((CardLinearLayout) holder.itemView).setmTop(DisplayUtils.dip2px(context, 8));
//                } else {
//                    ((CardLinearLayout) holder.itemView).setmTop(0);
//                }

                // 最后一个
                if (position - doneList.size() - 1 == downloadingList.size()) {
                    ((CardLinearLayout) holder.itemView).setBottom(true);
                } else {
                    ((CardLinearLayout) holder.itemView).setBottom(false);
                }
            }

            String icon = downloadEntity.getIcon();
            if (!TextUtils.isEmpty(icon)) {
                ImageUtils.getInstance(context).display(icon, viewHolder.dm_item_iv_icon);
            } else {
                viewHolder.dm_item_iv_icon.setImageResource(R.drawable.logo);
            }

            if (downloadEntity.getName().contains("光环助手")
                    || "local_plugin".equals(downloadEntity.getPlatform())) {
                viewHolder.dm_item_tv_title.setText(downloadEntity.getName());
            } else {
                String platform = downloadEntity.getPlatform();
                if ("local_plugin".equals(platform)) {
                    viewHolder.dm_item_tv_title.setText(downloadEntity.getName());
                } else {
                    platform = PlatformUtils.getInstance(context).getPlatformName(platform);
                    if (platform == null) {
                        viewHolder.dm_item_tv_title.setText(downloadEntity.getName());
                    } else {
                        viewHolder.dm_item_tv_title.setText(downloadEntity.getName() + " - " + platform);
                    }
                }
            }

            DownloadStatus status = downloadEntity.getStatus();
            if (status.equals(DownloadStatus.done)) {
                LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                viewHolder.dm_item_tv_downloads.setTextColor(0xFF9A9A9A);
                viewHolder.dm_item_tv_downloads.setText("下载完成");
                viewHolder.dm_item_iv_delete.setVisibility(View.VISIBLE);
                viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_download_style);
                if (downloadEntity.isPluggable()
                        && PackageManager.isInstalled(downloadEntity.getPackageName())) {
                    viewHolder.dm_item_tv_startorpause.setText("安装");
                    viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_plugin_style);
                } else {
                    viewHolder.dm_item_tv_startorpause.setText("安装");
                    viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_download_style);
                }
                viewHolder.dm_item_tv_speed.setText(R.string.hundred_percent);
            } else if (status.equals(DownloadStatus.downloading)) {
                if (!"pause".equals(statusMap.get(downloadEntity.getUrl()))) {
                    LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                            0, LinearLayout.LayoutParams.WRAP_CONTENT);
                    lparams.weight = 4;
                    viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                    viewHolder.dm_item_tv_downloads.setTextColor(context.getResources().getColor(R.color.theme));
                    viewHolder.dm_item_tv_downloads.setText(String.format("%s(剩%s)",
                            SpeedUtils.getSpeed(downloadEntity.getSpeed()),
                            SpeedUtils.getRemainTime(downloadEntity.getSize(), downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
                    viewHolder.dm_item_iv_delete.setVisibility(View.GONE);
                    viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_pause_style);
                    viewHolder.dm_item_tv_startorpause.setText("暂停");
                    viewHolder.dm_item_tv_speed.setText(downloadEntity.getPercent() + "%");
                }
            } else if (status.equals(DownloadStatus.waiting)) {
                LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                viewHolder.dm_item_tv_downloads.setTextColor(0xFF9A9A9A);
                viewHolder.dm_item_tv_downloads.setText("等待中");
                viewHolder.dm_item_iv_delete.setVisibility(View.VISIBLE);
                viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_pause_style);
                viewHolder.dm_item_tv_startorpause.setText("等待");
                viewHolder.dm_item_tv_speed.setText(downloadEntity.getPercent() + "%");
            } else if (status.equals(DownloadStatus.pause)
                    || status.equals(DownloadStatus.timeout)
                    || status.equals(DownloadStatus.neterror)) {
                LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                viewHolder.dm_item_tv_downloads.setTextColor(0xFF9A9A9A);
                viewHolder.dm_item_tv_downloads.setText("已暂停");
                viewHolder.dm_item_iv_delete.setVisibility(View.VISIBLE);
                viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_download_style);
                viewHolder.dm_item_tv_startorpause.setText("继续");
                viewHolder.dm_item_tv_speed.setText(downloadEntity.getPercent() + "%");
            }

            viewHolder.dm_item_progressbar.setProgress((int) (downloadEntity.getPercent() * 10));

            viewHolder.dm_item_tv_startorpause.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String str = ((TextView)v).getText().toString();
                    final String url = downloadEntity.getUrl();
                    DownloadManager.getInstance(context).put(url, System.currentTimeMillis());
                    if ("继续".equals(str) || "下载".equals(str)) {
                        if (NetworkUtils.isWifiConnected(context)) {
                            LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                                    0, LinearLayout.LayoutParams.WRAP_CONTENT);
                            lparams.weight = 4;
                            viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                            viewHolder.dm_item_tv_downloads.setTextColor(context.getResources().getColor(R.color.theme));
                            viewHolder.dm_item_tv_downloads.setText(String.format("%s(剩%s)",
                                    SpeedUtils.getSpeed(downloadEntity.getSpeed()),
                                    SpeedUtils.getRemainTime(downloadEntity.getSize(),
                                            downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
                            viewHolder.dm_item_iv_delete.setVisibility(View.GONE);

                            viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_pause_style);
                            viewHolder.dm_item_tv_startorpause.setText("暂停");

                            statusMap.put(url, "downloading");
                            notifyItemChanged(doneList.isEmpty() ? 0 : 1 + doneList.size());

                            Message msg = Message.obtain();
                            msg.what = Constants.CONTINUE_DOWNLOAD_TASK;
                            msg.obj = url;
                            DownloadManager.getInstance(context).sendMessageDelayed(msg, 1000);
                        } else {
                            DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
                                @Override
                                public void onConfirem() {
                                    LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                                            0, LinearLayout.LayoutParams.WRAP_CONTENT);
                                    lparams.weight = 4;
                                    viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                                    viewHolder.dm_item_tv_downloads.setTextColor(context.getResources().getColor(R.color.theme));
                                    viewHolder.dm_item_tv_downloads.setText(String.format("%s(剩%s)",
                                            SpeedUtils.getSpeed(downloadEntity.getSpeed()),
                                            SpeedUtils.getRemainTime(downloadEntity.getSize(),
                                                    downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
                                    viewHolder.dm_item_iv_delete.setVisibility(View.GONE);

                                    viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_pause_style);
                                    viewHolder.dm_item_tv_startorpause.setText("暂停");

                                    statusMap.put(url, "downloading");
                                    notifyItemChanged(doneList.isEmpty() ? 0 : 1 + doneList.size());

                                    Message msg = Message.obtain();
                                    msg.what = Constants.CONTINUE_DOWNLOAD_TASK;
                                    msg.obj = url;
                                    DownloadManager.getInstance(context).sendMessageDelayed(msg, 1000);
                                }
                            });
                        }
                    } else if ("安装".equals(str)) {
                        final String path = downloadEntity.getPath();
                        if (downloadEntity.isPluggable()
                                && PackageManager.isInstalled(downloadEntity.getPackageName())) {
                            showPluginDialog(downloadEntity.getPath());
                        } else {
                            if (FileUtils.isEmptyFile(path)) {
                                Toast.makeText(context, "解析包出错（可能被误删了），请重新下载", Toast.LENGTH_SHORT).show();
                                removeDownload(downloadEntity, viewHolder.getPosition());
                            } else {
                                if (downloadEntity.getName().contains("光环助手")) {
                                    context.startActivity(PackageUtils.getInstallIntent(path));
                                } else {
                                    PackageUtils.launchSetup(context, path);
                                }
                            }
                        }
                    } else if ("暂停".equals(str)) {
                        viewHolder.dm_item_tv_startorpause.setBackgroundResource(R.drawable.game_item_btn_download_style);
                        viewHolder.dm_item_tv_startorpause.setText("继续");
                        LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        viewHolder.dm_item_tv_downloads.setLayoutParams(lparams);
                        viewHolder.dm_item_tv_downloads.setTextColor(0xFF9A9A9A);
                        viewHolder.dm_item_tv_downloads.setText("已暂停");
                        viewHolder.dm_item_iv_delete.setVisibility(View.VISIBLE);
                        statusMap.put(url, "pause");
                        notifyItemChanged(doneList.isEmpty() ? 0 : 1 + doneList.size());
                        Message msg = Message.obtain();
                        msg.what = Constants.PAUSE_DOWNLOAD_TASK;
                        msg.obj = url;
                        DownloadManager.getInstance(context).sendMessageDelayed(msg, 1000);
                    } else if ("等待".equals(str)) {
                        Toast.makeText(context, "最多只能同时启动3个下载任务", Toast.LENGTH_SHORT).show();
                    } else if ("启动".equals(str)) {
                        Map<String, Object> kv = new HashMap<>();
                        kv.put("版本", downloadEntity.getPlatform());
                        DataUtils.onEvent(context, "游戏启动", downloadEntity.getName(), kv);

                        PackageUtils.launchApplicationByPackageName(context, downloadEntity.getPackageName());
                    }
                }
            });

            viewHolder.dm_item_tv_downloads.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (viewHolder.dm_item_iv_delete.getVisibility() == View.VISIBLE) {
                        showDeleteDialog(downloadEntity, viewHolder.getPosition());
                    }
                }
            });

            viewHolder.dm_item_iv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (viewHolder.dm_item_iv_delete.getVisibility() == View.VISIBLE) {
                        showDeleteDialog(downloadEntity, viewHolder.getPosition());
                    }
                }
            });

            viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (viewHolder.dm_item_iv_delete.getVisibility() == View.VISIBLE) {
                        showDeleteDialog(downloadEntity, viewHolder.getPosition());
                        return true;
                    }
                    return false;
                }
            });

        } else if (holder instanceof DownloadHeadViewHolder) {
            final DownloadHeadViewHolder viewHolder = (DownloadHeadViewHolder) holder;
            if (position == 0 && doneList.size() != 0) {
                CardRelativeLayout cardRelativeLayout = (CardRelativeLayout) viewHolder.itemView;
                cardRelativeLayout.setmBottom(DisplayUtils.dip2px(context, 8));
                viewHolder.dm_item_head_tv_task.setText("已完成");
                viewHolder.dm_item_head_tv_allstart.setVisibility(View.GONE);
            } else {
                CardRelativeLayout cardRelativeLayout = (CardRelativeLayout) viewHolder.itemView;
                if (doneList.isEmpty()) {
                    cardRelativeLayout.setmTop(0);
                } else {
                    cardRelativeLayout.setmTop(DisplayUtils.dip2px(context, 8));
                }
                cardRelativeLayout.setmBottom(DisplayUtils.dip2px(context, 8));
                viewHolder.dm_item_head_tv_task.setText("下载中");
                viewHolder.dm_item_head_tv_allstart.setVisibility(View.VISIBLE);

                int dlNumber = 0;
                int wtNumber = 0;
                for (int i = 0, size = downloadingList.size(); i < size; i++) {
                    if (DownloadStatus.downloading.equals(downloadingList.get(i).getStatus())) {
                        dlNumber++;
                    } else if (DownloadStatus.waiting.equals(downloadingList.get(i).getStatus())) {
                        wtNumber++;
                    }
                }
                if ((dlNumber + wtNumber) != downloadingList.size()) {
                    viewHolder.dm_item_head_tv_allstart.setText("全部开始");
                    viewHolder.dm_item_head_tv_allstart.setTextColor(context.getResources().getColor(R.color.theme));
                } else {
                    viewHolder.dm_item_head_tv_allstart.setText("全部暂停");
                    viewHolder.dm_item_head_tv_allstart.setTextColor(context.getResources().getColor(R.color.btn_gray));
                }

                viewHolder.dm_item_head_tv_allstart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String str = ((TextView)v).getText().toString();
                        final int base = (doneList.isEmpty() ? 0 : 1 + doneList.size()) + 1;
                        if ("全部开始".equals(str)) {
                            if (NetworkUtils.isWifiConnected(context)) {
                                for (int i = 0, size = downloadingList.size(); i < size; i++) {
                                    View view = downloadmanager_rv_show.getChildAt(base + i);
                                    if (view != null && view instanceof CardView) {
                                        TextView tv = (TextView) view.findViewById(R.id.dm_item_tv_startorpause);
                                        if (tv.getText().toString().equals("继续")) {
                                            tv.performClick();
                                        }
                                    } else {
                                        DownloadManager.getInstance(context).put(downloadingList.get(i).getUrl(),
                                                System.currentTimeMillis());
                                        Message msg = Message.obtain();
                                        msg.what = Constants.CONTINUE_DOWNLOAD_TASK;
                                        msg.obj = downloadingList.get(i).getUrl();
                                        DownloadManager.getInstance(context).sendMessageDelayed(msg, 1000);
                                        statusMap.put(downloadingList.get(i).getUrl(), "downloading");
                                    }
                                }
                                viewHolder.dm_item_head_tv_allstart.setText("全部暂停");
                                viewHolder.dm_item_head_tv_allstart.setTextColor(context.getResources().getColor(R.color.btn_gray));
                            } else {
                                DialogUtils.showDownloadDialog(context, new DialogUtils.ConfiremListener() {
                                    @Override
                                    public void onConfirem() {
                                        for (int i = 0, size = downloadingList.size(); i < size; i++) {
                                            View view = downloadmanager_rv_show.getChildAt(base + i);
                                            if (view != null && view instanceof CardView) {
                                                TextView tv = (TextView) view.findViewById(R.id.dm_item_tv_startorpause);
                                                if (tv.getText().toString().equals("继续")) {
                                                    tv.performClick();
                                                }
                                            } else {
                                                DownloadManager.getInstance(context).put(downloadingList.get(i).getUrl(),
                                                        System.currentTimeMillis());
                                                Message msg = Message.obtain();
                                                msg.what = Constants.CONTINUE_DOWNLOAD_TASK;
                                                msg.obj = downloadingList.get(i).getUrl();
                                                DownloadManager.getInstance(context).sendMessageDelayed(msg, 1000);
                                                statusMap.put(downloadingList.get(i).getUrl(), "downloading");
                                            }
                                        }
                                        viewHolder.dm_item_head_tv_allstart.setText("全部暂停");
                                        viewHolder.dm_item_head_tv_allstart.setTextColor(context.getResources().getColor(R.color.btn_gray));
                                    }
                                });
                            }
                        } else {
                            for (int i = 0, size = downloadingList.size(); i < size; i++) {
                                View view = downloadmanager_rv_show.getChildAt(base + i);
                                if (view != null && view instanceof CardView) {
                                    TextView tv = (TextView) view.findViewById(R.id.dm_item_tv_startorpause);
                                    if (tv.getText().toString().equals("暂停")) {
                                        tv.performClick();
                                    } else if (tv.getText().toString().equals("等待")) {
                                        DownloadManager.getInstance(context).pause(downloadingList.get(i).getUrl());
                                    }
                                } else {
                                    DownloadManager.getInstance(context).put(downloadingList.get(i).getUrl(),
                                            System.currentTimeMillis());
                                    Message msg = Message.obtain();
                                    msg.what = Constants.PAUSE_DOWNLOAD_TASK;
                                    msg.obj = downloadingList.get(i).getUrl();
                                    DownloadManager.getInstance(context).sendMessageDelayed(msg, 1000);
                                }
                            }
                            viewHolder.dm_item_head_tv_allstart.setText("全部开始");
                            viewHolder.dm_item_head_tv_allstart.setTextColor(context.getResources().getColor(R.color.theme));
                        }
                    }
                });
            }
        }
    }

    @Override
    public int getItemCount() {
        if (doneList.isEmpty() && downloadingList.isEmpty()) {
            return 0;
        }
        if (doneList.isEmpty()) {
            return 1 + downloadingList.size();
        }
        if (downloadingList.isEmpty()) {
            return 1 + doneList.size();
        }
        return 1 + doneList.size() + 1 + downloadingList.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0 || (doneList.size() > 0 && position == 1 + doneList.size())) {
            return 0;
        }
        return 1;
    }

    // 显示插件化
    public void showPluginDialog(final String path) {
        DialogUtils.showPluginDialog(context, new DialogUtils.ConfiremListener() {
            @Override
            public void onConfirem() {
                for (DownloadEntity downloadEntity : DownloadManager.getInstance(context).getAll()) {
                    if (downloadEntity.isPluggable()
                            && downloadEntity.getPath().equals(path)) {
                        Map<String, Object> kv6 = new HashMap<>();
                        kv6.put("操作", "点击插件化安装完成");
                        DataUtils.onEvent(context, "插件化", downloadEntity.getName(), kv6);
                        break;
                    }
                }

                if (FileUtils.isEmptyFile(path)) {
                    Toast.makeText(context, "解析包出错（可能被误删了），请重新下载", Toast.LENGTH_SHORT).show();
                } else {
                    context.startActivity(PackageUtils.getUninstallIntent(context, path));
                }
            }
        });
    }

    // 显示删除提示框
    private void showDeleteDialog(final DownloadEntity entry, final int position) {
        String msg;
        if (doneList.size() != 0 && position <= doneList.size()) {
            msg = "游戏还没安装哦，确定删除？";
        } else {
            msg = "游戏还没下载完，确定删除？";
        }
	    DialogUtils.showWarningDialog(context, "删除下载", msg, new DialogUtils.ConfiremListener() {
		    @Override
		    public void onConfirem() {
                removeDownload(entry, position);
		    }

        });
    }

    private void removeDownload(DownloadEntity entry, int position) {
        boolean isDoneEmpty = false;
        boolean isDownloadingEmpty = false;

        if (doneList.size() != 0 && position > 0 && position <= doneList.size()) {
            doneList.remove(position - 1);
            if (doneList.isEmpty()) {
                isDoneEmpty = true;
            }
        } else if (doneList.isEmpty()) {
            downloadingList.remove(position - 1);
            if (downloadingList.isEmpty()) {
                isDownloadingEmpty = true;
            }
        } else {
            downloadingList.remove(position - doneList.size() - 2);
            if (downloadingList.isEmpty()) {
                isDownloadingEmpty = true;
            }
        }

        if (doneList.isEmpty() && downloadingList.isEmpty()) {
            EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, 0));
            locationMap.clear();
            notifyDataSetChanged();
            if (downloadmanager_tv_none.getVisibility() == View.GONE) {
                downloadmanager_tv_none.setVisibility(View.VISIBLE);
            }
        } else if (isDoneEmpty) {
            EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                    doneList.size() + downloadingList.size()));
            notifyItemRangeRemoved(0, 2);
        } else if (isDownloadingEmpty) {
            EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                    doneList.size() + downloadingList.size()));
            notifyItemRangeRemoved(doneList.isEmpty() ? 0 : 1 + doneList.size(), 2);
        } else {
            EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                    doneList.size() + downloadingList.size()));
            notifyItemRemoved(position);
        }

        deleteList.add(entry.getUrl());
        statusMap.remove(entry.getUrl());
        locationMap.remove(entry.getUrl());
        initLocationMap();

        notifyItemChanged(doneList.isEmpty() ? 0 : 1 + doneList.size());

        DownloadManager.getInstance(context).cancel(entry.getUrl());
    }

    private void initLocationMap() {
        for (int i = 0; i < doneList.size(); i++) {
            locationMap.put(doneList.get(i).getUrl(), i);
        }
        for (int i = 0; i < downloadingList.size(); i++) {
            locationMap.put(downloadingList.get(i).getUrl(), i);
        }
    }

    public List<DownloadEntity> getDownloadingList() {
        return downloadingList;
    }

    public List<DownloadEntity> getDoneList() {
        return doneList;
    }

}
