package com.gh.gamecenter.download;

import android.content.Context;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.collection.ArrayMap;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;

import com.gh.common.util.DialogUtils;
import com.gh.common.util.PackageInstaller;
import com.gh.common.util.PackageLauncher;
import com.gh.common.xapk.XapkDialogHelper;
import com.gh.common.xapk.XapkInstaller;
import com.gh.common.xapk.XapkUnzipStatus;
import com.gh.download.DownloadManager;
import com.gh.gamecenter.R;
import com.gh.gamecenter.adapter.viewholder.DownloadHeadViewHolder;
import com.gh.gamecenter.adapter.viewholder.GameDownloadViewHolder;
import com.gh.gamecenter.common.constant.Constants;
import com.gh.gamecenter.common.entity.IconFloat;
import com.gh.gamecenter.common.utils.DialogHelper;
import com.gh.gamecenter.common.utils.ExtensionsKt;
import com.gh.gamecenter.common.utils.FileUtils;
import com.gh.gamecenter.common.utils.ImageUtils;
import com.gh.gamecenter.common.utils.NetworkUtils;
import com.gh.gamecenter.common.utils.NewFlatLogUtils;
import com.gh.gamecenter.common.utils.PermissionHelper;
import com.gh.gamecenter.common.utils.SensorsBridge;
import com.gh.gamecenter.core.utils.SpeedUtils;
import com.gh.gamecenter.databinding.DownloadmanagerItemHeadBinding;
import com.gh.gamecenter.databinding.FmDownloadmanagerItemBinding;
import com.gh.gamecenter.eventbus.EBDownloadChanged;
import com.gh.gamecenter.feature.utils.PlatformUtils;
import com.gh.gamecenter.feature.view.DownloadButton;
import com.gh.gamecenter.manager.PackagesManager;
import com.lightgame.adapter.BaseRecyclerAdapter;
import com.lightgame.download.DownloadConfig;
import com.lightgame.download.DownloadEntity;
import com.lightgame.download.DownloadStatus;
import com.lightgame.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by LGT on 2016/8/15.
 */
class GameDownloadFragmentAdapter extends BaseRecyclerAdapter<ViewHolder> {

    private final LinearLayout mNoDataSkip;

    private final List<DownloadEntity> mDownloadingList;
    private final List<DownloadEntity> mDownloadedList;

    private final ArrayMap<String, String> xapkStatusMap;

    // 1、此处的所有MAP只是对DownloadManager内部Map的引用，
    // 2、任何对下载器任务的操作，通过DownloadManager处理，由DownloadManager处理之后抛出对应的状态变化事件
    // 3、监听下载任务状态变化，刷新界面
    // 4、对状态只读不写。
    private final ArrayMap<String, Integer> locationMap;
    private final ArrayMap<String, String> statusMap;
    private final ArrayMap<String, String> urlMap;
    private final ArrayList<String> deleteList;

    private String url;

    GameDownloadFragmentAdapter(Context context, LinearLayout textView, String url) {
        super(context);

        this.url = url;

        mNoDataSkip = textView;

        statusMap = new ArrayMap<>();
        mDownloadingList = new ArrayList<>();

        locationMap = new ArrayMap<>();
        urlMap = new ArrayMap<>();
        deleteList = new ArrayList<>();

        mDownloadedList = new ArrayList<>();
        xapkStatusMap = new ArrayMap<>();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == 0) {
            return new DownloadHeadViewHolder(DownloadmanagerItemHeadBinding.inflate(mLayoutInflater, parent, false));
        } else {
            return new GameDownloadViewHolder(FmDownloadmanagerItemBinding.inflate(mLayoutInflater, parent, false));
        }
    }

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

            viewHolder.binding.getRoot().setBackground(ContextCompat.getDrawable(mContext, com.gh.gamecenter.common.R.drawable.reuse_listview_item_style));

            viewHolder.binding.dmItemTvTitle.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_primary));
            ExtensionsKt.removeDrawable(viewHolder.binding.dmItemTvSpeed);

            final DownloadEntity downloadEntity;
            if (mDownloadedList.size() != 0 && position > 0 && position <= mDownloadedList.size()) {
                downloadEntity = mDownloadedList.get(position - 1);
            } else if (mDownloadedList.isEmpty()) {
                downloadEntity = mDownloadingList.get(position - 1);
            } else {
                downloadEntity = mDownloadingList.get(position - mDownloadedList.size() - 2);
            }
            String icon = downloadEntity.getIcon();
            String rawIcon = ExtensionsKt.getMetaExtra(downloadEntity, Constants.RAW_GAME_ICON);
            if (!TextUtils.isEmpty(icon)) {
                if (!TextUtils.isEmpty(rawIcon)) {
                    icon = rawIcon;
                }
                IconFloat iconFloat = new IconFloat(
                        ExtensionsKt.getMetaExtra(downloadEntity, Constants.GAME_ICON_FLOAT_TOP_TEXT),
                        ExtensionsKt.getMetaExtra(downloadEntity, Constants.GAME_ICON_FLOAT_TOP_COLOR),
                        ExtensionsKt.getMetaExtra(downloadEntity, Constants.GAME_ICON_FLOAT_BOTTOM_TEXT)
                );
                viewHolder.binding.dmItemIvIcon.displayGameIcon(icon, ExtensionsKt.getMetaExtra(downloadEntity, Constants.GAME_ICON_SUBSCRIPT), iconFloat);
            } else {
                ImageUtils.display(viewHolder.binding.dmItemIvIcon.getIconIv(), com.gh.gamecenter.common.R.mipmap.logo);
                viewHolder.binding.dmItemIvIcon.getIconDecoratorIv().setVisibility(View.GONE);
            }

            String downloadTitle;
            if (downloadEntity.getName().contains("光环助手")
                    || !downloadEntity.isPlugin()) {
                downloadTitle = downloadEntity.getName();
            } else {
                String platform = downloadEntity.getPlatform();
                platform = PlatformUtils.getInstance(mContext).getPlatformName(platform);
                if (platform == null) {
                    downloadTitle = downloadEntity.getName();
                } else {
                    downloadTitle = downloadEntity.getName() + " - " + platform;
                }
            }

            if (!TextUtils.isEmpty(downloadEntity.getVersionName())) {
                downloadTitle = downloadTitle + " - V" + downloadEntity.getVersionName();
            }

            if (!viewHolder.binding.dmItemTvTitle.getText().equals(downloadTitle)) {
                viewHolder.binding.dmItemTvTitle.setText(downloadTitle);
            }

            if (!viewHolder.binding.dmItemTvTitle.isSelected()) {
                viewHolder.binding.dmItemTvTitle.postDelayed(() -> viewHolder.binding.dmItemTvTitle.setSelected(true), 2000);
            }

            if (downloadEntity.getUrl().equals(url)) {
                viewHolder.binding.getRoot().setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.select));
            } else {
                viewHolder.binding.getRoot().setBackgroundResource(com.gh.gamecenter.common.R.drawable.reuse_listview_item_style);
            }
            viewHolder.binding.getRoot().setOnLongClickListener(v -> {
                showDeleteDialog(viewHolder.binding.dmItemTvStartorpause, downloadEntity, viewHolder.getPosition());
                return true;
            });

            DownloadStatus status = downloadEntity.getStatus();
            String xapkStatus = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS);
            if (status.equals(DownloadStatus.done)) {
                viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_tertiary));
                viewHolder.binding.dmItemTvSpeed.setText("加载完成");
                // 重置点击事件避免复用问题
                viewHolder.binding.dmItemTvSpeed.setOnClickListener(null);
                // 双下载里的本地下载，已安装且不为更新下载的情况下，把下载文案改成启动
                if (PackagesManager.isInstalled(downloadEntity.getPackageName())
                        && !downloadEntity.isUpdate()
                        && ExtensionsKt.isLocalDownloadInDualDownloadMode(downloadEntity)) {
                    viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.launch);
                } else {
                    viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.install);
                }

                if (XapkUnzipStatus.UNZIPPING.name().equals(xapkStatus)) {
                    // XAPK状态有几率在SUCCESS后返回UNZIPPING, 此处对UNZIPPING之前的状态做一个判断
                    if (XapkUnzipStatus.SUCCESS.name().equals(xapkStatusMap.get(downloadEntity.getUrl()))) {
                        XapkInstaller.cancelUnzipTask(downloadEntity);
                        return;
                    }
                    String percent = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_PERCENT);
                    viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.XAPK_UNZIPPING);
                    viewHolder.binding.dmItemTvStartorpause.setProgress((int) (Float.parseFloat(percent == null ? "0" : percent) * 10));
                    viewHolder.binding.dmItemTvStartorpause.setText(percent + "%");
                    viewHolder.binding.dmItemTvSpeed.setTextColor(mContext.getResources().getColor(com.gh.gamecenter.common.R.color.text_tertiary));
                    viewHolder.binding.dmItemTvSpeed.setText(com.gh.gamecenter.feature.R.string.unzipping);
                    return;
                } else if (XapkUnzipStatus.FAILURE.name().equals(xapkStatus)) {
                    viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.install);
                    viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                    viewHolder.binding.dmItemTvStartorpause.setProgress((int) (downloadEntity.getPercent() * 10));
                    viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.secondary_red));
                    viewHolder.binding.dmItemTvSpeed.setText("解压失败");
                    viewHolder.binding.dmItemTvSpeed.setOnClickListener(v -> {
                        XapkDialogHelper.INSTANCE.showUnzipFailureDialog(mContext, downloadEntity, true);
                    });
                    ExtensionsKt.enlargeTouchArea(viewHolder.binding.dmItemTvSpeed, 50);
                    ExtensionsKt.setDrawableStart(viewHolder.binding.dmItemTvSpeed, R.drawable.unzip_failure_hint, null, null);
                } else if (XapkUnzipStatus.SUCCESS.name().equals(xapkStatus)) {
                    viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.XAPK_SUCCESS);
                    viewHolder.binding.dmItemTvStartorpause.setProgress(1000);
                    if (XapkInstaller.INSTANCE.isInstalling(downloadEntity.getPath())) {
                        viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.installing);
                    } else {
                        viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.install);
                    }
                }
                if (xapkStatus != null && !xapkStatus.isEmpty()) {
                    xapkStatusMap.put(downloadEntity.getUrl(), xapkStatus);
                }

                if (downloadEntity.isPluggable()
                        && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                    viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_PLUGIN);
                } else {
                    viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.INSTALL_NORMAL);
                }
            } else if (status.equals(DownloadStatus.downloading) || status.equals(DownloadStatus.redirected)) {
                viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
                viewHolder.binding.dmItemTvSpeed.setText(String.format("%s(剩%s)",
                        SpeedUtils.getSpeed(downloadEntity.getSpeed()),
                        SpeedUtils.getRemainTime(downloadEntity.getSize(), downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
                viewHolder.binding.dmItemTvStartorpause.setText(downloadEntity.getPercent() + "%");
                viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                viewHolder.binding.dmItemTvStartorpause.setProgress((int) (downloadEntity.getPercent() * 10));
            } else if (status.equals(DownloadStatus.waiting)) {
                viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_tertiary));
                viewHolder.binding.dmItemTvSpeed.setText(com.gh.gamecenter.feature.R.string.waiting);
                viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.waiting);
                viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.WAITING);
            } else if (status.equals(DownloadStatus.pause)
                    || status.equals(DownloadStatus.timeout)
                    || status.equals(DownloadStatus.neterror)
                    || status.equals(DownloadStatus.diskisfull)
                    || status.equals(DownloadStatus.diskioerror)
                    || status.equals(DownloadStatus.subscribe)) {
                viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.resume);
                viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
                viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_tertiary));

                if (status.equals(DownloadStatus.timeout)
                        || status.equals(DownloadStatus.neterror)
                        || status.equals(DownloadStatus.subscribe)) {
                    viewHolder.binding.dmItemTvSpeed.setText("等待WIFI");
                } else if (status.equals(DownloadStatus.diskisfull)) {
                    viewHolder.binding.dmItemTvSpeed.setText("已暂停，磁盘空间不足");
                } else {
                    viewHolder.binding.dmItemTvSpeed.setText("已暂停");
                }
            } else if (status.equals(DownloadStatus.overflow)) {
                viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_tertiary));
                viewHolder.binding.dmItemTvSpeed.setText("数据异常，请重新下载");
                viewHolder.binding.dmItemTvStartorpause.setText("失败");
                viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.FAILURE);
            }

            viewHolder.binding.dmItemTvStartorpause.setOnClickListener(v -> {
                String str = ((DownloadButton) v).getText();
                final String url = downloadEntity.getUrl();
                final String currentXApkStatus = downloadEntity.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS);
                DownloadManager.getInstance().put(url, System.currentTimeMillis());
                if (XapkUnzipStatus.SUCCESS.name().equals(currentXApkStatus) && XapkInstaller.INSTANCE.isInstalling(downloadEntity.getPath())) {
                    return;
                } else if (XapkUnzipStatus.UNZIPPING.name().equals(currentXApkStatus)) {
                    XapkInstaller.cancelUnzipTask(downloadEntity);
                    return;
                } else if (XapkUnzipStatus.FAILURE.name().equals(currentXApkStatus)
                        || XapkUnzipStatus.SUCCESS.name().equals(currentXApkStatus)) {
                    PermissionHelper.checkStoragePermissionBeforeAction(
                            mContext,
                            downloadEntity.getGameId(),
                            downloadEntity.getName(),
                            ExtensionsKt.getCategoryChinese(downloadEntity),
                            downloadEntity.getFormat(),
                            () -> {
                                final String path = downloadEntity.getPath();
                                if (downloadEntity.isPluggable()
                                        && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                                    showPluginDialog(
                                            downloadEntity.getPath(),
                                            downloadEntity.getPluginDesc(),
                                            downloadEntity.getGameId(),
                                            downloadEntity.getName(),
                                            ExtensionsKt.getGameCategory(downloadEntity),
                                            downloadEntity.getPlatform()
                                    );
                                } else {
                                    if (FileUtils.isEmptyFile(path)) {
                                        Utils.toast(mContext, com.gh.gamecenter.common.R.string.install_failure_hint);
                                        removeDownload(downloadEntity);
                                    } else {
                                        NewFlatLogUtils.INSTANCE.logGameInstall(
                                                downloadEntity.getGameId(),
                                                downloadEntity.getName(),
                                                "主动安装"
                                        );

                                        SensorsBridge.trackInstallGameClick(
                                                downloadEntity.getGameId(),
                                                downloadEntity.getName(),
                                                "主动安装",
                                                false,
                                                ""
                                        );
                                        PackageInstaller.install(mContext, downloadEntity);
                                    }
                                }
                            });
                    return;
                }

                switch (status) {
                    case pause:
                    case timeout:
                    case neterror:
                    case subscribe:
                        PermissionHelper.checkStoragePermissionBeforeAction(
                                mContext,
                                downloadEntity.getGameId(),
                                downloadEntity.getName(),
                                ExtensionsKt.getCategoryChinese(downloadEntity),
                                downloadEntity.getFormat(),
                                () -> {
                                    // 下载管理不用判断是否大于50M
                                    DialogUtils.checkDownload(mContext, Float.toString(100F), downloadEntity.getGameId(), downloadEntity.getName(), ExtensionsKt.getGameCategory(downloadEntity), isSubscribe -> {
                                        if (isSubscribe) {
                                            DownloadManager.getInstance().subscribe(downloadEntity);
                                            statusMap.put(url, DownloadStatus.subscribe.getStatus());
                                            notifyItemChanged(mDownloadedList.isEmpty() ? 0 : 1 + mDownloadedList
                                                    .size());
                                        } else {
                                            viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
                                            viewHolder.binding.dmItemTvSpeed.setText(String.format("%s(剩%s)",
                                                    SpeedUtils.getSpeed(downloadEntity.getSpeed()),
                                                    SpeedUtils.getRemainTime(downloadEntity.getSize(),
                                                            downloadEntity.getProgress(), downloadEntity.getSpeed() * 1024)));
                                            viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.DOWNLOADING_NORMAL);
                                            viewHolder.binding.dmItemTvStartorpause.setText(downloadEntity.getPercent() + "%");
                                            viewHolder.binding.dmItemTvStartorpause.setProgress((int) (downloadEntity.getPercent() * 10));
                                            statusMap.put(url, DownloadStatus.downloading.getStatus());
                                            notifyItemChanged(mDownloadedList.isEmpty() ? 0 : 1 + mDownloadedList
                                                    .size());
                                            DownloadManager.getInstance().resume(downloadEntity, false);
                                        }
                                    });
                                });
                        break;
                    case done:
                        if (str.equals(mContext.getString(com.gh.gamecenter.feature.R.string.install))) {
                            PermissionHelper.checkStoragePermissionBeforeAction(
                                    mContext,
                                    downloadEntity.getGameId(),
                                    downloadEntity.getName(),
                                    ExtensionsKt.getCategoryChinese(downloadEntity),
                                    downloadEntity.getFormat(),
                                    () -> {
                                        final String path = downloadEntity.getPath();
                                        if (downloadEntity.isPluggable()
                                                && PackagesManager.isInstalled(downloadEntity.getPackageName())) {
                                            showPluginDialog(
                                                    downloadEntity.getPath(),
                                                    downloadEntity.getPluginDesc(),
                                                    downloadEntity.getGameId(),
                                                    downloadEntity.getName(),
                                                    ExtensionsKt.getGameCategory(downloadEntity),
                                                    downloadEntity.getPlatform()
                                            );
                                        } else {
                                            if (FileUtils.isEmptyFile(path)) {
                                                Utils.toast(mContext, com.gh.gamecenter.common.R.string.install_failure_hint);
                                                removeDownload(downloadEntity);
                                            } else {
                                                NewFlatLogUtils.INSTANCE.logGameInstall(
                                                        downloadEntity.getGameId(),
                                                        downloadEntity.getName(),
                                                        "主动安装"
                                                );

                                                SensorsBridge.trackInstallGameClick(
                                                        downloadEntity.getGameId(),
                                                        downloadEntity.getName(),
                                                        "主动安装",
                                                        "true".equals(ExtensionsKt.getMetaExtra(downloadEntity, Constants.DSP_GAME)),
                                                        ExtensionsKt.getMetaExtra(downloadEntity, Constants.DSP_AD_ID)
                                                );
                                                PackageInstaller.install(mContext, downloadEntity);
                                            }
                                        }
                                    });
                        } else if (str.equals(mContext.getString(com.gh.gamecenter.feature.R.string.launch))) {
                            PackageLauncher.launchApp(mContext, null, downloadEntity.getPackageName());
                        }
                        break;
                    case redirected:
                    case downloading:
                        viewHolder.binding.dmItemTvStartorpause.setText(com.gh.gamecenter.feature.R.string.resume);
                        viewHolder.binding.dmItemTvStartorpause.setButtonStyle(DownloadButton.ButtonStyle.NORMAL);
                        viewHolder.binding.dmItemTvSpeed.setText("已暂停");
                        viewHolder.binding.dmItemTvSpeed.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_tertiary));
                        statusMap.put(url, DownloadStatus.pause.getStatus());
                        notifyItemChanged(mDownloadedList.isEmpty() ? 0 : 1 + mDownloadedList.size());

                        DownloadManager.getInstance().pause(downloadEntity.getUrl());
                        break;
                    case waiting:
                        Utils.toast(mContext, "最多只能同时下载三个任务，请稍等");
                        break;
                    case overflow:
                        DialogHelper.showCenterDialog(mContext
                                , "下载失败"
                                , "安装包数据校验失败，无法完成下载，建议删除任务重新下载"
                                , "知道了", "", () -> {
                                }, () -> {
                                });
                        break;
                }
//                DataUtils.onMtaEvent(HaloApp.getInstance().getApplication(), "下载管理", "游戏下载", str);
            });
        } else if (holder instanceof DownloadHeadViewHolder) {
            final DownloadHeadViewHolder viewHolder = (DownloadHeadViewHolder) holder;

            viewHolder.binding.getRoot().setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_surface));
            viewHolder.binding.divider.setBackgroundColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.ui_background));
            viewHolder.binding.dmItemHeadTvTask.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_6c6c6c));
            viewHolder.binding.dmItemHeadTvAllstart.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));

            if (position == 0 && mDownloadedList.size() != 0) {
                viewHolder.binding.dmItemHeadTvTask.setText("已完成");
                viewHolder.binding.dmItemHeadTvAllstart.setVisibility(View.GONE);
            } else {
                viewHolder.binding.dmItemHeadTvTask.setText(com.gh.gamecenter.feature.R.string.downloading);
                viewHolder.binding.dmItemHeadTvAllstart.setVisibility(View.VISIBLE);

                int dlNumber = 0;
                int wtNumber = 0;
                for (DownloadEntity downloadEntity : mDownloadingList) {
                    if (DownloadStatus.downloading.equals(downloadEntity.getStatus())) {
                        dlNumber++;
                    } else if (DownloadStatus.waiting.equals(downloadEntity.getStatus())) {
                        wtNumber++;
                    }
                }
                if ((dlNumber + wtNumber) == mDownloadingList.size()) {
                    viewHolder.binding.dmItemHeadTvAllstart.setText(R.string.download_all_push);
                    viewHolder.binding.dmItemHeadTvAllstart.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.btn_gray));
                } else {
                    viewHolder.binding.dmItemHeadTvAllstart.setText(R.string.download_all_start);
                    viewHolder.binding.dmItemHeadTvAllstart.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
                }

                viewHolder.binding.dmItemHeadTvAllstart.setOnClickListener(v -> {
                    String str = ((TextView) v).getText().toString();
                    if (mContext.getString(R.string.download_all_start).equals(str)) {
                        if (NetworkUtils.isWifiConnected(mContext)) {
                            startAll(viewHolder);
                        } else {
                            DialogHelper.showDownloadDialog(mContext, () -> startAll(viewHolder));
                        }
                    } else {
                        pauseAll(viewHolder);
                    }
                });
            }
        }
    }

    public void startAll(DownloadHeadViewHolder viewHolder) {
        for (DownloadEntity downloadEntity : mDownloadingList) {
            DownloadManager.getInstance().put(downloadEntity.getUrl(),
                    System.currentTimeMillis());
            Message msg = Message.obtain();
            msg.what = DownloadConfig.CONTINUE_DOWNLOAD_TASK;
            msg.obj = downloadEntity.getUrl();
            DownloadManager.getInstance().sendMessageDelayed(msg, 1000);
//            DownloadManager.getInstance().add(downloadEntity);
            statusMap.put(downloadEntity.getUrl(), DownloadStatus.downloading.getStatus());
        }

//        DownloadManager.getInstance().startAll();

        viewHolder.binding.dmItemHeadTvAllstart.setText(R.string.download_all_push);
        viewHolder.binding.dmItemHeadTvAllstart.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.btn_gray));
    }

    public void pauseAll(DownloadHeadViewHolder viewHolder) {
        for (DownloadEntity downloadEntity : mDownloadingList) {
            DownloadManager.getInstance().put(downloadEntity.getUrl(),
                    System.currentTimeMillis());
            Message msg = Message.obtain();
            msg.what = DownloadConfig.PAUSE_DOWNLOAD_TASK;
            msg.obj = downloadEntity.getUrl();
            DownloadManager.getInstance().sendMessageDelayed(msg, 1000);
//            DownloadManager.getInstance(getContext()).pause(downloadEntity);
        }

//        DownloadManager.getInstance().pauseAll();

        viewHolder.binding.dmItemHeadTvAllstart.setText("全部开始");
        viewHolder.binding.dmItemHeadTvAllstart.setTextColor(ContextCompat.getColor(mContext, com.gh.gamecenter.common.R.color.text_theme));
    }


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

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

    // 显示插件化
    void showPluginDialog(
            final String path,
            final String pluginDesc,
            final String gameId,
            final String gameName,
            final String gameType,
            final String platform
    ) {
        DialogHelper.showPluginDialog(
                mContext,
                pluginDesc,
                gameId != null ? gameId : "",
                gameName != null ? gameName : "",
                gameType != null ? gameType : "",
                platform != null ? platform : "",
                () -> {
                    if (FileUtils.isEmptyFile(path)) {
                        Utils.toast(mContext, com.gh.gamecenter.common.R.string.install_failure_hint);
                    } else {
                        PackageInstaller.uninstall(mContext, path);
                    }
                    return null;
                });
    }

    private void removeDownload(DownloadEntity entry) {
        DownloadManager.getInstance().cancel(entry.getUrl());

        Integer location = locationMap.get(entry.getUrl());
        if (location == null) {
            return;
        }
        boolean isDone = false;
        for (DownloadEntity downloadEntity : mDownloadedList) {
            if (entry.getUrl().equals(downloadEntity.getUrl())) {
                isDone = true;
                break;
            }
        }
        if (isDone) {
            if (mDownloadingList.isEmpty() && mDownloadedList.size() == 1) {
                mDownloadedList.remove(location.intValue());
                locationMap.clear();
                notifyDataSetChanged();
                EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, 0));
                if (mNoDataSkip.getVisibility() == View.GONE) {
                    mNoDataSkip.setVisibility(View.VISIBLE);
                }
            } else if (mDownloadedList.size() == 1) {
                mDownloadedList.remove(location.intValue());
                initLocationMap();
                notifyItemRangeRemoved(0, 2);
                EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                        mDownloadingList.size()));
            } else {
                mDownloadedList.remove(location.intValue());
                initLocationMap();
                notifyItemRemoved(location + 1);
                EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                        mDownloadingList.size()));
            }
        } else {
            if (mDownloadedList.isEmpty() && mDownloadingList.size() == 1) {
                mDownloadingList.remove(location.intValue());
                locationMap.clear();
                notifyDataSetChanged();
                EventBus.getDefault().post(new EBDownloadChanged("download", View.GONE, 0));
                if (mNoDataSkip.getVisibility() == View.GONE) {
                    mNoDataSkip.setVisibility(View.VISIBLE);
                }
            } else if (mDownloadingList.size() == 1) {
                mDownloadingList.remove(location.intValue());
                initLocationMap();
                notifyItemRangeRemoved(getBase(), 2);
                EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                        mDownloadingList.size()));
            } else {
                mDownloadingList.remove(location.intValue());
                initLocationMap();
                notifyDataSetChanged();
                EventBus.getDefault().post(new EBDownloadChanged("download", View.VISIBLE,
                        mDownloadingList.size()));
            }
        }

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

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

    // 显示删除提示框
    private void showDeleteDialog(DownloadButton downloadButton, final DownloadEntity entry, final int position) {
        boolean autoPause = DownloadStatus.downloading.equals(entry.getStatus());
        if (autoPause) {
            downloadButton.performClick();
        }
        String xapkStatus = entry.getMeta().get(XapkInstaller.XAPK_UNZIP_STATUS);
        String contentText;
        if (XapkUnzipStatus.UNZIPPING.name().equals(xapkStatus)) {
            contentText = "游戏正在解压安装哦，确定删除？";
        } else if (mDownloadedList.size() != 0 && position <= mDownloadedList.size()) {
            contentText = "游戏还没安装哦，确定删除？";
        } else {
            contentText = "游戏还没下载完，确定删除？";
        }

        DialogHelper.showDeleteDialog(mContext, "删除游戏", contentText, "删除", "再等等", () -> {
            removeDownload(entry);
            if (XapkUnzipStatus.UNZIPPING.name().equals(xapkStatus)) {
                XapkInstaller.cancelUnzipTask(entry);
            }
        }, () -> {
            if (autoPause) {
                downloadButton.performClick();
            }
        }, true);
    }

    public void initLocationMap() {
        locationMap.clear();
        for (int i = 0; i < mDownloadedList.size(); i++) {
            locationMap.put(mDownloadedList.get(i).getUrl(), i);
        }
        for (int i = 0; i < mDownloadingList.size(); i++) {
            locationMap.put(mDownloadingList.get(i).getUrl(), i);
        }
    }

    public int getBase() {
        return mDownloadedList.isEmpty() ? 0 : 1 + mDownloadedList.size();
    }

    List<DownloadEntity> getDownloadingList() {
        return mDownloadingList;
    }

    List<DownloadEntity> getDoneList() {
        return mDownloadedList;
    }

    public ArrayMap<String, Integer> getLocationMap() {
        return locationMap;
    }

    Integer getLocation(String url) {
        return locationMap.get(url);
    }

    ArrayMap<String, String> getStatusMap() {
        return statusMap;
    }

    ArrayMap<String, String> getUrlMap() {
        return urlMap;
    }

    public String getUrl(String packageName) {
        return urlMap.get(packageName);
    }

    ArrayList<String> getDeleteList() {
        return deleteList;
    }

    void initMap() {
        mDownloadingList.clear();
        mDownloadedList.clear();
        statusMap.clear();
        urlMap.clear();
        for (DownloadEntity downloadEntity : DownloadManager.getInstance().getAllDownloadEntityExcludeSilentTask()) {
            statusMap.put(downloadEntity.getUrl(), downloadEntity.getStatus().name());
            if (DownloadStatus.done.equals(downloadEntity.getStatus())) {
                if (!ExtensionsKt.isSimulatorGame(downloadEntity)) {
                    urlMap.put(downloadEntity.getPackageName(), downloadEntity.getUrl());
                    mDownloadedList.add(downloadEntity);
                }
            } else {
                mDownloadingList.add(downloadEntity);
            }
        }
        // 排序
        Comparator<DownloadEntity> comparator = (lhs, rhs) -> {
            if (rhs.getStart() > lhs.getStart()) {
                return 1;
            } else if (rhs.getStart() < lhs.getStart()) {
                return -1;
            } else {
                return 0;
            }
        };
        Collections.sort(mDownloadingList, comparator);

        comparator = (lhs, rhs) -> {
            if (rhs.getEnd() > lhs.getEnd()) {
                return 1;
            } else if (rhs.getEnd() < lhs.getEnd()) {
                return -1;
            } else {
                return 0;
            }
        };
        Collections.sort(mDownloadedList, comparator);

        initLocationMap();
    }

    public void setUrl(String url) {
        this.url = url;
        notifyItemRangeChanged(0, getItemCount());
    }
}
