package com.mjsheng.myappstore.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

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.mjsheng.myappstore.BuildConfig;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
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.comm.CommonDatas;
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.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.SaveListUtils;
import com.mjsheng.myappstore.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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.annotations.Nullable;
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;

/**
 * 作者 mjsheng
 * 日期 2019/3/23 16:26
 * 邮箱 501802639@qq.com
 * 来自：
 */

public class InitJpushServer extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.e("InitJpushServer", "onCreate");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 初始化 JPush
        JPushInterface.init(this);
        timerImitate();
//        getNetworkState();
        Log.e("InitJpushServer", "onStartCommand");

        return super.onStartCommand(intent, flags, startId);
    }

    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("initmjsheng", "set is null");
                } else {
                    Log.e("initmjsheng", "set ---" + set.toString());
                }
                Log.e("JPushInterface", s + "---" + i + "---");
                if (i == 0) {
                    Log.e("JPushInterface", "JPush绑定成功");
                    getNetworkState();
                    sendMACaddress();
                } 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", "网络连接断开");
                    timerImitate();
                }
            }
        });

    }


    //重新设置jpush
    private void timerImitate() {
        Observable.timer(15000, 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 getNetworkState() {

        Observable.timer(1000, TimeUnit.MILLISECONDS)
                .observeOn(rx.android.schedulers.AndroidSchedulers.mainThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        Log.e("JPushInterface", "reconnectNetworkState");
                        getLockedState();//
                    }
                });
    }


    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("initmjsheng", "应用联网管控：：" + 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("initmjsheng", "getDeselectID---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("initmjsheng", "getDeselectID---woring----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

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

                    @Override
                    public void onComplete() {

                    }
                });
    }

    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("initmjsheng", "getDeselectBrowerID---onSubscribe");

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String responString = responseBody.string();
                            LogUtils.e("initmjsheng", "浏览器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("initmjsheng", "getDeselectBrowerID---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("initmjsheng", "getDeselectBrowerID---wroing----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

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

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

    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 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("initmjsheng", "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("initmjsheng", "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("initmjsheng", "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("initmjsheng", "forceDownloadApi---onComplete");
                    }
                });
    }

    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.jiaoguanyi.appstore")) {
                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.mjsheng.myappstore".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 = "";
        String camera_ok = "";
        String camera_not = "";

        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();
            int is_camera = netAndLaunchData.getIs_camera();

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

            if (is_camera == 1) {
                camera_ok += app_package + ",";
            } else {
                camera_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);
        }
        if (!TextUtils.isEmpty(camera_ok)) {
            camera_ok = camera_ok.substring(0, camera_ok.length() - 1);
        }
        if (!TextUtils.isEmpty(camera_not)) {
            camera_not = camera_not.substring(0, camera_not.length() - 1);
        }

        LogUtils.e("launch:" + launch + "-----------net_ok:" + net_ok + "-----------net_not:" + net_not);
        boolean qch_app_power_on = Settings.System.putString(getApplicationContext().getContentResolver(), "qch_app_power_on", launch);

//        Intent netControlIntent = new Intent(CommonDatas.ACTION_HrReceiver_JGY_DIS);
//        netControlIntent.putExtra("package_name", net_not);
//        sendBroadcast(netControlIntent);
//
//        Intent netControlNotIntent = new Intent(CommonDatas.ACTION_HrReceiver_JGY);
//        netControlNotIntent.putExtra("package_name", net_ok);
//        sendBroadcast(netControlNotIntent);
        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);

        }
        MyApplication.getInstance().setFinished(true);
        if (!net_ok.equals("")) {
            String[] nots = net_ok.split(",");
            Log.e("fht", "not::" + net_ok);
        }


        Intent intent2 = new Intent("qch_camera_forbid");
        intent2.putExtra("camera_package_name", camera_not);
        sendBroadcast(intent2);
        Intent intent1 = new Intent("qch_camera_open");
        intent1.putExtra("camera_package_name", camera_ok);
        sendBroadcast(intent1);
    }

    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(getApplicationContext().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(getApplicationContext().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("mjsheng1", "系统管控::" + 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("initmjsheng", "getSystemSetting---code is -200");
                                    break;
                            }
                        } catch (Exception e) {
                            Log.e("initmjsheng", "1getSystemSetting---wroing----" + e.getMessage());
                            e.printStackTrace();
                        }
                    }

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

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

    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) {

                    }

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

        }
    }


    boolean locked = false;

    synchronized 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("jpttlocked", String.valueOf(lock));
                            if (lock == 0) {
                                locked = false;
                                boolean se = Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_unlock_ipad", 1);
                                Log.e("fht", "getLockedState---------" + Settings.System.getString(getApplicationContext().getContentResolver(), "qch_unlock_ipad"));
                                Log.e("jpttlocked1", "qch_unlock_ipad---------" + locked + se);
                            } else {
                                locked = true;
                                Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_unlock_ipad", 0);
                                Log.e("jpttlocked2", "qch_unlock_ipad---------" + locked);
//                                Settings.System.putString(getApplicationContext().getContentResolver(), "DeselectBrowserArray", "http://www.baidu.com");
                                String ss = Settings.System.getString(getApplicationContext().getContentResolver(), "DeselectBrowserArray");
                                Log.e("jpttlocked2", "DeselectBrowserArray---------" + ss);
                                getAppLimitApi();
                                getDeselectID();
                                getDeselectBrowerID();
                                getNetAndLaunchSetting();
                                Aria.download(this).resumeAllTask();
                                getForceDownload();
                                getSystemSetting();//从后台获取功能状态
                                resetDevice();
                            }
                        }
                    }

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

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

    private void resetDevice() {
        boolean isReset = MySQLData.GetBooleanData(this, CommonDatas.IS_RESET);
        if (isReset) {
            sendBroadcast(new Intent("android.intent.action.MASTER_CLEAR"));
        }
    }

    private void SettingSysData(JSONObject data) {
        try {
            int setting_call = changeNum(data.optInt("setting_call"));
            boolean qch_call_forbid = Settings.System.putInt(getApplicationContext().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(getApplicationContext().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(getApplicationContext().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(getApplicationContext().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(getApplicationContext().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(getApplicationContext().getContentResolver(), "qch_bt_forbid_on", setting_bluetooth);
            Log.e("SystemSetting", "qch_bt_forbid_on---------" + qch_bt_forbid_on);

            //系统导航条显示开关
            int setting_navigation = changeNum(data.optInt("setting_navigation"));
            boolean qch_hide_navigationBar = Settings.System.putInt(getApplicationContext().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(getApplicationContext().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);


            //tfmedia开关
            int setting_tfmedia = changeNum(data.optInt("setting_tfmedia"));
            boolean qch_tfmedia_forbid = Settings.System.putInt(getApplicationContext().getContentResolver(),
                    "qch_tfmedia_forbid", setting_tfmedia);
            Log.e("SystemSetting", "setting_tfmedia---------" + qch_tfmedia_forbid);
            String tfmediaStatus = "";
            switch (setting_tfmedia) {
                case 0:
                    tfmediaStatus = "qch_tfmedia_open";
                    break;
                case 1:
                    tfmediaStatus = "qch_tfmedia_forbid";
                    break;
            }
            Intent tfmediaIntent = new Intent(tfmediaStatus);
            sendBroadcast(tfmediaIntent);
            if (setting_tfmedia == 1) {
                JSONArray jSONArray = null;
                try {
                    jSONArray = data.getJSONArray("setting_tfmedia_format");

                    int i = 0;
                    StringBuffer stringBuffer = new StringBuffer();
                    while (!jSONArray.isNull(i)) {
                        stringBuffer.append(jSONArray.getString(i));
                        stringBuffer.append(",");
                        i++;
                    }
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    Settings.System.putString(getApplicationContext().getContentResolver(), "qch_tfmedia_filetypes", stringBuffer.toString());//影音管控
                    Log.e("SystemSetting", "qch_tfmedia_filetypes---------" + stringBuffer.toString());

                } catch (JSONException e) {
                    Log.e("SystemSetting", "qch_tfmedia_filetypes---------" + e.getMessage());

                }
            } else {
                Settings.System.putInt(getApplicationContext().getContentResolver(), "qch_tfmedia_forbid", 0);
            }
            //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("mjsheng", "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;
    }

}
