package com.mjsheng.myappstore.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.bumptech.glide.Glide;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.adapter.AppUpdateListAdapter;
import com.mjsheng.myappstore.adapter.DownloadListAdapter;
import com.mjsheng.myappstore.adapter.UninstallListAdapter;
import com.mjsheng.myappstore.base.BaseActivity;
import com.mjsheng.myappstore.bean.AppContentInfo;
import com.mjsheng.myappstore.bean.AppDownloadInfo;
import com.mjsheng.myappstore.bean.AppUpdateInfo;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LocalAppInfo;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.utils.AppsManagerUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.SpacesItemDecoration;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.view.RecycleGridLayoutManager;
import com.mjsheng.myappstore.widget.Sound;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.Response;

public class DownloadActivity extends BaseActivity implements OnCheckedChangeListener, Runnable {

    private static final int DOWNLOAD_RADID_BTTON_INDEX = 10;
    private static final int UNINSTALL_RADID_BTTON_INDEX = 11;
    private static final int UPDATE_RADID_BTTON_INDEX = 12;
    private static final int ABOUT_RADID_BTTON_INDEX = 13;

    private DownloadListAdapter mDownloadListAdapter;
    private UninstallListAdapter mUninstallListAdapter;
    private AppUpdateListAdapter mUpdateAppListAdapter;
    private RelativeLayout reLayout1, reLayout2, reLayout3;
    private RecyclerView mDownloadListView, mUninstallListView, mAppupdateListView;
    private RadioButton mDownloadRadioButton, mUpdateRadioButton, mUninstallRadioButton;
    //            , mAboutRadioButton;
    private RelativeLayout mLoadingLayout;
    private ImageView mLoadImg;
    private Integer index = 0;
    private RadioGroup mManageRadioGroup;
    private Integer LastCheckedId;
    private List<AppContentInfo> updateAllList = new ArrayList<>();
    private List<LocalAppInfo> uninstallAllList = new ArrayList<>();
    private Sound sound;
    private DownloadReceiver downloadReceiver;
    private ExecutorService mExecutorService;
    private TextView mManage_load_tv;
    private RecycleGridLayoutManager mManager;
    private RecycleGridLayoutManager mGridLayoutManager;
    private TextView mTv_version_code;
    private Button manage_about_tab;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        initParameter();
        initViews();
        switch (index) {
            case DOWNLOAD_RADID_BTTON_INDEX:
                mDownloadRadioButton.setChecked(true);
                break;
            case UNINSTALL_RADID_BTTON_INDEX:
                mUpdateRadioButton.setChecked(true);
                break;
            case UPDATE_RADID_BTTON_INDEX:
                mUninstallRadioButton.setChecked(true);
                break;
//            case ABOUT_RADID_BTTON_INDEX:
//                mAboutRadioButton.setChecked(true);
//                break;
        }
    }

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWNLOAD_RADID_BTTON_INDEX:
                    if (mDownloadListAdapter.getItemCount() == 0) {
                        //                        int width = (int) getResources().getDimension(R.dimen.managepage_notask_Width);
                        //                        ;
                        //                        int hight = (int) getResources().getDimension(R.dimen.managepage_notask_Hight);
                        //                        ;
                        //                        mLoadImg.setMaxWidth(width);
                        //                        mLoadImg.setMaxHeight(hight);
                        //                        ImageLoader.getDefault().load(DownloadActivity.this, R.drawable.manage_notask, mLoadImg);
                        mManage_load_tv.setText("没有任务");
                        mLoadingLayout.setVisibility(View.VISIBLE);
                    } else {
                        mLoadingLayout.setVisibility(View.GONE);
                    }
                    break;
                case UNINSTALL_RADID_BTTON_INDEX:
                    if (mUninstallListAdapter.getItemCount() == 0) {
                        int width = (int) getResources().getDimension(R.dimen.managepage_notask_Width);
                        ;
                        int hight = (int) getResources().getDimension(R.dimen.managepage_notask_Hight);
                        ;
                        mManage_load_tv.setText("没有任务");
                        //                        mLoadImg.setMaxWidth(width);
                        //                        mLoadImg.setMaxHeight(hight);
                        //                        ImageLoader.getDefault().load(DownloadActivity.this, R.drawable.manage_notask, mLoadImg);
                        mLoadingLayout.setVisibility(View.VISIBLE);
                    } else {
                        mLoadingLayout.setVisibility(View.GONE);
                    }
                    break;
                case UPDATE_RADID_BTTON_INDEX:
                    if (mUpdateAppListAdapter.getItemCount() == 0) {
                        //                        int width = (int) getResources().getDimension(R.dimen.managepage_noupdate_Width);
                        //                        ;
                        //                        int hight = (int) getResources().getDimension(R.dimen.managepage_notask_Hight);
                        //                        ;
                        //                        mLoadImg.setMaxWidth(width);
                        //                        mLoadImg.setMaxHeight(hight);
                        //                        ImageLoader.getDefault().load(DownloadActivity.this, R.drawable.manage_noupdate, mLoadImg);
                        mManage_load_tv.setText("没有更新");
                        mLoadingLayout.setVisibility(View.VISIBLE);
                    } else {
                        mLoadingLayout.setVisibility(View.GONE);
                    }
                    break;
                case ABOUT_RADID_BTTON_INDEX:
                    mLoadingLayout.setVisibility(View.GONE);
                    break;
                case Configure.SUCCESS:
                    Bundle data = msg.getData();
                    String httTag = data.getString("httpTag");
                    if (httTag.equals(Configure.RANKING_TYPE_UPDATE)) {
                        if (msg.obj != null) {
                            List<AppContentInfo> list = (List<AppContentInfo>) msg.obj;
                            if (!list.isEmpty()) {
                                mLoadingLayout.setVisibility(View.GONE);
                                updateAllList.addAll(list);
                                mUpdateAppListAdapter.setDatas(updateAllList);
                                mUpdateRadioButton.setText("可更新(" + list.size() + ")");
                            } else {
                                mUpdateRadioButton.setText("可更新(0)");
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }


    };
    private RecycleGridLayoutManager mLayoutManager;


    protected void initParameter() {
        setContentView(R.layout.manage_page_layout);
        sound = new Sound(DownloadActivity.this);
        mExecutorService = Executors.newCachedThreadPool();

        downloadReceiver = new DownloadReceiver();
        /* 注册广播 */
        IntentFilter mScreenOnFilter = new IntentFilter();
        mScreenOnFilter.addAction(Utils.DOWNLOAD_SERVICE_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_ALLSERVICE_ACTION);
        mScreenOnFilter.addAction(Utils.DOWNLOAD_NEWSERVICE_ACTION);
        mScreenOnFilter.addAction(Utils.ACTION_PACKAGE_REPLACED);
        mScreenOnFilter.addAction(Utils.ACTION_PACKAGE_REMOVED);
        mScreenOnFilter.addAction(Utils.ACTION_PACKAGE_ADDED);
        registerReceiver(downloadReceiver, mScreenOnFilter);

    }

    protected void initViews() {
        reLayout1 = (RelativeLayout) findViewById(R.id.manage_rLayout1);
        reLayout2 = (RelativeLayout) findViewById(R.id.manage_rLayout2);
        reLayout3 = (RelativeLayout) findViewById(R.id.manage_rLayout3);

        mDownloadListView = (RecyclerView) findViewById(R.id.download_manage_listview);
        mUninstallListView = (RecyclerView) findViewById(R.id.uninstall_manage_listview);
        mAppupdateListView = (RecyclerView) findViewById(R.id.appupdate_manage_listview);

        mManageRadioGroup = (RadioGroup) findViewById(R.id.manage_radio_group);
        mManageRadioGroup.setOnCheckedChangeListener(this);

        mDownloadRadioButton = findViewById(R.id.manage_download_tab);
        mUpdateRadioButton = findViewById(R.id.manage_update_tab);
        mUninstallRadioButton = findViewById(R.id.manage_uninstall_tab);
//        mAboutRadioButton = findViewById(R.id.manage_about_tab);

        mLoadingLayout = (RelativeLayout) findViewById(R.id.manage_linearlayout);
        mLoadImg = (ImageView) findViewById(R.id.manage_load_img);

        mManage_load_tv = (TextView) findViewById(R.id.manage_load_tv);

        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mTv_version_code = (TextView) findViewById(R.id.tv_version_code);
        mTv_version_code.setText("版本号：" + AppUtils.getAppVersionName() + "");
        mTv_version_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String registrationID = JPushInterface.getRegistrationID(DownloadActivity.this);
                Log.e("mjsheng", registrationID + "------------------------");
//                ToastUtils.showLong("registrationID::" + registrationID);
            }
        });
        manage_about_tab = findViewById(R.id.manage_about_tab);
        manage_about_tab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(DownloadActivity.this, AboutActivity.class));
            }
        });
        reLayout1.setVisibility(View.GONE);
        reLayout2.setVisibility(View.GONE);
        mDownloadRadioButton.setChecked(true);

        mExecutorService.execute(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        // 注销广播接收
        if (downloadReceiver != null) {
            unregisterReceiver(downloadReceiver);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        sound.playSoundEffect();
        RadioButton button = (RadioButton) findViewById(checkedId);
//        button.setTextColor(getResources().getColor(R.color.main_color));
        if (checkedId == R.id.manage_download_tab) {
            index = DOWNLOAD_RADID_BTTON_INDEX;
        } else if (checkedId == R.id.manage_uninstall_tab) {
            index = UNINSTALL_RADID_BTTON_INDEX;
        } else if (checkedId == R.id.manage_update_tab) {
            index = UPDATE_RADID_BTTON_INDEX;
        }
//        else if (checkedId == R.id.manage_about_tab) {
//            index = ABOUT_RADID_BTTON_INDEX;
//        }
        showContentList(index);
        if (LastCheckedId != null && LastCheckedId != checkedId) {
            RadioButton radioButton = (RadioButton) findViewById(LastCheckedId);
            //            radioButton.setBackgroundColor(Color.TRANSPARENT);
//            radioButton.setTextColor(getResources().getColor(R.color.textColor));
        }
        LastCheckedId = checkedId;
    }


    private void initUpdateAppDatas() {
        List<AppUpdateInfo> upadteApps = AppsManagerUtils.getUpadteApps(this);
        String update = new Gson().toJson(upadteApps);
        OkGo.post(Configure.HTTP_TAG_APPBAOMING)
                .params("baoming", java.net.URLEncoder.encode(update))
                .tag(this)
                .cacheKey(Configure.HTTP_TAG_APPBAOMING + java.net.URLEncoder.encode(update))
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppContentInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppContentInfo>> listLzyResponse, Call call, Response response) {
                        Message msg = new Message();
                        msg.what = Configure.SUCCESS;
                        Bundle bundle = new Bundle();
                        bundle.putString("httpTag", Configure.RANKING_TYPE_UPDATE);
                        msg.obj = listLzyResponse.data;
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mUpdateRadioButton.setText("可更新(0)");
                    }
                });
    }

    private void showContentList(int index) {
        if (index == DOWNLOAD_RADID_BTTON_INDEX) {
            mDownloadListView.setVisibility(View.VISIBLE);
            reLayout1.setVisibility(View.GONE);
            reLayout2.setVisibility(View.GONE);
            reLayout3.setVisibility(View.GONE);

            mDownloadListView.smoothScrollToPosition(0);
            mHandler.sendEmptyMessage(DOWNLOAD_RADID_BTTON_INDEX);
        } else if (index == UNINSTALL_RADID_BTTON_INDEX) {
            mDownloadListView.setVisibility(View.GONE);
            reLayout2.setVisibility(View.GONE);
            reLayout1.setVisibility(View.VISIBLE);
            reLayout3.setVisibility(View.GONE);

            mUninstallListView.smoothScrollToPosition(0);
            mHandler.sendEmptyMessage(UNINSTALL_RADID_BTTON_INDEX);
        } else if (index == UPDATE_RADID_BTTON_INDEX) {
            mDownloadListView.setVisibility(View.GONE);
            reLayout1.setVisibility(View.GONE);
            reLayout2.setVisibility(View.VISIBLE);
            reLayout3.setVisibility(View.GONE);

            mAppupdateListView.smoothScrollToPosition(0);
            mHandler.sendEmptyMessage(UPDATE_RADID_BTTON_INDEX);
        }
//        else if (index == ABOUT_RADID_BTTON_INDEX) {
//            mDownloadListView.setVisibility(View.GONE);
//            reLayout1.setVisibility(View.GONE);
//            reLayout2.setVisibility(View.GONE);
//            reLayout3.setVisibility(View.VISIBLE);
//            mHandler.sendEmptyMessage(ABOUT_RADID_BTTON_INDEX);
//
//        }
    }

    @Override
    public void run() {
        int orientation = getResources().getConfiguration().orientation;

        mDownloadListAdapter = new DownloadListAdapter(this, new DownloadListAdapter.setItemSizeListener() {
            @Override
            public void setItemSize(int size) {
                mDownloadRadioButton.setText("新任务(" + size + ")");
                if (index == DOWNLOAD_RADID_BTTON_INDEX) {
                    mHandler.sendEmptyMessage(DOWNLOAD_RADID_BTTON_INDEX);
                }
            }
        });
        switch (orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                mManager = new RecycleGridLayoutManager(this, 1);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                mManager = new RecycleGridLayoutManager(this, 2);
                break;
        }
        mManager.setOrientation(GridLayoutManager.VERTICAL);
        mManager.setSmoothScrollbarEnabled(true);
        mDownloadListView.setLayoutManager(mManager);
        mDownloadListView.setNestedScrollingEnabled(false);
        mDownloadListView.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x),
                getResources().getDimensionPixelSize(R.dimen.PX10x), getResources().getDimensionPixelSize(R.dimen.PX10x)));
        ((DefaultItemAnimator) mDownloadListView.getItemAnimator()).setSupportsChangeAnimations(false);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mDownloadListView.setAdapter(mDownloadListAdapter);
            }
        });

        mUninstallListAdapter = new UninstallListAdapter(this, new UninstallListAdapter.setItemSizeListener() {
            @Override
            public void setItemSize(int size) {
                mUninstallRadioButton.setText("已安装(" + uninstallAllList.size() + ")");
                if (index == UNINSTALL_RADID_BTTON_INDEX) {
                    mHandler.sendEmptyMessage(UNINSTALL_RADID_BTTON_INDEX);
                }
            }
        });
        switch (orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                mLayoutManager = new RecycleGridLayoutManager(this, 1);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                mLayoutManager = new RecycleGridLayoutManager(this, 3);
                break;
        }
        mLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mLayoutManager.setSmoothScrollbarEnabled(true);
        mUninstallListView.setLayoutManager(mLayoutManager);
        mUninstallListView.setNestedScrollingEnabled(false);
        mUninstallListView.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x),
                getResources().getDimensionPixelSize(R.dimen.PX10x), getResources().getDimensionPixelSize(R.dimen.PX10x)));
        ((DefaultItemAnimator) mUninstallListView.getItemAnimator()).setSupportsChangeAnimations(false);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mUninstallListView.setAdapter(mUninstallListAdapter);
            }
        });

        mUpdateAppListAdapter = new AppUpdateListAdapter(this, new AppUpdateListAdapter.setItemSizeListener() {
            @Override
            public void setItemSize(int size) {
                mUpdateRadioButton.setText("可更新(" + updateAllList.size() + ")");
                if (index == UNINSTALL_RADID_BTTON_INDEX) {
                    mHandler.sendEmptyMessage(UPDATE_RADID_BTTON_INDEX);
                }
            }
        });
        switch (orientation) {
            case Configuration.ORIENTATION_PORTRAIT:
                mGridLayoutManager = new RecycleGridLayoutManager(this, 1);
                break;
            case Configuration.ORIENTATION_LANDSCAPE:
                mGridLayoutManager = new RecycleGridLayoutManager(this, 3);
                break;
        }
        mGridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mGridLayoutManager.setSmoothScrollbarEnabled(true);
        mAppupdateListView.setLayoutManager(mGridLayoutManager);
        mAppupdateListView.setNestedScrollingEnabled(false);
        mAppupdateListView.addItemDecoration(new SpacesItemDecoration(getResources().getDimensionPixelSize(R.dimen.PX5x), getResources().getDimensionPixelSize(R.dimen.PX5x),
                getResources().getDimensionPixelSize(R.dimen.PX10x), getResources().getDimensionPixelSize(R.dimen.PX10x)));
        ((DefaultItemAnimator) mAppupdateListView.getItemAnimator()).setSupportsChangeAnimations(false);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAppupdateListView.setAdapter(mUpdateAppListAdapter);
            }
        });


        mUninstallListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        // 当ListView处于滑动状态时，停止加载图片，保证操作界面流畅
                        Glide.with(DownloadActivity.this).pauseRequests();
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        // 当ListView处于静止状态时，继续加载图片
                        Glide.with(DownloadActivity.this).resumeRequests();
                        break;
                }
            }
        });

        mUninstallListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:
                    case RecyclerView.SCROLL_STATE_SETTLING:
                        // 当ListView处于滑动状态时，停止加载图片，保证操作界面流畅
                        Glide.with(DownloadActivity.this).pauseRequests();
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:
                        // 当ListView处于静止状态时，继续加载图片
                        Glide.with(DownloadActivity.this).resumeRequests();
                        break;
                }
            }
        });

        Intent allIntent = new Intent();
        allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
        sendBroadcast(allIntent);

        uninstallAllList = AppsManagerUtils.getUserApps(this);
        if (uninstallAllList != null && !uninstallAllList.isEmpty()) {

            if (mUninstallListAdapter != null) {
                mUninstallListView.post(new Runnable() {
                    @Override
                    public void run() {
                        mUninstallListAdapter.setDatas(uninstallAllList);
                        mUninstallRadioButton.setText("已安装(" + uninstallAllList.size() + ")");
                    }
                });
            }
        }
        initUpdateAppDatas();
    }

    private void getUpdateAppDatas(String packageName) {
        List<AppUpdateInfo> upadteApps = new ArrayList<>();
        upadteApps.add(AppsManagerUtils.getUpAppsByPackageName(this, packageName));
        String update = new Gson().toJson(upadteApps);
        OkGo.post(Configure.HTTP_TAG_APPBAOMING)
                .params("baoming", java.net.URLEncoder.encode(update))
                .tag(this)
                .cacheKey(Configure.HTTP_TAG_APPBAOMING + java.net.URLEncoder.encode(update))
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppContentInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppContentInfo>> listLzyResponse, Call call, Response response) {
                        List<AppContentInfo> infoList = listLzyResponse.data;
                        if (!infoList.isEmpty() && infoList.get(0) != null) {
                            updateAllList.addAll(infoList);
                            mUpdateAppListAdapter.addDatas(infoList.get(0));
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                    }
                });
    }

    public class DownloadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (Utils.DOWNLOAD_SERVICE_ACTION.equals(intent.getAction())) {
                AppDownloadInfo downloadInfo = (AppDownloadInfo) intent.getSerializableExtra("DownloadInfo");
                if (downloadInfo == null)
                    return;
                if (downloadInfo.getState() == 10) {
                    mDownloadListAdapter.removeItem(downloadInfo);
                    if (updateAllList != null) {
                        Iterator<AppContentInfo> it = updateAllList.iterator();
                        int number = -1;
                        while (it.hasNext()) {
                            number++;
                            AppContentInfo value = it.next();
                            if (downloadInfo.getPackageName().equals(value.getApp_baoming())) {
                                it.remove();
                            }
                        }
                    }
                } else {
                    mDownloadListAdapter.updateProgress(downloadInfo);
                }
                int position = -1;
                for (int i = 0; i < mDownloadListAdapter.allTask.size(); i++) {
                    if (downloadInfo.getUrl().equals(mDownloadListAdapter.allTask.get(i).getUrl())) {
                        position = i;
                    }
                }
                if (position != -1) {
                    mDownloadListAdapter.allTask.set(position, downloadInfo);
                }
                if (position == 0) {
                    mDownloadListAdapter.notifyItemChanged(0);
                }

                mUpdateAppListAdapter.updateProgress(downloadInfo); //更新进度
            } else if (Utils.DOWNLOAD_ALLSERVICE_ACTION.equals(intent.getAction())) {
                List<AppDownloadInfo> list = (List<AppDownloadInfo>) intent.getSerializableExtra("allTask");

                mDownloadListAdapter.setDatas(list);
            } else if (Utils.DOWNLOAD_NEWSERVICE_ACTION.equals(intent.getAction())) {
                AppDownloadInfo downloadInfo = (AppDownloadInfo) intent.getSerializableExtra("addTask");
                mDownloadListAdapter.addDatas(downloadInfo);
            } else if (Utils.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
                String packageName = intent.getStringExtra("packageName");
                Log.e("fht", "安装成功" + packageName);
                mDownloadListAdapter.removeItem(packageName);
                SaveListUtils.getDownLoadList().remove(packageName);//移除下载列表
                LocalAppInfo info = AppsManagerUtils.getAppsByPackageName(DownloadActivity.this, packageName);
                if (uninstallAllList != null) {
                    uninstallAllList.add(info);
                }
                mUninstallListAdapter.addDatas(info);

                getUpdateAppDatas(packageName);
            } else if (Utils.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
                String packageName = intent.getStringExtra("packageName");
                Log.e("aaaaa", "卸载成功" + packageName);
                if (uninstallAllList != null) {
                    Iterator<LocalAppInfo> it = uninstallAllList.iterator();
                    int number = -1;
                    while (it.hasNext()) {
                        number++;
                        LocalAppInfo value = it.next();
                        if (packageName.equals(value.getPackageName())) {
                            it.remove();
                        }
                    }
                }
                mUninstallListAdapter.removeItem(packageName);

                if (updateAllList != null) {
                    Iterator<AppContentInfo> it = updateAllList.iterator();
                    int number = -1;
                    while (it.hasNext()) {
                        number++;
                        AppContentInfo value = it.next();
                        if (packageName.equals(value.getApp_baoming())) {
                            it.remove();
                            mUpdateAppListAdapter.removeUpItem(packageName);
                        }
                    }
                }
            } else if (Utils.ACTION_PACKAGE_REPLACED.equals(intent.getAction())) {
                String packageName = intent.getStringExtra("packageName");
                Log.e("aaaaa", "替换成功" + packageName);
                if (uninstallAllList != null) {
                    int position = -1;
                    for (int i = 0; i < mUninstallListAdapter.mDataList.size(); i++) {
                        if (packageName.equals(mUninstallListAdapter.mDataList.get(i).getPackageName())) {
                            position = i;
                        }
                    }
                    if (position != -1) {
                        LocalAppInfo info = AppsManagerUtils.getAppsByPackageName(DownloadActivity.this, packageName);
                        mUninstallListAdapter.notifyItem(position, info);
                        uninstallAllList.set(position, info);
                    }
                }

                getUpdateAppDatas(packageName);
            }
        }
    }
}
