package com.wzkj.vzone.org.ui.fragment.history;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.wuxiaolong.pullloadmorerecyclerview.PullLoadMoreRecyclerView;
import com.wzkj.vzone.org.R;
import com.wzkj.vzone.org.base.Operation;
import com.wzkj.vzone.org.common.CommonUrl;
import com.wzkj.vzone.org.common.ConstantUtil;
import com.wzkj.vzone.org.entity.SuccessEntity;
import com.wzkj.vzone.org.entity.TypeGameEntity;
import com.wzkj.vzone.org.entity.TypeTask;
import com.wzkj.vzone.org.eventEntity.InstallInfo;
import com.wzkj.vzone.org.listener.OnTypeTaskClickListener;
import com.wzkj.vzone.org.ui.activity.ForumActivity;
import com.wzkj.vzone.org.ui.activity.GameDetailTypeActivity;
import com.wzkj.vzone.org.ui.activity.LoginActivity;
import com.wzkj.vzone.org.util.AppTool;
import com.wzkj.vzone.org.util.DialogTool;
import com.wzkj.vzone.org.util.FastJsonUtils;
import com.wzkj.vzone.org.util.ToastUtils;
import com.wzkj.vzone.org.util.ToolFile;
import com.wzkj.vzone.org.util.ToolHttp;
import com.wzkj.vzone.org.util.ToolImage;
import com.wzkj.vzone.org.util.ToolPhone;
import com.wzkj.vzone.org.widget.progressBar.MyProgressBar;
import com.wzkj.vzone.org.widget.roundedImageView.RoundedImageView;

import org.apache.http.Header;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Executor;


/**
 * 推荐游戏
 *
 * @author Jason
 */
public class NetGameFragment extends Fragment {

    private PullLoadMoreRecyclerView plmrv_recommend;
    private RecyclerViewAdapter recommendAdapter;
    private List<TypeTask> currentTasks;

    private LinearLayout ll_retry;
    private Button btn_retry;
    private boolean isEmpty = true;

    private int page = 1;

    public static NetGameFragment getInstance(String title) {
        NetGameFragment sf = new NetGameFragment();
        return sf;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_net_game, null);

        /**
         * 设置状态栏背景
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setTranslucentStatus(true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this.getActivity());
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.transparent);
            tintManager.setNavigationBarTintEnabled(true);
            tintManager.setStatusBarAlpha(1f);
        }

        ll_retry = (LinearLayout) view.findViewById(R.id.ll_retry);
        btn_retry = (Button) view.findViewById(R.id.btn_retry);
        btn_retry.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ToolHttp.checkNetwork()) { // 有网
                    ll_retry.setVisibility(View.GONE);
                    getCurrentGameData();
                }
            }
        });

        //正在进行的任务任务listview
        currentTasks = new ArrayList<>();

        plmrv_recommend = (PullLoadMoreRecyclerView) view.findViewById(R.id.plmrv_recommend);
        plmrv_recommend.setLinearLayout();
        plmrv_recommend.setPullRefreshEnable(false);// 需要下拉刷新
        plmrv_recommend.setPushRefreshEnable(true);// 需要上拉刷新
        plmrv_recommend.setFooterViewText("正在加载");

        recommendAdapter = new RecyclerViewAdapter(currentTasks);
        recommendAdapter.setOnTypeTaskClickListener(new OnTypeTaskClickListener() {
            @Override
            public void onCurrentTaskClick(TypeTask currentTask, String hasGift) {
                if (ConstantUtil.isUserLogin()) {
                    // 把详情请求地址放在intent里传递过去
                    Intent gameDetailIntent = new Intent(getActivity(), GameDetailTypeActivity.class);
                    gameDetailIntent.putExtra("url", currentTask.getAnd_dow_address());
                    gameDetailIntent.putExtra("gameId", currentTask.getId());
                    gameDetailIntent.putExtra("packageName", currentTask.getAnd_package());

                    new Operation(getActivity()).forward(gameDetailIntent);
                } else {
                    new Operation(getActivity()).forward(LoginActivity.class);
                }
            }

            @Override
            public void onGameGiftClick(TypeTask currentTask) {
                if (ConstantUtil.isUserLogin()) {
                    // 领取游戏礼包
                    getGameGift(currentTask.getId(), 2);
                } else {
                    new Operation(getActivity()).forward(LoginActivity.class);
                }
            }

            @Override
            public void onForumClick(String url) {
                if (!TextUtils.isEmpty(url)) {
                    Intent forumIntent = new Intent(getActivity(), ForumActivity.class);
                    forumIntent.putExtra("forum_url", url);
                    startActivity(forumIntent);
                } else {
                    ToastUtils.showShort(getActivity(), "暂无相关论坛资讯");
                }
            }
        });
        plmrv_recommend.setAdapter(recommendAdapter);
        plmrv_recommend.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getCurrentGameData();
            }

            @Override
            public void onLoadMore() {
                page++;
                getCurrentGameData();
            }
        });

        if (ToolHttp.checkNetwork()) { // 有网
            getCurrentGameData();
        } else {
            showEmptyView();
        }

        //上报后的Crash会显示该标签
        CrashReport.setUserSceneTag(getActivity(), 15489);
        //得到缓存对象
        return view;
    }

    /**
     * 设置状态栏背景
     */
    @TargetApi(19)
    private void setTranslucentStatus(boolean on) {
        Window win = getActivity().getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    /**
     * 初始化当前任务
     */
    public void getCurrentGameData() {
        // 获取正在进行的任务
        RequestParams currentParams = new RequestParams();
        currentParams.put("platform", 0);
        currentParams.put("uid", ConstantUtil.UID);
        currentParams.put("type", 1);
        currentParams.put("page", page);// 起始页为1

        ToolHttp.getClient().get(CommonUrl.URL_TYPE_GAME, currentParams, getCurrentTaskResponseHandler());
    }


    /**
     * 获取正在进行的任务
     */
    private ResponseHandlerInterface getCurrentTaskResponseHandler() {
        return new JsonHttpResponseHandler() {

            @Override
            public void onFinish() {
                super.onFinish();
                plmrv_recommend.setPullLoadMoreCompleted();
            }

            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                super.onProgress(bytesWritten, totalSize);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                if (response != null) {
                    TypeGameEntity gameEntity = FastJsonUtils.stringToObject(response.toString(), TypeGameEntity.class);
                    if (gameEntity != null) {
                        if (gameEntity.getCode() == 200) {
                            //放入缓存中
                            setCurrentGameData(gameEntity, page);
                        } else if (gameEntity.getCode() == 401) {
                            ToastUtils.showLong(NetGameFragment.this.getActivity(), gameEntity.getMsg());
                            new Operation(getActivity()).forward(LoginActivity.class);
                        } else {
                            ToastUtils.showLong(NetGameFragment.this.getActivity(), gameEntity.getMsg());
                        }
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                if (errorResponse == null) {
                    ToastUtils.showLong(NetGameFragment.this.getActivity(), ConstantUtil.ERRORMSG);
                } else {
                    ToastUtils.showShort(getActivity(), errorResponse.toString());
                }

                if (page > 1) {
                    page--;
                }
            }
        };
    }

    /**
     * 更新正在进行的任务
     */
    private void setCurrentGameData(TypeGameEntity gameEntity, int page) {
        if (page == 1) {
            if (currentTasks != null) {
                if (currentTasks.size() > 0) {
                    currentTasks.clear();
                }
            }
        }


        List<TypeTask> games = gameEntity.getList();
        if (games == null || games.size() == 0) {
            ToastUtils.showShort(getActivity(), "没有更多数据啦");
        } else {
            currentTasks.addAll(games);
            recommendAdapter.notifyDataSetChanged();
        }
    }


    /**
     * 显示重试
     */
    private void showEmptyView() {
        if (ll_retry != null) {
            if (isEmpty) {
                ll_retry.setVisibility(View.VISIBLE);
            } else {
                ll_retry.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 领取游戏礼包
     */
    private void getGameGift(String gameId, int type) {
        // 2表示游戏礼包
        RequestParams params = new RequestParams();
        params.put("uid", ConstantUtil.UID);
        params.put("token", ConstantUtil.TOKEN);
        params.put("gid", gameId);
        params.put("p_i", ToolPhone.getImei(getActivity()));
        params.put("t", type);
        ToolHttp.getClient().get(CommonUrl.gameAwardURL, params, getGameGiftResponseHandler());
    }

    /**
     * 领取游戏礼包
     */
    private ResponseHandlerInterface getGameGiftResponseHandler() {
        return new JsonHttpResponseHandler() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onProgress(int bytesWritten, int totalSize) {
                super.onProgress(bytesWritten, totalSize);

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                if (response != null) {
                    SuccessEntity successEntity = FastJsonUtils.stringToObject(response.toString(), SuccessEntity.class);
                    if (successEntity != null) {
                        // 刷新个人资料
                        if (!TextUtils.isEmpty(successEntity.getNovice())) {
                            DialogTool.gameGiftDialog(getActivity(), successEntity.getNovice(), successEntity.getGiftbag_name(), successEntity.getDesribe());
                        } else {
                            ToastUtils.showShort(getActivity(), "暂无礼包");
                        }

                    } else {
                        ToastUtils.showShort(getActivity(), "暂无礼包");
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                ToastUtils.showShort(getActivity(), "暂无礼包");
            }
        };
    }

    class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

        private List<TypeTask> recommendTasks;
        private OnTypeTaskClickListener onTypeTaskClickListener;

        public void setOnTypeTaskClickListener(OnTypeTaskClickListener onTypeTaskClickListener) {
            this.onTypeTaskClickListener = onTypeTaskClickListener;
        }

        public RecyclerViewAdapter(List<TypeTask> recommendTasks) {
            this.recommendTasks = recommendTasks;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_net_game, null, false);
            ViewHolder viewHolder = new ViewHolder(view);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            if (recommendTasks != null && recommendTasks.size() > 0) {

                // 海报，解决图片错乱
                final TypeTask typeTask = recommendTasks.get(position);
                if (!TextUtils.isEmpty(typeTask.getIcon())) {
                    final String tag = (String) holder.riv_game_icon.getTag();
                    final String uri = typeTask.getIcon();
                    if (!uri.equals(tag)) {
                        // 设置默认图片
                        holder.riv_game_icon.setImageResource(R.mipmap.show_default);

                        holder.riv_game_icon.setTag(uri);
                        ToolImage.getImageLoader().displayImage(uri, holder.riv_game_icon, ToolImage.getFadeOptions(R.mipmap.show_default, R.mipmap.show_default));

                    }
                } else {
                    // 设置默认图片
                    holder.riv_game_icon.setImageResource(R.mipmap.show_default);
                }

                // 游戏名称
                holder.tv_game_name.setText(typeTask.getGame_name());
                holder.tv_desc.setText(typeTask.getIntroduction());
                holder.tv_down_size.setText(String.format("%s  %s人下载", typeTask.getGame_size(), typeTask.getDow_num()));

                final String gift = typeTask.getGift_bag();// 0" 无礼包不显示礼包按钮，"1"有礼包，显示礼包按钮
                if (TextUtils.equals(gift, "0")) {
                    holder.btn_get_gift.setVisibility(View.GONE);
                } else {
                    holder.btn_get_gift.setVisibility(View.VISIBLE);
                }
                holder.riv_game_icon.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onTypeTaskClickListener != null) {
                            onTypeTaskClickListener.onCurrentTaskClick(typeTask, gift);
                        }
                    }
                });

                holder.ll_net_game.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onTypeTaskClickListener != null) {
                            onTypeTaskClickListener.onCurrentTaskClick(typeTask, gift);
                        }
                    }
                });

                /**
                 * 点击领取礼包
                 */
                holder.btn_get_gift.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onTypeTaskClickListener != null) {
                            onTypeTaskClickListener.onGameGiftClick(typeTask);
                        }
                    }
                });


                /**
                 * 点击论坛攻略
                 */
                holder.btn_forum_tips.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (onTypeTaskClickListener != null) {
                            onTypeTaskClickListener.onForumClick(typeTask.getGame_bbs());
                        }
                    }
                });



                // 查看当前状态
                if (typeTask.isRefreshing()) {
                    // 当前状态正在刷新，隐藏下载按钮，显示进度条，并设置进度条的值
                    holder.btn_download_install_open.setVisibility(View.GONE);
                    holder.mpb_download_progress.setVisibility(View.VISIBLE);
                    holder.mpb_download_progress.setProgress(typeTask.getProgress());
                } else {
                    // 当前不是刷新状态，隐藏进度条，显示下载按钮
                    holder.btn_download_install_open.setVisibility(View.VISIBLE);
                    holder.mpb_download_progress.setVisibility(View.GONE);
                }


                if (AppTool.checkApkExist(getActivity(), typeTask.getAnd_package())) {
                    // 游戏已安装
                    holder.btn_download_install_open.setText("打开");
                    holder.btn_download_install_open.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AppTool.openAppByPackageName(getActivity(), typeTask.getAnd_package());
                        }
                    });
                } else {
                    final String localGamePath = ConstantUtil.LOCAL_DOWNLOAD_PATH+typeTask.getGame_name()+".apk";
                    typeTask.setGameLocalPath(localGamePath);

                    File file = new File(localGamePath);
                    if (file.exists()) {
                        // 游戏已下载，但还没安装
                        holder.btn_download_install_open.setText("安装");
                        holder.btn_download_install_open.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppTool.install(getActivity(), localGamePath);
                            }
                        });
                    } else {
                        // 游戏还没下载
                        holder.btn_download_install_open.setText("下载");
                        holder.btn_download_install_open.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 下载游戏之前的准备工作
                                if (TextUtils.isEmpty(typeTask.getAnd_dow_address())) {
                                    ToastUtils.showShort(getActivity(), "游戏下载地址为空");
                                    return;
                                }

                                int gameSize = 0;
                                try {
                                    gameSize = Integer.parseInt(typeTask.getGame_size().toLowerCase().replace("m", "").replace("b", ""));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                if (gameSize > ToolFile.getSDFreeSize()) {
                                    ToastUtils.showShort(getActivity(), "存储空间不足，请清理缓存后重试");
                                    return;
                                }

                                if (!TextUtils.isEmpty(typeTask.getGameLocalPath())) {

                                } else {
                                    ToastUtils.showShort(getActivity(), "未找到本地下载路径");
                                }

                                if (ConstantUtil.DOWNLOAD_TASKS != null && ConstantUtil.DOWNLOAD_TASKS.size() > 3) {
                                    ToastUtils.showShort(getActivity(), "您最多能同时下载3个任务");
                                    return;
                                }



                                typeTask.setRefreshing(true);// 状态为正在刷新
                                holder.btn_download_install_open.setVisibility(View.GONE);// 开始下载，隐藏下载按钮
                                holder.mpb_download_progress.setVisibility(View.VISIBLE);// 显示进度条
                                holder.mpb_download_progress.setProgress(0);// 初始化进度为0%
                                downloadGame(position, typeTask);
                                // 已开始下载的话
                            }
                        });
                    }
                }

                // 点击进度条取消当前任务
                holder.mpb_download_progress.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (ConstantUtil.DOWNLOAD_TASKS != null) {
                            Callback.Cancelable cancelable = ConstantUtil.DOWNLOAD_TASKS.get(typeTask.getId());
                            if (cancelable != null) {
                                cancelable.cancel();
                            }

                            typeTask.setRefreshing(false);// 现在停止刷新
                            holder.mpb_download_progress.setVisibility(View.GONE);// 隐藏进度条
                            holder.btn_download_install_open.setVisibility(View.VISIBLE);// 显示下载|安装|打开按钮
                        }
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return recommendTasks == null ? 0 : recommendTasks.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            LinearLayout ll_net_game;
            RoundedImageView riv_game_icon;

            Button btn_forum_tips;
            Button btn_get_gift;

            TextView tv_game_name;

            TextView tv_desc;// 描述
            TextView tv_down_size;// 描述

            Button btn_download_install_open;
            MyProgressBar mpb_download_progress;

            public ViewHolder(View itemView) {
                super(itemView);

                // 这里查找控件
                ll_net_game = (LinearLayout) itemView.findViewById(R.id.ll_net_game);
                riv_game_icon = (RoundedImageView) itemView.findViewById(R.id.riv_game_icon);
                btn_forum_tips = (Button) itemView.findViewById(R.id.btn_forum_tips);
                btn_get_gift = (Button) itemView.findViewById(R.id.btn_get_gift);
                tv_game_name = (TextView) itemView.findViewById(R.id.tv_game_name);

                tv_desc = (TextView) itemView.findViewById(R.id.tv_desc);
                tv_down_size = (TextView) itemView.findViewById(R.id.tv_down_size);

                btn_download_install_open = (Button) itemView.findViewById(R.id.btn_download_install_open);
                mpb_download_progress = (MyProgressBar) itemView.findViewById(R.id.mpb_download_progress);
            }
        }
    }


    private final Executor executor = new PriorityExecutor(8, true);
    /**
     * 下载游戏，这个方法在Activity销毁之后仍会继续执行
     */
    private void downloadGame(final int position, final TypeTask typeTask) {
        org.xutils.http.RequestParams params = new org.xutils.http.RequestParams(typeTask.getAnd_dow_address());
        params.setAutoResume(true);
        params.setAutoRename(false);
        params.setSaveFilePath(typeTask.getGameLocalPath());
        params.setExecutor(executor);
        params.setCancelFast(true);

        Callback.Cancelable downloadTask = x.http().get(params, new Callback.ProgressCallback<File>() {

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                // 更新下载进度
                int progress = (int)(current*100/total);
                // 把进度写进我们的对象里
                typeTask.setProgress(progress);
                // 发送进度广播
                Intent processIntent = new Intent("process");
                processIntent.putExtra("process", progress);
                processIntent.putExtra("id", typeTask.getId());
                getActivity().sendBroadcast(processIntent);
                updateProgress(position, typeTask, false);
            }

            @Override
            public void onSuccess(File result) {

            }


            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtils.showShort(getActivity(), "下载失败");
                typeTask.setRefreshing(false);

                // 发送下载失败广播
                Intent processIntent = new Intent();
                processIntent.putExtra("process", -1);
                processIntent.putExtra("id", typeTask.getId());
                getActivity().sendBroadcast(processIntent);

                updateProgress(position, typeTask, true);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                // 从列表中移除
                if (ConstantUtil.DOWNLOAD_TASKS != null) {
                    ConstantUtil.DOWNLOAD_TASKS.remove(typeTask.getId());
                }
                typeTask.setRefreshing(false);// 无论是下载完成还是下载失败，此时状态为停止刷新
            }
        });


        // 下载任务放进队列里
        if (ConstantUtil.DOWNLOAD_TASKS == null) {
            ConstantUtil.DOWNLOAD_TASKS = new HashMap<>();
        }
        ConstantUtil.DOWNLOAD_TASKS.put(typeTask.getId(), downloadTask);
    }

    /**
     * 更新控件的进度，注意要判空
     * @param position 要更新的位置
     * @param isError 是否发生错误(下载失败)
     */
    public void updateProgress(int position, final TypeTask typeTask, boolean isError) {
        // 根据点击的position找到之前点击的下载按钮所在的ViewHolder
        RecyclerViewAdapter.ViewHolder viewHolder = (RecyclerViewAdapter.ViewHolder) plmrv_recommend.getRecyclerView().findViewHolderForAdapterPosition(position);

        if (viewHolder != null) {
            // 通过viewholder可以找回我们刚才点击的按钮和进度条
            Button btn_download_install_open = viewHolder.btn_download_install_open;
            MyProgressBar mpb_download_progress = viewHolder.mpb_download_progress;


            if (isError) {
                // 下载过程发生错误，显示下载按钮，隐藏进度条
                btn_download_install_open.setVisibility(View.VISIBLE);
                mpb_download_progress.setVisibility(View.GONE);
            } else {
                // 更新进度
                mpb_download_progress.setProgress(typeTask.getProgress());
                if (typeTask.getProgress() == 100) {
                    if (AppTool.checkApkExist(getActivity(), typeTask.getAnd_package())) {
                        btn_download_install_open.setText("打开");
                        btn_download_install_open.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppTool.openAppByPackageName(getActivity(), typeTask.getAnd_package());
                            }
                        });
                    } else {
                        btn_download_install_open.setText("安装");
                        btn_download_install_open.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AppTool.install(getActivity(), typeTask.getGameLocalPath());
                            }
                        });
                    }

                    btn_download_install_open.setVisibility(View.VISIBLE);
                    mpb_download_progress.setVisibility(View.GONE);
                } else {
                    btn_download_install_open.setVisibility(View.GONE);
                    mpb_download_progress.setVisibility(View.VISIBLE);
                }

            }
        }
    }




    @Subscribe
    public void onEventMainThread(final InstallInfo installInfo) {

        // 安装完成
        if (plmrv_recommend == null) {
            return;
        }

        for (int i = 0, j = plmrv_recommend.getLayoutManager().getChildCount(); i < j; i++) {
            if (TextUtils.equals(currentTasks.get(i).getAnd_package(), installInfo.getPackageName())) {

                View view = plmrv_recommend.getLayoutManager().findViewByPosition(i);
                Button btn_download_install_open = (Button) view.findViewById(R.id.btn_download_install_open);
                btn_download_install_open.setText("打开");
                btn_download_install_open.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AppTool.openAppByPackageName(getActivity(), installInfo.getPackageName());
                    }
                });

                if (ConstantUtil.deleteAfterInstall) {
                    // 自动删除
                    File file = new File(currentTasks.get(i).getGameLocalPath());
                    if (file.exists()) {
                        file.delete();
                    }
                }
                break;
            }
        }
    }
}