package com.mjsheng.myappstore.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.res.Configuration;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.arialyy.aria.core.Aria;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.lzy.okserver.download.DownloadManager;
import com.lzy.okserver.download.DownloadService;
import com.mjsheng.myappstore.BuildConfig;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.base.BaseFragmentActivity;
import com.mjsheng.myappstore.base.MyApplication;
import com.mjsheng.myappstore.bean.ForceDownloadBean;
import com.mjsheng.myappstore.bean.ForceDownloadData;
import com.mjsheng.myappstore.bean.NetAndLaunchBean;
import com.mjsheng.myappstore.bean.NetAndLaunchData;
import com.mjsheng.myappstore.bean.UploadAppInfo;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.dialog.ExitDialog;
import com.mjsheng.myappstore.fragment.BrandFragment;
import com.mjsheng.myappstore.fragment.CategoryPageFragment;
import com.mjsheng.myappstore.fragment.HomePageFragment;
import com.mjsheng.myappstore.fragment.ProjectFragment;
import com.mjsheng.myappstore.fragment.RankingPageFragment;
import com.mjsheng.myappstore.network.Network;
import com.mjsheng.myappstore.network.api.AppLimitApi;
import com.mjsheng.myappstore.network.api.DeselectBrowserIDApi;
import com.mjsheng.myappstore.network.api.DeselectIDApi;
import com.mjsheng.myappstore.network.api.ForceDownloadApi;
import com.mjsheng.myappstore.network.api.NetAndLaunchApi;
import com.mjsheng.myappstore.network.api.SystemSettingApi;
import com.mjsheng.myappstore.network.api.UpdateApi;
import com.mjsheng.myappstore.network.api.UploadAppInfoApi;
import com.mjsheng.myappstore.utils.ApkUtils;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.utils.update.AllDialogShowStrategy;
import com.mjsheng.myappstore.utils.update.NotificationDownloadCreator;
import com.mjsheng.myappstore.utils.update.OkhttpCheckWorker;
import com.mjsheng.myappstore.utils.update.ToastCallback;
import com.mjsheng.myappstore.widget.Sound;
import com.tianma.netdetector.lib.NetworkType;

import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateBuilder;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.functions.Action1;


public class AppStoreActivity extends BaseFragmentActivity implements OnClickListener,
        OnCheckedChangeListener {

    private Fragment[] mFragments;
    private FragmentManager mFragmentManager;
    private ImageView mBackIv;
    private LinearLayout mAgeLl, mSearchLl;
    private RelativeLayout mHomeLl, mCategoryLl, mRatingLl, mSpecialLl, mBrandLl, mDownloadLl;
    private RelativeLayout mSelect = null;
    private String ageSystem;
    private Sound sound;
    private ExitDialog exitDialog = null;
    private View mHome_page_line, mCategory_line, mRating_line, mSpecial_line, mBrand_line;
    private View mSelectView;
    private TextView mHome_page_tv, mCategory_tv, mRating_tv, mSpecial_tv, mBrand_tv;
    private TextView mSelectTv;
    private ToastCallback callback;
    private Bundle savedInstanceState;
    private int fragmentTag = 0;
    private long mPreClickTime;
    private Context mContext;
    private ImageView mHome_page_iv_recommend;
    private ImageView mHome_page_iv_category;
    private ImageView mHome_page_iv_rating;
    private ImageView mHome_page_iv_brand;
    private ImageView mHome_page_iv_special;
    private ImageView mHome_page_iv_download;
    private final String ACTION_HrReceiver_JGY_DIS = "qch_jgy_network_disallow";
    private final String ACTION_HrReceiver_JGY = "qch_jgy_network_allow";
    private int[] normal_icon = {R.drawable.top_recommend_normal, R.drawable.top_category_normal, R.drawable.top_rating_normal, R.drawable.top_brand_normal, R.drawable.top_special_normal};
    private int[] press_icon = {R.drawable.top_recommend_press, R.drawable.top_category_press, R.drawable.top_rating_press, R.drawable.top_brand_press, R.drawable.top_special_press};
    private List<ImageView> mTopList;
    private DownloadManager downloadManager;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setContentView(R.layout.activity_appstore);
        mContext = this;
        initView(savedInstanceState, fragmentTag);
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        //        super.onSaveInstanceState(outState, outPersistentState);
    }

    private LocationReceiver mLocationReceiver;

    private class LocationReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //                ToastTool.show("广播：：："+intent.getAction() + "--------" + intent.getStringExtra("package_name"));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            // FRAGMENTS_TAG
            savedInstanceState.remove("android:support:fragments");
            savedInstanceState.remove("android:fragments");
        }
        Aria.get(this).getDownloadConfig().setMaxTaskNum(1);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_appstore);
        Aria.download(this).removeAllTask(false);
        //        Aria.download(this).register();
//        IntentFilter intentFilter = new IntentFilter();
//        intentFilter.addAction("qch_jgy_network_disallow");
//        intentFilter.addAction("qch_jgy_network_allow");
        //        intentFilter.addAction("qch_hide_statusBar");
        //        intentFilter.addAction("qch_show_NavigationBar");
        //        intentFilter.addAction("qch_hide_NavigationBar");
        //        intentFilter.addAction("qch_action_usb_usb_midi");
        //        intentFilter.addAction("qch_action_usb_usb_mtp");
        //        intentFilter.addAction("qch_action_usb_usb_charge");
//        intentFilter.addAction("qch_camera_open");
//        intentFilter.addAction("qch_camera_forbid");
        mLocationReceiver = new LocationReceiver();
        //        registerReceiver(mLocationReceiver, intentFilter);

        this.savedInstanceState = savedInstanceState;
        MyApplication.addActivity(this);
        MyApplication.mainActivity = this;


        ageSystem = getIntent().getStringExtra("ageSystem");

        sound = new Sound(this);
        callback = new ToastCallback(this);
        initView(savedInstanceState, fragmentTag);
        initData();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                MyApplication.getInstance().updateTask();
//                Log.e("fht", "AppStoreActivity updateTask");
//
//            }
//        }).run();
        Log.e("fht", "AppStoreActivity onCreate");
        downloadManager = DownloadService.getDownloadManager();
        downloadManager.startAllTask();
        Intent allIntent = new Intent();
        allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
        sendBroadcast(allIntent);
    }

    private void initView(Bundle savedInstanceState, int fragmentTag) {

        setChangeBySystem();
        if (savedInstanceState == null) {
            mFragments = new Fragment[5];
            mFragmentManager = getSupportFragmentManager();
        }
        //        initManagePageFragment();
        mBackIv = (ImageView) findViewById(R.id.back_iv);
        mAgeLl = (LinearLayout) findViewById(R.id.age_selected_ll);
        mDownloadLl = (RelativeLayout) findViewById(R.id.download_ll);
        mSearchLl = (LinearLayout) findViewById(R.
                id.search_ll);
        mHomeLl = (RelativeLayout) findViewById(R.id.home_page_ll);
        mCategoryLl = (RelativeLayout) findViewById(R.id.category_ll);
        mRatingLl = (RelativeLayout) findViewById(R.id.rating_ll);
        mSpecialLl = (RelativeLayout) findViewById(R.id.special_ll);
        mBrandLl = (RelativeLayout) findViewById(R.id.brand_ll);

        mHome_page_line = (View) findViewById(R.id.home_page_line);
        mCategory_line = (View) findViewById(R.id.category_line);
        mRating_line = (View) findViewById(R.id.rating_line);
        mSpecial_line = (View) findViewById(R.id.special_line);
        mBrand_line = (View) findViewById(R.id.brand_line);

        mHome_page_tv = (TextView) findViewById(R.id.home_page_tv);
        mCategory_tv = (TextView) findViewById(R.id.category_tv);
        mRating_tv = (TextView) findViewById(R.id.rating_tv);
        mSpecial_tv = (TextView) findViewById(R.id.special_tv);
        mBrand_tv = (TextView) findViewById(R.id.brand_tv);

        mTopList = new ArrayList<>();
        mHome_page_iv_recommend = (ImageView) findViewById(R.id.home_page_iv_recommend);
        mHome_page_iv_category = (ImageView) findViewById(R.id.home_page_iv_category);
        mHome_page_iv_rating = (ImageView) findViewById(R.id.home_page_iv_rating);
        mHome_page_iv_brand = (ImageView) findViewById(R.id.home_page_iv_brand);
        mHome_page_iv_special = (ImageView) findViewById(R.id.home_page_iv_special);
        mTopList.add(mHome_page_iv_recommend);
        mTopList.add(mHome_page_iv_category);
        mTopList.add(mHome_page_iv_rating);
        mTopList.add(mHome_page_iv_brand);
        mTopList.add(mHome_page_iv_special);

        mSelect = mCategoryLl;
        mSelectView = mCategory_line;
        mSelectTv = mCategory_tv;

        mBackIv.setOnClickListener(this);
        mAgeLl.setOnClickListener(this);
        mDownloadLl.setOnClickListener(this);
        mSearchLl.setOnClickListener(this);
        mHomeLl.setOnClickListener(this);
        mCategoryLl.setOnClickListener(this);
        mRatingLl.setOnClickListener(this);
        mSpecialLl.setOnClickListener(this);
        mBrandLl.setOnClickListener(this);


        Log.e("mjsehng", "fragmentTag====" + fragmentTag);
        switch (fragmentTag) {
            case 0:
                mHomeLl.performClick();
                break;
            case 1:
                mCategoryLl.performClick();
                break;
            case 2:
                mRatingLl.performClick();
                break;
            case 3:
                mSpecialLl.performClick();
                break;
            case 4:
                mBrandLl.performClick();
                break;
        }

    }

    private void initData() {
        Log.e("mjhsneg", "gagagag--------------------------" + Utils.getSerial());
        getLockedState();
        initJpush();//初始化极光推送
        update();//接口更新app
        sendMACaddress();
        Log.e("mac", com.blankj.utilcode.util.DeviceUtils.getMacAddress());
    }

    synchronized public void sendMACaddress() {
        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        OkGo.post(Configure.SEND_DEVICES)
                .params("sn", Utils.getSerial())
                .params("mac", com.blankj.utilcode.util.DeviceUtils.getMacAddress())
                .params("jpush_id", rid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        com.alibaba.fastjson.JSONObject msgObject = JSON.parseObject(s);
                        int code = msgObject.getInteger("code");
                        Log.e("sendMACaddress", msgObject.getString("msg"));
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        Log.e("sendMACaddress", e.getMessage());

                    }
                });
        {

        }
    }

    private boolean locked = false;

    public void getLockedState() {
        OkGo.post(Configure.HTTP_TAG_FIRST)
                .params("sn", Utils.getSerial())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e("onSuccess", s);
                        Log.e("getSerial", Utils.getSerial());
                        com.alibaba.fastjson.JSONObject msgObject = JSON.parseObject(s);
                        Log.e("getForceDownload", s);
                        Integer code = (msgObject.getInteger("code"));
                        if (code == 200) {
                            com.alibaba.fastjson.JSONObject dataArray = msgObject.getJSONObject("data");
                            int lock = dataArray.getInteger("lock");
                            Log.e("ttlocked", String.valueOf(lock));
                            if (lock == 0) {
                                locked = false;
                                boolean se = Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_unlock_ipad", 1);
                                Log.e("ttlocked1", "getLockedState---------" + Settings.System.getString(getApplicationContext().getContentResolver(), "qch_unlock_ipad"));
                                Log.e("ttlocked1", "qch_unlock_ipad---------" + locked + se);
                            } else {
                                locked = true;
                                Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_unlock_ipad", 0);
                                Log.e("ttlocked2", "qch_unlock_ipad---------" + locked);
                                String ss = Settings.System.getString(getApplicationContext().getContentResolver(), "DeselectBrowserArray");
                                Log.e("ttlocked2", "DeselectBrowserArray---------" + ss);
                                lazyLoading();
                            }
                        }
                    }

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

                });// 请求方式和请求url
    }

    private void lazyLoading() {
        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        getDeselectBrowerID();//浏览器网址管控
                        getDeselectID();//ID管控
                        getAppLimitApi();//写入可被安装的包名
                        getAppInfo();//上传APP信息
                        getSystemSetting();//设置系统管控
                        getNetAndLaunchSetting();//联网管控
                        Aria.download(this).resumeAllTask();
                        getForceDownload();//强制下载apk
                        resetDevice();//恢复出厂设置
                        //                        fromNetToUpdate();
                        String registrationID = JPushInterface.getRegistrationID(AppStoreActivity.this);
                        Log.e("mjsheng", registrationID + "------------------------");
//                        ToastUtils.showLong("registrationID::" + registrationID);
                        //                        Log.e("mjsheng", "getAndroidID" + "------------------------" + DeviceUtils.getAndroidID());
                        //                        Log.e("mjsheng", "getMacAddress" + "------------------------" + DeviceUtils.getMacAddress());
                        //                        Log.e("mjsheng", "getSerial" + "------------------------" + PhoneUtils.getSerial());
                        //                        Log.e("mjsheng", "getIMEI" + "------------------------" + PhoneUtils.getIMEI());
                        //                        Log.e("mjsheng", "getMEID" + "------------------------" + PhoneUtils.getMEID());
                        //                        Log.e("mjsheng", "getIMSI" + "------------------------" + PhoneUtils.getIMSI());
                        List<String> list = SaveListUtils.getList();
                        if (list == null) {
                            return;
                        }
                        LogUtils.e(list.toString() + "-----------------------------");
                    }
                });
    }

    private void resetDevice() {
        boolean isReset = MySQLData.GetBooleanData(this, CommonDatas.IS_RESET);
        int batteryLevel = getBatteryLevel();
        LogUtils.e(batteryLevel + "------------------" + isReset);
        if (isReset && batteryLevel >= CommonDatas.MIN_POWER) {
            sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));
        }
    }

    private int getBatteryLevel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(getApplicationContext()).
                    registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            return (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
                    intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }
    }


    @Override
    protected void onStop() {

        super.onStop();
    }

    public void setChangeBySystem() {
        if (ageSystem.equals("3")) {
            MyApplication.ageType = 1;
        } else if (ageSystem.equals("6")) {
            MyApplication.ageType = 2;
        } else if (ageSystem.equals("10")) {
            MyApplication.ageType = 3;
        } else {
            MyApplication.ageType = 1;
        }
    }

    /**
     * 预加载管理界面，以防这是点击下载，任务未能显示出来
     */
    private void initManagePageFragment() {
        if (mFragmentManager != null && mFragments != null) {
            FragmentTransaction transaction = mFragmentManager
                    .beginTransaction();
            transaction.commit();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        Intent allIntent = new Intent();
        allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
        sendBroadcast(allIntent);
    }

    // 切换显示内容
    public void switchContent(int index) {
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        hideFragments(transaction);
        try {
            switch (index) {
                case 0:
                    if (mFragments[0] == null) {
                        // 首页 推荐页面
                        mFragments[0] = new HomePageFragment();

                        Bundle bundle = new Bundle();
                        bundle.putString("ageSystem", ageSystem);
                        mFragments[0].setArguments(bundle);
                        transaction.add(R.id.content,
                                mFragments[0], 0 + "");
                    } else {
                        transaction.show(mFragments[0]);
                        Intent allIntent = new Intent();
                        allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
                        sendBroadcast(allIntent);
                    }
                    break;
                case 1:
                    if (mFragments[1] == null) {
                        // 分类
                        mFragments[1] = new CategoryPageFragment();
                        transaction.add(R.id.content, mFragments[1], 1 + "");
                    } else {

                        transaction.show(mFragments[1]);
                        Intent allIntent = new Intent();
                        allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
                        sendBroadcast(allIntent);
                    }
                    break;
                case 2:
                    if (mFragments[2] == null) {
                        // 排行   3个RadioButton
                        mFragments[2] = new RankingPageFragment();
                        transaction.add(R.id.content,
                                mFragments[2], 2 + "");
                    } else {
                        transaction.show(mFragments[2]);
                        Intent allIntent = new Intent();
                        allIntent.setAction(Utils.DOWNLOAD_ALLTASK_ACTION);
                        sendBroadcast(allIntent);
                    }
                    break;
                case 3:
                    if (mFragments[3] == null) {
                        // 专题
                        mFragments[3] = new ProjectFragment();
                        transaction.add(R.id.content,
                                mFragments[3], 3 + "");
                    } else {
                        transaction.show(mFragments[3]);
                    }
                    break;
                case 4:
                    if (mFragments[4] == null) {
                        // 品牌
                        mFragments[4] = new BrandFragment();
                        transaction.add(R.id.content,
                                mFragments[4], 4 + "");
                    } else {
                        transaction.show(mFragments[4]);
                    }
                    break;
            }
            transaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 将所有的Fragment都置为隐藏状态。
    private void hideFragments(FragmentTransaction transaction) {
        if (mFragments != null) {
            for (int i = 0; i < mFragments.length; i++) {
                if (mFragments[i] != null) {
                    transaction.hide(mFragments[i]);
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        sound.playSoundEffect();
        switch (v.getId()) {
            case R.id.back_iv:
                lazyExit();
                //                if (exitDialog == null) {
                //                    exitDialog = new ExitDialog(this, new ExitDialog.PriorityListener() {
                //                        @Override
                //                        public void refreshPriorityUI(String string) {
                //                            if (string.equals("YES")) {
                //                                finish();
                //                            }
                //                        }
                //                    });
                //                    exitDialog.show();
                //                } else {
                //                    exitDialog.show();
                //                }
                break;
            // 搜索应用界面
            case R.id.search_ll:
                Intent intent = new Intent();
                intent.setClass(this, SearchActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                break;
            // 下载界面
            case R.id.download_ll:
                Intent download = new Intent();
                download.setClass(this, DownloadActivity.class);
                download.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(download);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                break;
            // 设置界面
            case R.id.age_selected_ll:
                Intent setting = new Intent();
                setting.setClass(this, SettingActivity.class);
                setting.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(setting);
                overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                break;
            case R.id.home_page_ll:
                fragmentTag = 0;
                switchContent(0);
                changeIcon(0);
                //                mHomeLl.setBackgroundResource(R.drawable.appstoreactivity_itembg);
                //                mHome_page_line.setVisibility(View.VISIBLE);
                mHome_page_tv.setTextColor(getResources().getColor(R.color.appstore_selecte_color));

                if (mSelect != mHomeLl) {
                    mSelect.setBackgroundResource(0);
                    mSelect = mHomeLl;
                    //                    mSelectView.setVisibility(View.GONE);
                    mSelectView = mHome_page_line;

                    mSelectTv.setTextColor(getResources().getColor(R.color.textColor));
                    mSelectTv = mHome_page_tv;
                }
                break;
            case R.id.category_ll:
                fragmentTag = 1;
                switchContent(1);
                changeIcon(1);
                //                mCategoryLl.setBackgroundResource(R.drawable.appstoreactivity_itembg);
                //                mCategory_line.setVisibility(View.VISIBLE);
                mCategory_tv.setTextColor(getResources().getColor(R.color.appstore_selecte_color));
                mCategory_tv.setTextColor(getResources().getColor(R.color.appstore_selecte_color));

                if (mSelect != mCategoryLl) {
                    mSelect.setBackgroundResource(0);
                    mSelect = mCategoryLl;

                    //                    mSelectView.setVisibility(View.GONE);
                    mSelectView = mCategory_line;

                    mSelectTv.setTextColor(getResources().getColor(R.color.textColor));
                    mSelectTv = mCategory_tv;
                }
                break;
            case R.id.rating_ll:
                fragmentTag = 2;
                switchContent(2);
                changeIcon(2);
                //                mRatingLl.setBackgroundResource(R.drawable.appstoreactivity_itembg);
                //                mRating_line.setVisibility(View.VISIBLE);
                mRating_tv.setTextColor(getResources().getColor(R.color.appstore_selecte_color));

                if (mSelect != mRatingLl) {
                    mSelect.setBackgroundResource(0);
                    mSelect = mRatingLl;

                    mSelectView.setVisibility(View.GONE);
                    mSelectView = mRating_line;

                    mSelectTv.setTextColor(getResources().getColor(R.color.textColor));
                    mSelectTv = mRating_tv;
                }
                break;
            case R.id.special_ll:
                fragmentTag = 3;
                switchContent(3);
                changeIcon(4);
                //                mSpecialLl.setBackgroundResource(R.drawable.appstoreactivity_itembg);
                //                mSpecial_line.setVisibility(View.VISIBLE);
                mSpecial_tv.setTextColor(getResources().getColor(R.color.appstore_selecte_color));

                if (mSelect != mSpecialLl) {
                    mSelect.setBackgroundResource(0);
                    mSelect = mSpecialLl;

                    mSelectView.setVisibility(View.GONE);
                    mSelectView = mSpecial_line;

                    mSelectTv.setTextColor(getResources().getColor(R.color.textColor));
                    mSelectTv = mSpecial_tv;
                }
                break;
            case R.id.brand_ll:
                fragmentTag = 4;
                switchContent(4);
                changeIcon(3);
                //                mBrandLl.setBackgroundResource(R.drawable.appstoreactivity_itembg);
                //                mBrand_line.setVisibility(View.VISIBLE);
                mBrand_tv.setTextColor(getResources().getColor(R.color.appstore_selecte_color));

                if (mSelect != mBrandLl) {
                    mSelect.setBackgroundResource(0);
                    mSelect = mBrandLl;

                    mSelectView.setVisibility(View.GONE);
                    mSelectView = mBrand_line;

                    mSelectTv.setTextColor(getResources().getColor(R.color.textColor));
                    mSelectTv = mBrand_tv;
                }
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        sound.playSoundEffect();

    }


    //    public boolean onKeyDown(int keyCode, KeyEvent event) {
    //        if (keyCode == KeyEvent.KEYCODE_BACK) {
    //            if (exitDialog == null) {
    //                exitDialog = new ExitDialog(AppStoreActivity.this, new ExitDialog.PriorityListener() {
    //                    @Override
    //                    public void refreshPriorityUI(String string) {
    //                        if (string.equals("YES")) {
    //                            finish();
    //                            //                            moveTaskToBack(false);
    //                        }
    //                    }
    //                });
    //                exitDialog.show();
    //            } else {
    //                exitDialog.show();
    //            }
    //            return true;
    //        }
    //        return super.onKeyDown(keyCode, event);
    //    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }

    private void getAppInfo() {
        ArrayList<UploadAppInfo> appList = new ArrayList<>(); //用来存储获取的应用信息数据
        List<PackageInfo> packages = getPackageManager().getInstalledPackages(0);

        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            UploadAppInfo uploadAppInfo = new UploadAppInfo();
            uploadAppInfo.setApp_name(packageInfo.applicationInfo.loadLabel(getPackageManager()).toString());
            uploadAppInfo.setPackage_name(packageInfo.packageName);
            uploadAppInfo.setId(i);
            String firstInstallTime = Utils.transferLongToDate(packageInfo.firstInstallTime);
            uploadAppInfo.setInstall_time(firstInstallTime);

            //            Log.e("mjsheng", "------------------" + uploadAppInfo);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                //非系统应用
                appList.add(uploadAppInfo);
            } else {

            }


        }

        //        Log.e("mjsheng", "UploadAppInfo========" + appList.toString());

        Gson gson = new Gson();
        String jsonString = gson.toJson(appList);
        Log.e("mjsheng", "json========" + jsonString);

        UploadAppInfoApi uploadAppInfoApi = Network.getUploadAppInfoApi();
        uploadAppInfoApi.getUploadAppInfoApi(Configure.HTTP_KEY, Utils.getSerial(), jsonString)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Log.e("mjhseng", "上传的结果" + responseBody.string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "UploadAppInfoApi=onError:");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initJpush() {

        JPushInterface.setAlias(this, Utils.getSerial(), new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {
                if (set == null) {
                    Log.e("mjhseng", "set is null");
                } else {
                    Log.e("mjhseng", "set ---" + set.toString());
                }
                Log.e("JPushInterface", s + "---" + i + "---");
                if (i == 0) {
                    Log.e("JPushInterface", "JPush绑定成功");
                } else if (i == 6001) {
                    Log.e("JPushInterface", "无效的设置,用户名为空");
                } else if (i == 6002) {
                    Log.e("JPushInterface", "设置超时，请重试");
                    timerImitate();
                } else if (i == 6011) {
                    Log.e("JPushInterface", "短时间内操作过于频繁");
                } else if (i == 996) {
                    Log.e("JPushInterface", "网络连接断开");
                }
            }
        });

    }

    //重新设置jpush
    private void timerImitate() {
        Observable.timer(10000, TimeUnit.MILLISECONDS)
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        Log.e("JPushInterface", "JPushInterface重新加载");
                        initJpush();
                    }
                });
    }

    private void update() {
        UpdateBuilder updateBuilder = UpdateBuilder.create();
        // 配置toast通知的回调
        updateBuilder.setDownloadCallback(callback);
        //                updateBuilder.setCheckCallback(callback);
        updateBuilder.setDownloadNotifier(new NotificationDownloadCreator());
        updateBuilder.setUpdateStrategy(new AllDialogShowStrategy());
        updateBuilder.setCheckWorker(OkhttpCheckWorker.class);
        updateBuilder.check();
    }

    @Override
    public void onBackPressed() {
        lazyExit();

        super.onBackPressed();
    }

    private void lazyExit() {
        if (System.currentTimeMillis() - mPreClickTime > 1000) {
            ToastUtils.showShort("再按一次，退出");
            mPreClickTime = System.currentTimeMillis();
            return;
        } else {
            finish();
        }
    }

    private void getAppLimitApi() {
        AppLimitApi appLimitApi = Network.getAppLimitApi();
        appLimitApi.getAppLimitApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String responString = responseBody.string();
                            Log.e("mjhseng", responString);
                            JSONObject jsonObject = new JSONObject(responString);
                            Integer code = jsonObject.optInt("code");
                            switch (code) {
                                case 200:
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String result = data.optString("result");
                                    writeAppPackageList(result);
                                    break;
                                default:
                                    Log.e("mjhseng", "getAppLimitApi---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("mjhseng", "getAppLimitApi---woring----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "getAppLimitApi=onError:");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void writeAppPackageList(String result) {
        if (!TextUtils.isEmpty(result)) {
            LogUtils.e(result);
            Settings.System.putString(getContentResolver(), "qch_app_forbid", result);
        } else {
            Log.e("mjsheng", "writeAppPackageList is null:");

        }
    }

    private void getDeselectID() {
        DeselectIDApi deselectIDApi = Network.getDeselectIDApi();
        deselectIDApi.getDeselectIDApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String responString = responseBody.string();
                            LogUtils.e("mjhseng", "应用联网管控：：" + responString);
                            JSONObject jsonObject = new JSONObject(responString);
                            Integer code = jsonObject.optInt("code");
                            switch (code) {
                                case 200:
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String ids = data.optString("ids");
                                    writeDeselectIDtoSystem(ids);
                                    break;
                                default:
                                    Log.e("mjhseng", "getDeselectID---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("mjhseng", "getDeselectID---woring----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "DeselectIDApi=onError:");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void fromNetToUpdate() {
        UpdateApi updateApi = Network.getUpdateApi();
        updateApi.getUpdateApi(BuildConfig.APPLICATION_ID, Configure.HTTP_KEY)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        //                        autoUpdate(responseBody);
                    }


                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "UpdateApi=onError:");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void autoUpdate(ResponseBody responseBody) {
        try {
            String responString = responseBody.string();
            JSONObject object = new JSONObject(responString);
            Integer code = object.optInt("code");
            if (code == 200) {
                JSONObject jsonObject = object.getJSONObject("data");
                String url = jsonObject.optString("url");
                int version_code = jsonObject.optInt("version_code");
                LogUtils.e(url + "-----------" + version_code + "---------" + AppUtils.getAppVersionCode());

                if (version_code > AppUtils.getAppVersionCode()) {
                    Aria.download(this)
                            .load(url)     //读取下载地址
                            .setDownloadPath(PathUtils.getExternalDownloadsPath() + "/ygj/" + EncryptUtils.encryptMD5ToString(url) + ".apk")
                            .setExtendField(BuildConfig.APPLICATION_ID)
                            .start();   //启动下载}}
                }
            }
        } catch (Exception e) {
            Log.e("mjhseng", "UpdateApi---woring----" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void getDeselectBrowerID() {
        DeselectBrowserIDApi deselectBrowserIDApi = Network.getDeselectBrowserIDApi();
        deselectBrowserIDApi.getDeselectBrowserIDApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("mjhseng", "getDeselectBrowerID---onSubscribe");

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String responString = responseBody.string();
                            LogUtils.e("mjhseng", "浏览器ID管控::" + responString);
                            JSONObject jsonObject = new JSONObject(responString);
                            Integer code = jsonObject.optInt("code");
                            switch (code) {
                                case 200:
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    String ids = data.optString("ids");
                                    writeDeselectBrowserIDtoSystem(ids);
                                    break;
                                default:
                                    Log.e("mjhseng", "getDeselectBrowerID---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("mjhseng", "getDeselectBrowerID---wroing----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "getDeselectBrowerID=onError:");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("mjhseng", "getDeselectBrowerID---onComplete");
                    }
                });
    }

    private void getNetAndLaunchSetting() {
        NetAndLaunchApi netAndLaunchApi = Network.getNetAndLaunchApi();
        netAndLaunchApi.getNetAndLaunchApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NetAndLaunchBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("mjhseng", "getNetAndLaunchSetting---onSubscribe");

                    }

                    @Override
                    public void onNext(NetAndLaunchBean netAndLaunchBean) {
                        switch (netAndLaunchBean.getCode()) {
                            case 200:
                                setNetAndlaunch(netAndLaunchBean);
                                break;
                            default:
                                ToastUtils.showShort(netAndLaunchBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "getNetAndLaunchSetting=onError:");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("mjhseng", "getNetAndLaunchSetting---onComplete");
                    }
                });
    }

    private void getForceDownload() {
        ForceDownloadApi forceDownloadApi = Network.getForceDownloadApi();
        forceDownloadApi.getForceDownloadApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ForceDownloadBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("mjhseng", "forceDownloadApi---onSubscribe");

                    }

                    @Override
                    public void onNext(ForceDownloadBean forceDownloadBean) {
                        switch (forceDownloadBean.getCode()) {
                            case 200:
                                forceDownload(forceDownloadBean.getData());
                                break;
                            default:
                                LogUtils.e("getForceDownload is error:" + forceDownloadBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "forceDownloadApi=onError:");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("mjhseng", "forceDownloadApi---onComplete");
                    }
                });
    }

    //    private void forceDownload(List<ForceDownloadData> data) {
//        if (data == null || data.size() <= 0) {
//            return;
//        }
//        for(int i=0;i<data.size();i++) {
//            ForceDownloadData forceDownloadData = data.get(i);
//            String app_package = forceDownloadData.getApp_package();
//            String app_url = forceDownloadData.getApp_url();
//            if (!AppUtils.isAppInstalled(app_package)) {
//                Aria.download(this)
//                        .load(app_url)     //读取下载地址
//                        .setDownloadPath(PathUtils.getExternalDownloadsPath() + "/ygj/" + EncryptUtils.encryptMD5ToString(app_package) + ".apk")
//                        .setExtendField(app_package)
//                        .start();   //启动下载}
//            }
//        }
//    }
    private void forceDownload(List<ForceDownloadData> data) {
        if (data == null || data.size() <= 0) {
            return;
        }
        getSelfDownload(data);
        List<String> list = SaveListUtils.getList();

        for (int i = 0; i < data.size(); i++) {
            ForceDownloadData forceDownloadData = data.get(i);
            String app_package = forceDownloadData.getApp_package();
            String app_url = forceDownloadData.getApp_url();
            if (data.get(i).getApp_package().equals("com.mjsheng.myappstore")) {
                continue;//为自身的跳过下载
            }
            LogUtils.e(list);
            if (list != null) {
                if (!list.contains(app_package)) {
                    SaveListUtils.addToList(app_package);
                }
            } else {
                SaveListUtils.addToList(app_package);
            }
            if (!AppUtils.isAppInstalled(app_package)) {
                if (!SaveListUtils.isDownLoading(app_package)) {
                    Aria.download(this)
                            .load(app_url)     //读取下载地址
                            .setDownloadPath(PathUtils.getExternalDownloadsPath() + "/ygj/" + EncryptUtils.encryptMD5ToString(app_package) + ".apk")
                            .setExtendField(app_package)
                            .start();   //启动下载}
                    SaveListUtils.addDownLoadList(app_package);
                }
            }
        }
    }

    private void getSelfDownload(List<ForceDownloadData> forceDownloadDataList) {
        for (ForceDownloadData forceDownloadData : forceDownloadDataList) {
            if ("com.jiaoguanyi.appstore".equals(forceDownloadData.getApp_package())) {
                Aria.download(this)
                        .load(forceDownloadData.getApp_url())     //读取下载地址
                        .setDownloadPath(PathUtils.getExternalDownloadsPath() + "/ygj/" + EncryptUtils.encryptMD5ToString("com.mjsheng.myappstore") + ".apk")
                        .setExtendField("com.mjsheng.myappstore")
                        .start();   //启动下载}


            } else {
//                Log.e("fht", "未上传应用");
            }
        }
    }

    private void setNetAndlaunch(NetAndLaunchBean netAndLaunchBean) {
        LogUtils.e("联网和自启管控：" + netAndLaunchBean.toString());
        String net_ok = "";
        String net_not = "";
        String launch = "";
        List<NetAndLaunchData> data = netAndLaunchBean.getData();
        for (int i = 0; i < data.size(); i++) {
            NetAndLaunchData netAndLaunchData = data.get(i);
            String app_package = netAndLaunchData.getApp_package();
            int is_auto = netAndLaunchData.getIs_auto();
            int is_network = netAndLaunchData.getIs_network();

            if (is_auto == 1) {
                launch += app_package + ",";
            }
            if (is_network == 1) {
                net_ok += app_package + ",";
            } else {
                net_not += app_package + ",";
            }

        }


        if (!TextUtils.isEmpty(launch)) {
            launch = launch.substring(0, launch.length() - 1);
        }
        if (!TextUtils.isEmpty(net_ok)) {
            net_ok = net_ok.substring(0, net_ok.length() - 1);
        }
        if (!TextUtils.isEmpty(net_not)) {
            net_not = net_not.substring(0, net_not.length() - 1);
        }

        LogUtils.e("launch:" + launch + "-----------net_ok:" + net_ok + "-----------net_not:" + net_not);
        boolean qch_app_power_on = Settings.System.putString(getContentResolver(), "qch_app_power_on", launch);
        if (!net_not.equals("")) {
            String[] bans = net_not.split(",");
            Settings.System.putString(getContentResolver(), "qch_jgy_network_disallow", net_not);
            Log.e("fht", "ban::" + net_not);

        }

        if (!net_ok.equals("")) {
            String[] nots = net_ok.split(",");
            Log.e("fht", "not::" + net_ok);
//            new  BroadcastThread("qch_jgy_network_allow",nots).start();
        }
    }

    private class BroadcastThread extends Thread {
        String packagename[];
        String action;

        public BroadcastThread(String a, String s[]) {
            super();
            this.packagename = s;
            this.action = a;
        }

        @Override
        public void run() {
            super.run();
            for (String name : packagename) {
                Intent disIntent = new Intent(action);
                disIntent.putExtra("package_name", name);
                Log.e("mymjsheng", "package_name::" + name);
                sendBroadcast(disIntent);
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void writeDeselectBrowserIDtoSystem(String ids) {
        if (!TextUtils.isEmpty(ids)) {
            boolean deselectBrowserArray = Settings.System.putString(getContentResolver(), "DeselectBrowserArray", ids);
            Log.e("SystemSetting", "DeselectBrowserArray---------" + deselectBrowserArray);


        } else {
            Log.e("mjsheng", "writeDeselectBrowserIDtoSystem is null:");

        }
    }

    private void writeDeselectIDtoSystem(String ids) {
        if (!TextUtils.isEmpty(ids)) {
            boolean deselectViewArray = Settings.System.putString(getContentResolver(), "DeselectViewArray", ids);
            Log.e("SystemSetting", "deselectViewArray---------" + deselectViewArray);
        } else {
            Log.e("mjsheng", "writeDeselectIDtoSystem is null:");
        }
    }

    private void getSystemSetting() {
        final SystemSettingApi systemSettingApi = Network.getSystemSettingApi();
        systemSettingApi.getSystemSettingApi(Configure.HTTP_KEY, Utils.getSerial())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            //                            Log.e("mjsheng", "systemSettingBean::" + systemSettingBean);
                            String responString = responseBody.string();
                            LogUtils.e("mjsheng", "系统管控::" + responString);
                            JSONObject jsonObject = new JSONObject(responString);
                            Integer code = jsonObject.optInt("code");
                            switch (code) {
                                case 200:
                                    JSONObject data = jsonObject.getJSONObject("data");
                                    SettingSysData(data);
                                    break;
                                default:
                                    Log.e("mjhseng", "getSystemSetting---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("mjhseng", "getSystemSetting---wroing----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("mjsheng", "getSystemSetting=onError:");
                    }

                    @Override
                    public void onComplete() {
                        Log.e("mjhseng", "getSystemSetting---onComplete");
                    }
                });
    }

    private void SettingSysData(JSONObject data) {
        try {
            int setting_call = changeNum(data.optInt("setting_call"));
            boolean qch_call_forbid = Settings.System.putInt(getContentResolver(), "qch_call_forbid", setting_call);
            Log.e("SystemSetting", "qch_call_forbid---------" + qch_call_forbid);

            int setting_phone = changeNum(data.optInt("setting_phone"));
            boolean qch_white_list_on = Settings.System.putInt(getContentResolver(), "qch_white_list_on", setting_phone);
            Log.e("SystemSetting", "qch_white_list_on---------" + qch_white_list_on);

            String setting_phones = data.optString("setting_phones");
            boolean qch_white_list_Array = Settings.System.putString(getContentResolver(), "qch_white_list_Array", setting_phones);
            //            ToastTool.show("qch_call_forbid::"+setting_call+"----setting_phones::"+setting_phones+"----"+qch_white_list_Array+"---"+qch_call_forbid);
            Log.e("SystemSetting", "qch_white_list_Array---------" + qch_white_list_Array + "---" + setting_phones);

            int setting_memory = changeNum(data.optInt("setting_memory"));
            boolean qch_sdcard_forbid_on = Settings.System.putInt(getContentResolver(), "qch_sdcard_forbid_on", setting_memory);
            Log.e("SystemSetting", "qch_sdcard_forbid_on---------" + qch_sdcard_forbid_on);


            //USB数据功能管控
            //仅充电：usb_charge
            //MTP模式：usb_mtp
            //Midi模式：usb_midi
            String setting_usb = data.optString("setting_usb");
            if (!BuildConfig.DEBUG) {
                boolean qch_usb_choose = Settings.System.putString(getContentResolver(), "qch_usb_choose", setting_usb);
                Log.e("SystemSetting", "qch_usb_choose---------" + qch_usb_choose);
                String usbStatus = "";
                switch (setting_usb) {
                    case "usb_charge":
                        usbStatus = "qch_action_usb_usb_charge";
                        break;
                    case "usb_mtp":
                        usbStatus = "qch_action_usb_usb_mtp";
                        break;
                    case "usb_midi":
                        usbStatus = "qch_action_usb_usb_midi";
                        break;

                }
                Intent usbIntent = new Intent(usbStatus);
                sendBroadcast(usbIntent);
            }

            int setting_bluetooth = changeNum(data.optInt("setting_bluetooth"));
            boolean qch_bt_forbid_on = Settings.System.putInt(getContentResolver(), "qch_bt_forbid_on", setting_bluetooth);
            Log.e("SystemSetting", "qch_bt_forbid_on---------" + qch_bt_forbid_on);
            Log.e("SystemSetting", "qch_bt_forbid_on---------" + Settings.System.getInt(getContentResolver(), "qch_bt_forbid_on", 0));

            //系统导航条显示开关
            int setting_navigation = changeNum(data.optInt("setting_navigation"));
            boolean qch_hide_navigationBar = Settings.System.putInt(getContentResolver(), "qch_hide_NavigationBar", setting_navigation);
            Log.e("SystemSetting", "qch_hide_navigationBar---------" + qch_hide_navigationBar);

            String navigationStatus = "";
            switch (setting_navigation) {
                case 0:
                    navigationStatus = "qch_show_NavigationBar";
                    break;
                case 1:
                    navigationStatus = "qch_hide_NavigationBar";
                    break;

            }
            Intent navIntent = new Intent(navigationStatus);
            sendBroadcast(navIntent);


            //状态栏显示开关
            int setting_statusbar = changeNum(data.optInt("setting_statusbar"));
            boolean qch_hide_statusBar = Settings.System.putInt(getContentResolver(), "qch_hide_statusBar", setting_statusbar);
            Log.e("SystemSetting", "qch_hide_statusBar---------" + qch_hide_statusBar);

            String statusbarStatus = "";
            switch (setting_statusbar) {
                case 0:
                    statusbarStatus = "qch_show_statusBar";
                    break;
                case 1:
                    statusbarStatus = "qch_hide_statusBar";
                    break;

            }
            Intent statusIntent = new Intent(statusbarStatus);
            sendBroadcast(statusIntent);

            //摄像头开关
            int setting_camera = changeNum(data.optInt("setting_camera"));
            Log.e("SystemSetting", "setting_camera---------" + setting_camera);
            String cameraStatus = "";
            switch (setting_camera) {
                case 0:
                    cameraStatus = "qch_camera_open";
                    break;
                case 1:
                    cameraStatus = "qch_camera_forbid";
                    break;
            }
            Intent cameraIntent = new Intent(cameraStatus);
            sendBroadcast(cameraIntent);

            //added:2019.12.6
            //设置5个app的开关
            //时钟
            int deskclock = changeNum(data.optInt("setting_clock"));
            Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_app_deskclock", deskclock);
            Log.e("SystemSetting", "qch_app_deskclock" + deskclock);
            //录音机
            int soundrecorder = changeNum(data.optInt("setting_recording"));
            Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_app_soundrecorder", soundrecorder);
            Log.e("SystemSetting", "qch_app_soundrecorder" + soundrecorder);
            //音乐
            int music = changeNum(data.optInt("setting_music"));
            Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_app_music", music);
            Log.e("SystemSetting", "qch_app_music" + music);
            //图库
            int gallery = changeNum(data.optInt("setting_picture"));
            Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_app_gallery", gallery);
            Log.e("SystemSetting", "qch_app_gallery" + gallery);
            //壁纸
            int wallpaper = changeNum(data.optInt("setting_wallpaper"));
            Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_app_wallpaper", wallpaper);
            Log.e("SystemSetting", "qch_app_wallpaper" + wallpaper);
            //文件管理器
            int filemanager = changeNum(data.optInt("setting_file"));
            Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_app_filemanager", filemanager);
            Log.e("SystemSetting", "qch_app_filemanager" + filemanager);

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("mjhseng", "SettingSysData---error::" + e.getMessage());
        }
    }

    private int changeNum(int status) {
        int num = 1;
        switch (status) {
            case 0:
                num = 1;
                break;
            case 1:
                num = 0;
                break;
            default:
                num = 1;
        }
        return num;
    }

    private void changeIcon(int postion) {
        mTopList.get(postion).setBackgroundResource(press_icon[postion]);
        for (int i = 0; i < mTopList.size(); i++) {
            if (i == postion) {
                continue;
            }
            mTopList.get(i).setBackgroundResource(normal_icon[i]);
        }
    }

    @Override
    public void onNetConnected(NetworkType networkType) {
        super.onNetConnected(networkType);
        //        ToastUtils.showLong("网络链接了");
        initJpush();
        Aria.download(this).resumeAllTask();
    }
}
