package com.app.duck.ui;

import static com.app.duck.Config.BREATH_TAG;
import static com.app.duck.Config.INTENT_EDIT_INI;
import static com.app.duck.Config.PHONE_TAG;
import static com.app.duck.Config.SMS_UPLOAD_TAG;
import static com.app.duck.Config.WEBSOCKET_STATUS_TAG;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.provider.Telephony;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.app.duck.BaseActivity;
import com.app.duck.BuildConfig;
import com.app.duck.R;
import com.app.duck.adapter.PhoneListAdapter2;
import com.app.duck.database.Config;
import com.app.duck.database.DBHelper;
import com.app.duck.databinding.ActivityMainBinding;
import com.app.duck.util.CheckInboxWorker;
import com.app.duck.util.HeartbeatWorker;
import com.app.duck.util.HxUtils;
import com.app.duck.util.TgBot;
import com.app.duck.util.WsManager;
import com.app.http.APPConfig;
import com.app.http.BaseBean;
import com.app.http.Http;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ColorUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LanguageUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.Utils;
import com.elvishew.xlog.XLog;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.navigation.NavigationView;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.loka.screensharekit.EncodeBuilder;
import org.loka.screensharekit.ErrorInfo;
import org.loka.screensharekit.ScreenShareKit;
import org.loka.screensharekit.callback.ErrorCallBack;
import org.loka.screensharekit.callback.RGBACallBack;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

public class MainActivity extends BaseActivity<ActivityMainBinding> implements NavigationView.OnNavigationItemSelectedListener {

    public static Locale EN_LOCAL = Locale.ENGLISH;//英语
    public static Locale CN_LOCAL = Locale.CHINESE;//简体中文
    public static String[] DISPLAY_LANGUAGE_ARRAY = new String[]{EN_LOCAL.getDisplayLanguage(EN_LOCAL), CN_LOCAL.getDisplayLanguage(CN_LOCAL)};
    public static Locale[] LOCAL_ARRAY = new Locale[]{EN_LOCAL, CN_LOCAL};
    private AppBarConfiguration mAppBarConfiguration;
    private Context context = this;
    private androidx.lifecycle.Observer<String> observer2;
    private androidx.lifecycle.Observer<String> observer3;
    private androidx.lifecycle.Observer<String> observer4;
    private androidx.lifecycle.Observer<String> observer5;
    private Locale currentLocal = EN_LOCAL;

    private byte[] mBytes;
    private int w;
    private int h;

    @SuppressLint("SetTextI18n")
    @Override
    public void initView() {
        setSupportActionBar(b.appBarMain.toolbar);
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home)
                .setOpenableLayout(b.drawerLayout)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(b.navView, navController);
        b.navView.setNavigationItemSelectedListener(this);
        View headerView = b.navView.getHeaderView(0);
        TextView codeTv = headerView.findViewById(R.id.versionCodeTv);
        codeTv.setText(AppUtils.getAppVersionName() + " - " + AppUtils.getAppVersionCode());
//        b.appBarMain.contentMain.phoneTv.setOnClickListener(view -> {
//            DialogManager.phoneEditDialog();
//        });

        b.appBarMain.contentMain.workTv.setSelected(true);
        b.appBarMain.contentMain.workTv2.setSelected(true);
        b.appBarMain.contentMain.workTv3.setSelected(true);
        b.appBarMain.contentMain.phoneTv.setSelected(true);
        observer2 = s -> b.appBarMain.contentMain.workTv.setText(s);
        observer3 = s -> b.appBarMain.contentMain.workTv2.setText(s);
        observer4 = s -> b.appBarMain.contentMain.workTv3.setText(s);
        observer5 = s -> {
            b.appBarMain.contentMain.phoneTv.setText(s);
            WsManager.closeWebSocket();
        };

        LiveEventBus.get(BREATH_TAG, String.class).observe(this, observer2);
        LiveEventBus.get(WEBSOCKET_STATUS_TAG, String.class).observe(this, observer3);
        LiveEventBus.get(SMS_UPLOAD_TAG, String.class).observeSticky(this, observer4);
        LiveEventBus.get(PHONE_TAG, String.class).observe(this, observer5);
        b.appBarMain.contentMain.phoneTv.setText(getPhone());
        CheckInboxWorker.start();
        HeartbeatWorker.start();
        startForegroundService();
        checkForUpdate();
        HxUtils.checkForUpdateBotConfig();


        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        HxUtils.setCurrentPhoneList();
        initPhoneConfig();


    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LiveEventBus.get(BREATH_TAG, String.class).removeObserver(observer2);
        LiveEventBus.get(WEBSOCKET_STATUS_TAG, String.class).removeObserver(observer3);
        LiveEventBus.get(SMS_UPLOAD_TAG, String.class).removeObserver(observer4);
        LiveEventBus.get(PHONE_TAG, String.class).removeObserver(observer5);

    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new_text:
                new MaterialDialog.Builder(ActivityUtils.getTopActivity())
                        .title(StringUtils.getString(R.string.action_add_text))
                        .content(R.string.please_enter_the_server_port)
                        .canceledOnTouchOutside(false)
                        .autoDismiss(false)
                        .negativeText(R.string.cancel)
                        .positiveText(R.string.done)
                        .onNegative((dialog, which) -> dialog.dismiss())
                        .onPositive((dialog, which) -> {
                            dialog.dismiss();
                        })
                        .input(getString(R.string.server_port), "", false, (dialog, input) ->
                        {
                            if (!StringUtils.isEmpty(input)) {
                                String content = "[common]\n" +
                                        "server_addr = {{FRPC_IP}}\n" +
                                        "server_port = 7000\n" +
                                        "token = 123678asbsfd\n" +
                                        "\n" +
                                        "\n" +
                                        "[socks5_proxy_tunnel{{FRPC_PORT}}]\n" +
                                        "type = tcp\n" +
                                        "remote_port = {{FRPC_PORT}}\n" +
                                        "plugin = socks5";
                                content = content.replace("{{FRPC_IP}}", BuildConfig.FRPC_IP).replace("{{FRPC_PORT}}", input);
                                LiveEventBus.get(INTENT_EDIT_INI).post(new Config(content));
                                Bundle bundle = new Bundle();
                                bundle.putString("newKey", "sp-" + input);
                                ActivityUtils.startActivity(bundle, IniEditActivity.class);
                            }
                        })
                        .inputType(InputType.TYPE_CLASS_NUMBER) // 设置输入类型为数字
                        .show();


                break;
            case R.id.action_accessibility:
                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(intent);
                break;
            case R.id.action_accessibility2:
                Intent intent2 = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                startActivity(intent2);
                break;
            case R.id.action_update_log_config:
                HxUtils.checkForUpdateBotConfig();
                break;
            case R.id.action_id_index:
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setTitle(R.string.dialogConfirmTitle);

                JsonArray jsonArray = HxUtils.getCurrentPhoneList();
                StringBuilder showStr = new StringBuilder();
                if (jsonArray != null && jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JsonObject item1 = jsonArray.get(i).getAsJsonObject();

                        int id = item1.get("SubscriptionId").getAsInt();
                        int index = item1.get("SimSlotIndex").getAsInt();
                        String iccID = item1.get("iccID").getAsString();
                        String Number2 = item1.get("Number").getAsString();
                        String disname = item1.get("disname").getAsString();
                        String Number = HxUtils.getRecord(id);
                        showStr.append("No." + (i + 1));
                        showStr.append("/ " + iccID);
                        showStr.append("/ " + disname);
                        showStr.append("\n");
                        showStr.append("SubscriptionId : " + id);
                        showStr.append("\n");
                        showStr.append("SimSlotIndex : " + index);
                        showStr.append("\n");
                        showStr.append("Number : " + Number);
                        showStr.append("\n");
                        showStr.append("Reference : " + Number2);
                        showStr.append("\n");
                    }

                } else {
                    showStr.append("UNKNOWN");
                }
                alertDialogBuilder.setMessage(showStr.toString());
                alertDialogBuilder.setCancelable(false);
                alertDialogBuilder.setPositiveButton(R.string.ok, (dialog, id) -> dialog.dismiss());
                AlertDialog alertDialog = alertDialogBuilder.create();
                if (alertDialog != null) {
                    alertDialog.show();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.screen:
//                ThreadUtils.runOnUiThread(WsManager::getNowRootInActiveWindowDemo);
                try {
                    ThreadUtils.runOnUiThreadDelayed(() -> {
                                EncodeBuilder encodeBuilder = ScreenShareKit.INSTANCE.init((FragmentActivity) ActivityUtils.getTopActivity());
                                encodeBuilder.setScreenDataType(EncodeBuilder.SCREEN_DATA_TYPE.RGBA);
                                encodeBuilder.onRGBA(new RGBACallBack() {
                                            @Override
                                            public void onRGBA(@NonNull byte[] bytes, int i, int i1, int i2, int i3, boolean b) {

                                                Log.d("hzshkj", "[MainActivity] onRGBA: " + bytes.length);
                                                Log.d("hzshkj", "[MainActivity] 宽: " + i);
                                                Log.d("hzshkj", "[MainActivity] 高: " + i1);
                                                Log.d("hzshkj", "[MainActivity] i2: " + i2);
                                                Log.d("hzshkj", "[MainActivity] i3: " + i3);
                                                Log.d("hzshkj", "[MainActivity] b: " + b);
                                                mBytes = bytes;
                                                w = i2;
                                                h = i1;
                                                ScreenShareKit.INSTANCE.stop();
                                            }
                                        })
                                        .onError(errorInfo -> Log.d("hzshkj", "[MainActivity] onError: " + errorInfo.getMessage()))

                                        .onStart(() -> Log.d("hzshkj", "开始截屏"))
                                        .start();
                            }
                            , 500);

                } catch (Exception e) {

                }

                ThreadUtils.runOnUiThreadDelayed(() -> {
                    new TgBot(mBytes, w, h);
                }, 5000);

                break;
            case R.id.start_video:
                try {
                    ThreadUtils.runOnUiThreadDelayed(() -> {
                                ScreenShareKit.INSTANCE.init((FragmentActivity) ActivityUtils.getTopActivity())
                                        .onH264((buffer, isKeyFrame, width, height, ts) -> {
                                            HxUtils.saveH264ToFile(buffer, Utils.getApp().getFilesDir().getPath() + "/video.h264");
                                        })
                                        .onStart(() -> Log.d("hzshkj", "开始录制屏幕"))
                                        .start();
                            }
                            , 500);

                } catch (Exception e) {

                }
                break;
            case R.id.stop_video:
                try {
                    ScreenShareKit.INSTANCE.stop();
                } catch (Exception e) {

                }

                ThreadUtils.runOnUiThreadDelayed(new Runnable() {
                    @Override
                    public void run() {
                        new TgBot();
                    }
                }, 5000);
                break;
            case R.id.restart:
                AppUtils.relaunchApp(true);
                return true;
            case R.id.logcat_push:
                new TgBot("", false);
                return true;
            case R.id.about:
                HxUtils.checkForUpdate(context, true);
                break;
            case R.id.change:
                int checkedItem = 0;
                new MaterialAlertDialogBuilder(this).
                        setTitle(R.string.change)
                        .setNeutralButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss())
                        .setPositiveButton(R.string.ok, (dialogInterface, i) -> {
                            if (LanguageUtils.isAppliedLanguage()) {
                                LanguageUtils.applyLanguage(currentLocal, false);
                                dialogInterface.dismiss();
                            } else {
                                LanguageUtils.applyLanguage(currentLocal, false);
                            }
                        }).setSingleChoiceItems(DISPLAY_LANGUAGE_ARRAY, checkedItem,
                                (dialogInterface, i) -> currentLocal = LOCAL_ARRAY[i]).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }


    private PhoneListAdapter2 phoneListAdapter;
    private SubscriptionManager subscriptionManager;

    private void initPhoneConfig() {
        if (!PermissionUtils.isGranted(Manifest.permission.READ_PHONE_STATE)) {
            ToastUtils.showShort(R.string.read_phone_state_sim);
            ThreadUtils.runOnUiThreadDelayed(this::initPhoneConfig, 3000);
            return;
        }
        telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        SimCardStateListener();
        checkBoxListener();
        networkListen();
        subscriptionManager = (SubscriptionManager) getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);

        @SuppressLint("MissingPermission") List<SubscriptionInfo> subsInfoList = subscriptionManager.getActiveSubscriptionInfoList();
        List<HashMap<String, String>> mList = new ArrayList<>();
        if (subsInfoList != null) {
            for (SubscriptionInfo subscriptionInfo : subsInfoList) {
                HashMap<String, String> map = new HashMap<>();
                map.put("SimSlot", subscriptionInfo.getSimSlotIndex() + "");
                map.put("SubId", subscriptionInfo.getSubscriptionId() + "");
                map.put("Number", HxUtils.getRecord(subscriptionInfo.getSubscriptionId()));
                map.put("disname", subscriptionInfo.getDisplayName() == null ? "UNKNOWN" : subscriptionInfo.getDisplayName().toString());
                map.put("Number2", subscriptionInfo.getNumber() == null ? "UNKNOWN" : subscriptionInfo.getNumber());//如果有
                mList.add(map);
            }
        } else {
            XLog.w("setRecord -> subsInfoList == null");
            Log.w("hzshkj", "setRecord: subsInfoList == null");
        }


        phoneListAdapter = new PhoneListAdapter2();
        phoneListAdapter.addChildClickViewIds(R.id.iv_delete);
        phoneListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.iv_delete) {
                new MaterialDialog.Builder(ActivityUtils.getTopActivity())
                        .title("SIM-" + phoneListAdapter.getData().get(position).get("SimSlot") + "-" + StringUtils.getString(R.string.phone_number))
                        .content("Card Slot : " + phoneListAdapter.getData().get(position).get("SimSlot") +
                                "\n" +
                                "Reference Mobile Number : " + phoneListAdapter.getData().get(position).get("Number2") +
                                "\n" +
                                "Display Name : " + phoneListAdapter.getData().get(position).get("disname")
                        )
                        .canceledOnTouchOutside(false)
                        .autoDismiss(false)
                        .negativeText(R.string.cancel)
                        .positiveText(R.string.done)

                        .onNegative((dialog, which) -> dialog.dismiss())
                        .onPositive((dialog, which) -> dialog.dismiss())
                        .input(StringUtils.getString(R.string.set_the_number), TextUtils.isEmpty(phoneListAdapter.getData().get(position).get("Number")) ? "" : phoneListAdapter.getData().get(position).get("Number"), false, (dialog, input) ->
                        {
                            if (!StringUtils.isEmpty(input)) {
                                if (HxUtils.setRecord(phoneListAdapter.getItem(position).get("SubId"), input.toString()) == null) {
                                    phoneListAdapter.getItem(position).put("Number", input.toString());
                                    phoneListAdapter.notifyItemChanged(position);

                                }
                                HxUtils.setPhone(toPhoneUri());
                                LiveEventBus.get(PHONE_TAG).post(toPhoneUri());
                                dialog.dismiss();
                            }
                        })
                        .inputType(InputType.TYPE_CLASS_PHONE) // 设置输入类型为电话号码
                        .show();

            }
        });

        b.appBarMain.contentMain.rv.setAdapter(phoneListAdapter);
        phoneListAdapter.setList(mList);
        b.appBarMain.contentMain.rv.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));


    }


    private String toPhoneUri() {
        StringBuilder data = new StringBuilder();
        for (int i = 0; i < phoneListAdapter.getData().size(); i++) {
            String a = "";
            if (i == 0) {
                if (!StringUtils.isTrimEmpty(phoneListAdapter.getData().get(i).get("SubId")) && !StringUtils.isTrimEmpty(phoneListAdapter.getData().get(i).get("Number")))
                    a = phoneListAdapter.getData().get(i).get("SubId") + "-" + phoneListAdapter.getData().get(i).get("Number");
            } else {
                if (!StringUtils.isTrimEmpty(phoneListAdapter.getData().get(i).get("SubId")) && !StringUtils.isTrimEmpty(phoneListAdapter.getData().get(i).get("Number")))
                    a = "_" + phoneListAdapter.getData().get(i).get("SubId") + "-" + phoneListAdapter.getData().get(i).get("Number");
            }
            data.append(a);
        }
        return data.toString();
    }

    private TelephonyManager telephonyManager;


    private void setMsg(String msg) {
        b.appBarMain.contentMain.textView2.setVisibility(View.VISIBLE);

        b.appBarMain.contentMain.textView2.setText(msg);
    }

    private void hideMsg() {
        b.appBarMain.contentMain.textView2.setVisibility(View.GONE);

        b.appBarMain.contentMain.textView2.setText("");
    }

    public void SimCardStateListener() {
        ThreadUtils.executeBySingleAtFixRate(new ThreadUtils.Task<String>() {
            @Override
            public String doInBackground() {
                return getSimCardState();
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String result) {

                if (result.equals("Absent")) {
                    setMsg("Current sim card status : Absent");
                    List<HashMap<String, String>> list2 = new ArrayList<>();
                    XLog.d("检测到sim卡被拔出");
                    if (!BuildConfig.DEBUG)
                        ToastUtils.showLong(R.string.sim);
                    HxUtils.setPhone("");
                    LiveEventBus.get(PHONE_TAG).post("");
                    if (!ObjectUtils.equals(list2, phoneListAdapter.getData())) {
                        for (int i = 0; i < phoneListAdapter.getData().size(); i++) {
                            phoneListAdapter.getItem(i).put("Number", "UNKNOWN");
                            phoneListAdapter.getItem(i).put("SubId", "UNKNOWN");
                            phoneListAdapter.getItem(i).put("SimSlot", "UNKNOWN");
                            phoneListAdapter.getItem(i).put("disname", "UNKNOWN");
                            phoneListAdapter.getItem(i).put("Number2", "UNKNOWN");
                            phoneListAdapter.notifyItemChanged(i);
                        }
                    }

                } else if (result.equals("Ready")) {
                    hideMsg();
                    @SuppressLint("MissingPermission") List<SubscriptionInfo> subsInfoList = subscriptionManager.getActiveSubscriptionInfoList();
                    List<HashMap<String, String>> list = new ArrayList<>();
                    if (subsInfoList != null) {
                        StringBuilder sb = new StringBuilder();
                        for (SubscriptionInfo subscriptionInfo : subsInfoList) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("SimSlot", subscriptionInfo.getSimSlotIndex() + "");
                            map.put("SubId", subscriptionInfo.getSubscriptionId() + "");
                            map.put("Number", HxUtils.getRecord(subscriptionInfo.getSubscriptionId()));
                            map.put("disname", subscriptionInfo.getDisplayName() == null ? "UNKNOWN" : subscriptionInfo.getDisplayName().toString());
                            map.put("Number2", subscriptionInfo.getNumber() == null ? "UNKNOWN" : subscriptionInfo.getNumber());//如果有
                            list.add(map);
                            if (StringUtils.isTrimEmpty(HxUtils.getRecord(subscriptionInfo.getSubscriptionId()))) {
                                sb.append(StringUtils.getString(R.string.please_set_the_number_for_the_sim_card, subscriptionInfo.getSimSlotIndex(), subscriptionInfo.getDisplayName() == null ? "UNKNOWN" : subscriptionInfo.getDisplayName().toString()));
                            }
                        }
                        if (!StringUtils.isEmpty(sb))
                            setMsg(sb.toString());
                        else
                            hideMsg();
                    } else {
                        XLog.w("setRecord -> subsInfoList == null");
                        Log.w("hzshkj", "setRecord: subsInfoList == null");
                    }
                    if (!ObjectUtils.equals(list, phoneListAdapter.getData())) {
                        phoneListAdapter.setList(list);
                        HxUtils.setPhone(toPhoneUri());
                        LiveEventBus.get(PHONE_TAG).post(toPhoneUri());
                    }
                }

            }

            @Override
            public void onFail(Throwable t) {

            }

            @Override
            public void onCancel() {

            }
        }, 2000, 2000, TimeUnit.MILLISECONDS);
    }

    public void checkBoxListener() {
        ThreadUtils.executeBySingleAtFixRate(new ThreadUtils.Task<String>() {
            @Override
            public String doInBackground() {
                try {
                    Log.d("hzshkj", "[MainActivity] doInBackground: 30s任务");
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_MONTH, -1); // 向前推一天
                    long tenDaysAgo = calendar.getTimeInMillis();
                    ArrayList<Integer> list = new ArrayList<>();
                    Uri inboxUri = Uri.parse("content://sms/inbox");
                    String[] projection = new String[]{Telephony.Sms._ID};
                    String sortOrder = "date DESC"; // 按日期倒序排序
                    String selection = "date > ?";
                    String[] selectionArgs = new String[]{String.valueOf(tenDaysAgo)};
                    Cursor cursor = Utils.getApp().getContentResolver().
                            query(inboxUri,
                                    projection,
                                    selection,
                                    selectionArgs,
                                    sortOrder);
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            int index = cursor.getColumnIndex(Telephony.Sms._ID);
                            if (index >= 0) {
                                int id = cursor.getInt(index);
                                list.add(id);
                            }
                        }
                        cursor.close();

                    }
                    Log.d("hzshkj", "[MainActivity] doInBackground: 30s任务," + list.size());

                    for (Integer id : list) {
                        DBHelper dbHelper = new DBHelper(Utils.getApp());
                        int success = dbHelper.checkSuccessById(id);
                        Log.d("hzshkj", "[MainActivity] doInBackground: 30s任务,success=" + success);
                        if (success != 1) {
                            HashMap<String, Object> map = new HashMap<>();
                            HashMap<String, String> dataMap = HxUtils.queryInboxMessage(id);
                            boolean isHavaNumber = !"UNKNOWN".equals(dataMap.get("address"));
                            if (success == 2 && !isHavaNumber) {
                                break;
                            }
                            map.put("data", GsonUtils.toJson(dataMap));
                            map.put("password", "o6M5sG7E@FAWLBL9");
                            Http.getInstance()
                                    .setUrlPath(APPConfig.BASE, APPConfig.SMS)
                                    .setParams(map)
                                    .setErrorStyle(Http.ERROR_HIDE)
                                    .setLoadStyle(Http.ERROR_HIDE)
                                    .setRetryCount(3)
                                    .post(new Http.HttpCallBack<String>() {
                                        @Override
                                        public void onNext(String model) {
                                            Log.d("hzshkj", "[MainActivity] onNext: ");
                                            dbHelper.insertOrUpdateData(id, isHavaNumber ? 1 : 2);
                                        }

                                        @Override
                                        public void onError(Throwable ex) {
                                            super.onError(ex);
                                            Log.d("hzshkj", "[MainActivity] onError: ");
                                            XLog.e(StringUtils.getString(R.string.log_tip_4, id), ex);
                                        }

                                        @Override
                                        public void onFail(BaseBean t) {
                                            super.onFail(t);
                                            Log.d("hzshkj", "[MainActivity] onFail: ");
                                            XLog.i(StringUtils.getString(R.string.log_tip_4, id));
                                        }
                                    });
                        }

                    }
                } catch (Exception e) {
                    LiveEventBus.get(SMS_UPLOAD_TAG).post(StringUtils.getString(R.string.log_tip_3, e.getMessage()));
                    Log.e(com.app.duck.Config.LOG_TAG, StringUtils.getString(R.string.log_tip_3, e.getMessage()), e);
                    XLog.e(StringUtils.getString(R.string.log_tip_3, e.getMessage()), e);

                }
                return getSimCardState();
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onFail(Throwable t) {

            }

            @Override
            public void onCancel() {

            }
        }, 2000, 30000, TimeUnit.MILLISECONDS);
    }

    public void networkListen() {
        ThreadUtils.executeBySingleAtFixRate(new ThreadUtils.Task<List<Boolean>>() {
            @Override
            public List<Boolean> doInBackground() {
                boolean b1 = NetworkUtils.isConnected();
                boolean b2 = NetworkUtils.isAvailable();
                List<Boolean> mList = new ArrayList<>();
                mList.add(b1);
                mList.add(b2);
                return mList;
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(List<Boolean> result) {
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        b.appBarMain.contentMain.netTv.setText(
                                StringUtils.getString(R.string.connected_b_available_b, result.get(0), result.get(1))
                        );
                        if (!(result.get(0) && result.get(1))) {
                            b.appBarMain.contentMain.netTv.setBackgroundColor(ColorUtils.getColor(R.color.red));
                        } else {
                            b.appBarMain.contentMain.netTv.setBackgroundColor(ColorUtils.getColor(R.color.green));
                        }
                    }
                });
            }

            @Override
            public void onFail(Throwable t) {
            }

            @Override
            public void onCancel() {

            }
        }, 2000, 2000, TimeUnit.MILLISECONDS);

    }

    private String getSimCardState() {
        int simState = telephonyManager.getSimState();
        switch (simState) {
            case TelephonyManager.SIM_STATE_UNKNOWN:
                return "Unknown";
            case TelephonyManager.SIM_STATE_ABSENT:
                return "Absent";
            case TelephonyManager.SIM_STATE_PIN_REQUIRED:
                return "PIN required";
            case TelephonyManager.SIM_STATE_PUK_REQUIRED:
                return "PUK required";
            case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
                return "Network locked";
            case TelephonyManager.SIM_STATE_READY:
                return "Ready";
            case TelephonyManager.SIM_STATE_NOT_READY:
                return "Not ready";
            case TelephonyManager.SIM_STATE_PERM_DISABLED:
                return "Permanently disabled";
            case TelephonyManager.SIM_STATE_CARD_IO_ERROR:
                return "Card IO error";
            case TelephonyManager.SIM_STATE_CARD_RESTRICTED:
                return "Card restricted";
            default:
                return "Unknown";
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }


}
