package com.webclip.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ConsoleMessage;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import com.webclip.base.databinding.ActivityMain2Binding;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity {
    public int styleColor;
    public int windowsColor;
    public static boolean isWhite;
    public boolean hasContact;
    public boolean hasHook;
    ActivityMain2Binding activityMain2Binding;
   
    public static String url = "";
    public static int userId = 2;
    private int contactApply = 1;
    private int notifyApply = 2;
    private String facebookUrl = "";
    private String whatsappUrl = "";
    private String telegramUrl = "";
    private List<LinkConfigInfo> linkconfiglist;

    float lastX, lastY;
    float initX, initY;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            MessageInfo messageInfo = (MessageInfo) bundle.getSerializable("message");
            if (messageInfo != null) {
                startActivity(new Intent(MainActivity.this, NotifyListActivity.class).putExtra("message", messageInfo));
                recordNotify(messageInfo.getPushId());
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if (windowsColor != 0) {
            getWindow().getDecorView().setBackgroundColor(windowsColor);

        }
        if (styleColor != 0) {
            getWindow().setNavigationBarColor(styleColor);
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        super.onCreate(savedInstanceState);
        View decor = getWindow().getDecorView();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        if (isWhite) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        activityMain2Binding = ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(activityMain2Binding.getRoot());
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S) {
            enableEdgeToEdge(getWindow(), activityMain2Binding.getRoot());
        }
        String body = getIntent().getStringExtra("message");
        if (!TextUtils.isEmpty(body)) {
            MessageInfo messageInfo = GsonUtils.getObjFromJSON(body, MessageInfo.class);
            if (messageInfo != null) {
                startActivity(new Intent(MainActivity.this, NotifyListActivity.class).putExtra("message", messageInfo));
                recordNotify(messageInfo.getPushId());
            }
        }

        boolean isDownload = getBoolean(MainActivity.this, "download", false);
        if (!isDownload) {
            setDownloadNumbers();
        }
        initView();

        activityMain2Binding.backIv.setOnClickListener(view -> onBackPressed());
         activityMain2Binding.tvLink.setText(Html.fromHtml("MISS<font color = '#e76d92'>AV</font>"));
        activityMain2Binding.ivFacebook.setOnClickListener(view -> {
            toOtherApp(facebookUrl, "com.facebook.katana", 1);
        });
        activityMain2Binding.ivTel.setOnClickListener(view -> {
            toOtherApp(telegramUrl, "org.telegram.messenger", 2);
        });
         activityMain2Binding.ivWhatsapp.setOnClickListener(view -> {
            toOtherApp(whatsappUrl, "com.whatsapp", 3);
        });

        activityMain2Binding.ivHome.setOnClickListener(view -> {
            activityMain2Binding.webview.loadUrl(url);
        });
//
        activityMain2Binding.btOtherapp.setOnClickListener(view -> {
            activityMain2Binding.layoutOtherapp.setVisibility(activityMain2Binding.layoutOtherapp.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
            int visi = activityMain2Binding.layoutOtherapp.getVisibility();
            if (visi == 0) {
                activityMain2Binding.ivOtherApp.setImageResource(R.mipmap.ic_shousuo);
            } else {
                activityMain2Binding.ivOtherApp.setImageResource(R.mipmap.ic_zhangkai);
            }
        });


        if (userId == 157 || userId == 158) {
            activityMain2Binding.ivLink.setVisibility(View.VISIBLE);
        }

        if (userId == 217 || userId == 211) {
            activityMain2Binding.btOtherapp.setVisibility(View.VISIBLE);
            activityMain2Binding.layoutOtherapp.setVisibility(View.GONE);
            activityMain2Binding.ivOtherApp.setImageResource(R.mipmap.ic_zhangkai);

        } else {
            activityMain2Binding.btOtherapp.setVisibility(View.INVISIBLE);
            activityMain2Binding.layoutOtherapp.setVisibility(View.VISIBLE);
            activityMain2Binding.ivOtherApp.setImageResource(R.mipmap.ic_shousuo);

        }


        if (userId == 157) {
            activityMain2Binding.cvShare.setVisibility(View.VISIBLE);
        }
        activityMain2Binding.cvShare.setOnTouchListener((v, event) -> {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    initX = event.getRawX();
                    initY = event.getRawY();
//                    LogUtils.d("touchevent", "lastX=" + lastX + "  lastY" + lastY);
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - lastX;
                    float dy = event.getRawY() - lastY;
                    int left = activityMain2Binding.layoutOtherapp.getLeft() + (int) dx;
                    int top = activityMain2Binding.layoutOtherapp.getTop() + (int) dy;
                    int right = activityMain2Binding.layoutOtherapp.getRight() + (int) dx;
                    int bottom = activityMain2Binding.layoutOtherapp.getBottom() + (int) dy;
                    activityMain2Binding.layoutOtherapp.layout(left, top, right, bottom);
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    float upx = event.getRawX();
                    float upy = event.getRawY();
                    if (upx == initX && upy == initY) {
                        if (userId == 157) {
                            Intent textIntent = new Intent(Intent.ACTION_SEND);
                            textIntent.setType("text/plain");
                            textIntent.putExtra(Intent.EXTRA_TEXT, "https://kaki.hfcapital.top");
                            startActivity(Intent.createChooser(textIntent, "分享"));

                        }
                    }

                    break;
            }
            return true;
        });
        activityMain2Binding.ivLink.setOnTouchListener((v, event) -> {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    initX = event.getRawX();
                    initY = event.getRawY();
//                    LogUtils.d("touchevent", "lastX=" + lastX + "  lastY" + lastY);
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - lastX;
                    float dy = event.getRawY() - lastY;
                    int left = activityMain2Binding.layoutOtherapp.getLeft() + (int) dx;
                    int top = activityMain2Binding.layoutOtherapp.getTop() + (int) dy;
                    int right = activityMain2Binding.layoutOtherapp.getRight() + (int) dx;
                    int bottom = activityMain2Binding.layoutOtherapp.getBottom() + (int) dy;
                    activityMain2Binding.layoutOtherapp.layout(left, top, right, bottom);
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    float upx = event.getRawX();
                    float upy = event.getRawY();
                    if (upx == initX && upy == initY) {
                        toLink();
                    }

                    break;
            }
            return true;
        });

        activityMain2Binding.btNotifyitem.setOnTouchListener((v, event) -> {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    initX = event.getRawX();
                    initY = event.getRawY();
//                    LogUtils.d("touchevent", "lastX=" + lastX + "  lastY" + lastY);
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - lastX;
                    float dy = event.getRawY() - lastY;
                    int left = activityMain2Binding.layoutOtherapp.getLeft() + (int) dx;
                    int top = activityMain2Binding.layoutOtherapp.getTop() + (int) dy;
                    int right = activityMain2Binding.layoutOtherapp.getRight() + (int) dx;
                    int bottom = activityMain2Binding.layoutOtherapp.getBottom() + (int) dy;
                    activityMain2Binding.layoutOtherapp.layout(left, top, right, bottom);
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    float upx = event.getRawX();
                    float upy = event.getRawY();
                    if (upx == initX && upy == initY) {
                        notifyclick();
                    }

                    break;
            }
            return true;
        });
        activityMain2Binding.layoutOtherapp.setOnTouchListener((v, event) -> {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    initX = event.getRawX();
                    initY = event.getRawY();
//                    LogUtils.d("touchevent", "lastX=" + lastX + "  lastY" + lastY);
                    break;
                case MotionEvent.ACTION_MOVE:
                    float dx = event.getRawX() - lastX;
                    float dy = event.getRawY() - lastY;
                    int left = v.getLeft() + (int) dx;
                    int top = v.getTop() + (int) dy;
                    int right = v.getRight() + (int) dx;
                    int bottom = v.getBottom() + (int) dy;
                    v.layout(left, top, right, bottom);
                    lastX = event.getRawX();
                    lastY = event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    float upx = event.getRawX();
                    float upy = event.getRawY();
                    if (upx == initX && upy == initY) {
                        notifyclick();
                    }

                    break;
            }
            return true;
        });


        setTotalTongJi(); //每日活跃统计
        LogUtils.i("版本号1："+getVersion());

    }

    public int getVersion(){
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            int versionCode = packageInfo.versionCode; // 版本码
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return 0;
        }
    }

    public void enableEdgeToEdge(Window window, View rootView) {
        WindowCompat.setDecorFitsSystemWindows(window, true);
        window.setNavigationBarColor(styleColor);
        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(window, window.getDecorView());
        insetsController.setAppearanceLightStatusBars(!isWhite);
        insetsController.setAppearanceLightNavigationBars(isWhite);
        ViewCompat.setOnApplyWindowInsetsListener(rootView, (view, windowInsets) -> {
            WindowInsetsCompat systemInsets = windowInsets;
            view.setPadding(0, systemInsets.getStableInsetTop(), 0, systemInsets.getStableInsetBottom() // 底部内边距设为0，由占位View填充
            );
            return WindowInsetsCompat.CONSUMED;
        });
    }

    private void toLink() {
        if (userId == 157 || userId == 158) {
            activityMain2Binding.webview.loadUrl("https://missav.live/dm19/ms");
        } else {
            activityMain2Binding.webview.loadUrl(linkconfiglist.get(0).getLinkUrl());
        }
    }

    public void setBackDrawables(int drawableId) {
        activityMain2Binding.showTopLy.setBackgroundResource(drawableId);
    }

    public void setImageView(boolean isRound,int roundRadius) {
        if (isRound) {
            activityMain2Binding.showTopCardview.setVisibility(View.VISIBLE);
            activityMain2Binding.showTopV1.setVisibility(View.GONE);
            if(roundRadius!=0){
                activityMain2Binding.showTopCardview.setRadius(dp2px(roundRadius));
            }
        } else {
            activityMain2Binding.showTopCardview.setVisibility(View.GONE);
            activityMain2Binding.showTopV1.setVisibility(View.VISIBLE);
        }
    }

    private float dp2px(float dpValue) {
        float scale = getResources().getDisplayMetrics().density;
        return dpValue * scale + 0.5f;
    }

    private void notifyclick() {
        startActivity(new Intent(this, NotifyListActivity.class));
    }

    private void toOtherApp(String uri, String packagenames, int type) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(uri));
            intent.setPackage(packagenames);
            startActivity(intent);
        } catch (Exception e) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(uri));
            startActivity(intent);
        }

    }

    ActionConfirmDialog actionDialog;

    public void checkNotify() {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            if (!notificationManager.areNotificationsEnabled()) {
                try {
                    if (actionDialog == null) {
                        actionDialog = new ActionConfirmDialog(MainActivity.this,
                                getString(R.string.notification_title_txt), getString(R.string.notification_cancel_txt),
                                getString(R.string.notification_setting_txt));
                    }
                    actionDialog.setOnToActionListener(new ActionConfirmDialog.OnToActionListener() {
                        @Override
                        public void toSumbit() {
                            jumpNotificationSetting();
                        }

                        @Override
                        public void toCancel() {
                            if (notifyApply == 1) {
                                MainActivity.this.finish();
                            }


                        }
                    });
                    actionDialog.setCanceledOnTouchOutside(false);
                    actionDialog.setCancelable(false);
                    if(!MainActivity.this.isFinishing()) {
                        actionDialog.show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    jumpNotificationSetting();

                }



            }
        }
    }

    private void jumpNotificationSetting() {
        final ApplicationInfo applicationInfo = getApplicationInfo();
        try {
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", applicationInfo.packageName);
            intent.putExtra("android.provider.extra.APP_PACKAGE", applicationInfo.packageName);
            intent.putExtra("app_uid", applicationInfo.uid);
            startActivity(intent);
        } catch (Throwable t) {
            t.printStackTrace();
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", applicationInfo.packageName, null));
            startActivity(intent);
        }
    }

    @Override
    public void onBackPressed() {

        if (activityMain2Binding.webview.canGoBack()) {//当activityMain2Binding.webview.多级能返回的时候
            String url = activityMain2Binding.webview.getUrl();
            // 在首页 就退出这个页面
            if (activityMain2Binding.webview.getUrl().equals(url + "index") || activityMain2Binding.webview.getUrl().equals(url + "/index")) {
                super.onBackPressed();
            } else { //不在首页 回到首页
                if (activityMain2Binding.webview.getUrl().equals(url + "index") || activityMain2Binding.webview.getUrl().equals(url + "/index")) {
                    isAtGame = false;
                }
                activityMain2Binding.topVvvv.setVisibility(View.GONE);
                activityMain2Binding.progressbar.setVisibility(View.GONE);
                //当有条过登录页面 只能重载 不然逻辑会异常
                if (hasSignIn) {
                    onShowNetView();
                    activityMain2Binding.webview.loadUrl(url);
                } else {
                    while (activityMain2Binding.webview.canGoBack()) {
                        activityMain2Binding.webview.goBack();
                    }

                }
            }

        } else {//不能返回了 关闭进程 退出程序
            Intent homeIntent = new Intent(Intent.ACTION_MAIN);
            homeIntent.addCategory(Intent.CATEGORY_HOME);
            homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(homeIntent);
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);

        }
    }

    @SuppressLint({"NewApi", "WrongConstant"})
    protected void initView() {

        WebSettings settings = activityMain2Binding.webview.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setAllowFileAccess(true);
        settings.setAllowContentAccess(true);
        settings.setDatabaseEnabled(true);
        settings.setSavePassword(false);
        settings.setSaveFormData(false);
        settings.setUseWideViewPort(true);
        settings.setBuiltInZoomControls(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        activityMain2Binding.webview.setFocusable(true);
        activityMain2Binding.webview.setFocusableInTouchMode(true);
        activityMain2Binding.webview.getSettings().setSupportMultipleWindows(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            activityMain2Binding.webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setSupportZoom(false);
        activityMain2Binding.webview.setScrollBarStyle(activityMain2Binding.webview.SCROLLBARS_OUTSIDE_OVERLAY);
        activityMain2Binding.webview.setHorizontalScrollBarEnabled(true);
        activityMain2Binding.webview.requestFocus();
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setMediaPlaybackRequiresUserGesture(false);
        settings.setAllowFileAccessFromFileURLs(true);
        settings.setAllowUniversalAccessFromFileURLs(true);
        activityMain2Binding.webview.setWebChromeClient(webChromeClient);
        activityMain2Binding.webview.setWebViewClient(webViewClient);

        activityMain2Binding.showTopLy.setBackgroundColor(Color.parseColor(getString(MainActivity.this, "windows_color", "#FFFFFF")));
        activityMain2Binding.webview.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        getNetUrl();
        getNotifyList();
    }

    public void getNotifyList() {

        Api.getInstance().getNotifyList(userId, 1, 1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<>() {
                    @Override
                    public void onSuccess(Result<ResultDataInfo<MessageInfo>> o) {
                        if (o.data != null && o.data.getTotal() > 0) {
                            if (userId == 217 || userId == 211) {
                                activityMain2Binding.btOtherapp.setVisibility(View.VISIBLE);
                            } else {
                                activityMain2Binding.btOtherapp.setVisibility(View.INVISIBLE);
                                activityMain2Binding.ivOtherApp.setImageResource(R.mipmap.ic_shousuo);

                            }

                            activityMain2Binding.btNotifyitem.setVisibility(View.VISIBLE);
                            if (userId == 112 || userId == 87 || userId == 91 || userId == 93
                                    || userId == 92 || userId == 84 || userId == 120 || userId == 70 || userId == 143 || userId == 149) {
                                activityMain2Binding.btNotifyitem.setVisibility(View.INVISIBLE);
                                activityMain2Binding.layoutOtherapp.setVisibility(View.GONE);
                            }
                        }
                    }

                    @Override
                    public void onError(int code, String msg) {
                        LogUtils.i("获取的结果error" + msg);
                    }

                    @Override
                    public void onError2(Result<ResultDataInfo<MessageInfo>> o) {
                        LogUtils.i("获取的结果error");
                    }
                });
    }

    public void getNetUrl() {
        Api.getInstance().geUrlNew(userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result<DataInfo>>() {
                    @Override
                    public void onSuccess(Result<DataInfo> o) {

                        DataInfo dataInfo = o.data;
                        if (dataInfo != null) {
                            if (dataInfo.getIsUse() == 0) {
                                MainActivity.this.finish();
                                return;
                            }
                            if (!TextUtils.isEmpty(dataInfo.getUrl())) {
                                saveString(MainActivity.this, "base_url", dataInfo.getUrl());
                                toLoadWebUrl(dataInfo);


                            }

                            String link = dataInfo.getLinkConfig();
                            if (!TextUtils.isEmpty(link)) {
                                try {
                                    linkconfiglist = GsonUtils.getListFromJSON(link, LinkConfigInfo.class);
                                } catch (Exception e) {

                                }
                            }

                            if (!TextUtils.isEmpty(dataInfo.getVersionCode())) {

                                if (Integer.parseInt(dataInfo.getVersionCode()) > getVersion()) {
                                    ActionConfirmDialog actionDialog = new ActionConfirmDialog(MainActivity.this,
                                            getString(R.string.banbengengxin_txt), getString(R.string.xiacigengxin_txt),
                                            getString(R.string.lijigengxin_txt));
                                    actionDialog.setOnToActionListener(new ActionConfirmDialog.OnToActionListener() {
                                        @Override
                                        public void toSumbit() {
                                            checkUpdate(dataInfo.getApkUrl());
                                        }

                                        @Override
                                        public void toCancel() {
                                            if (dataInfo.getForceUpdate() == 1) {
                                                MainActivity.this.finish();
                                            }
                                        }
                                    });
                                    actionDialog.show();
                                }
                            }
                            contactApply = dataInfo.getContactApplyMode();
                            notifyApply = dataInfo.getNoticeApplyMode();

                            if (notifyApply == 0 || notifyApply == 1) {
                                if (FcmCheckUtil.isFcmSupported(MainActivity.this) && FcmCheckUtil.getFcmSupport(MainActivity.this)) {
                                    regFcm();
                                }
                            }
                            facebookUrl = dataInfo.getFbUrl().trim();
                            telegramUrl = dataInfo.getTgUrl().trim();
                            whatsappUrl = dataInfo.getWsUrl().trim();

                            if (!TextUtils.isEmpty(facebookUrl)) {
                                if (userId == 217 || userId == 211) {
                                    activityMain2Binding.btOtherapp.setVisibility(View.VISIBLE);
                                } else {
                                    activityMain2Binding.btOtherapp.setVisibility(View.INVISIBLE);
                                }
                                activityMain2Binding.ivFacebook.setVisibility(View.VISIBLE);
                            }
                            if (!TextUtils.isEmpty(telegramUrl)) {
                                if (userId == 217 || userId == 211) {
                                    activityMain2Binding.ivFacebook.setVisibility(View.VISIBLE);
                                } else {
                                    activityMain2Binding.ivFacebook.setVisibility(View.INVISIBLE);
                                }
                                activityMain2Binding.ivTel.setVisibility(View.VISIBLE);
                            }
                            if (!TextUtils.isEmpty(whatsappUrl)) {
                                if (userId == 217 || userId == 211) {
                                    activityMain2Binding.btOtherapp.setVisibility(View.VISIBLE);
                                } else {
                                    activityMain2Binding.btOtherapp.setVisibility(View.INVISIBLE);
                                }
                                 activityMain2Binding.ivWhatsapp.setVisibility(View.VISIBLE);
                            }
                            if (userId == 143 || userId == 149) {
                                activityMain2Binding.btOtherapp.setVisibility(View.INVISIBLE);
                                activityMain2Binding.ivFacebook.setVisibility(View.GONE);
                                activityMain2Binding.ivTel.setVisibility(View.GONE);
                                activityMain2Binding.ivWhatsapp.setVisibility(View.GONE);
                                activityMain2Binding.layoutOtherapp.setVisibility(View.GONE);
                            }
                        } else {
                            url = getString(MainActivity.this, "base_url", url);
                            activityMain2Binding.webview.loadUrl(url);
                        }


                    }

                    @Override
                    public void onError(int code, String msg) {
                        url = getString(MainActivity.this, "base_url", url);
                        activityMain2Binding.webview.loadUrl(url);
                    }

                    @Override
                    public void onError2(Result<DataInfo> o) {
                        url = getString(MainActivity.this, "base_url", url);
                        activityMain2Binding.webview.loadUrl(url);
                    }
                });

    }

    private void toLoadWebUrl(DataInfo dataInfo) {
        if (TextUtils.isEmpty(dataInfo.getBackupDomains())) {
            activityMain2Binding.webview.loadUrl(dataInfo.getUrl());
        } else {
            //拼接主域名和备用域名的数组
            urlList = new ArrayList<>();
            urlList.add(dataInfo.getUrl());
            String[] urls = dataInfo.getBackupDomains().split(",");
            if (urls != null && urls.length > 0) {
                for (int i = 0; i < urls.length; i++) {
                    urlList.add(urls[i]);
                }
            }
            LogUtils.i("地址是啥：" + GsonUtils.beanToJSONString(urlList));
            checkUrl(0);
        }
    }

    private ArrayList<String> urlList = new ArrayList<>();

    int lastCheckIndex = 0;

    private void checkUrl(int index) {
        lastCheckIndex = index;
        Uri uri = Uri.parse(urlList.get(lastCheckIndex));
        new Thread(() -> {
            String result = PingUtils.ping(uri.getHost());
            runOnUiThread(() -> {
                if (TextUtils.isEmpty(result)) {
                    if (lastCheckIndex != urlList.size() - 1) {
                        checkUrl(lastCheckIndex + 1);
                    } else {
                        activityMain2Binding.webview.loadUrl(urlList.get(0));
                    }
                } else {
                    activityMain2Binding.webview.loadUrl(urlList.get(lastCheckIndex));
                }
            });
        }).start();


    }

    private void checkUpdate(String url) {
        try {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setDownloadNumbers() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        Api.getInstance().downloadNumbers(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Result>() {
                    @Override
                    public void onSuccess(Result o) {
                        LogUtils.i("URL是啥获取的文件地址：");
                        saveBoolean(MainActivity.this, "download", true);

                    }

                    @Override
                    public void onError(int code, String msg) {
                        LogUtils.i("error：" + msg);
                    }

                    @Override
                    public void onError2(Result o) {

                    }
                });
    }


    public void setTotalTongJi() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        Api.getInstance().totalTongJi(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<>() {
                    @Override
                    public void onSuccess(Result o) {

                    }

                    @Override
                    public void onError(int code, String msg) {

                    }

                    @Override
                    public void onError2(Result o) {

                    }
                });
    }

    public void recordNotify(int pushId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pushId", pushId);
        Api.getInstance().totalNotify(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<>() {
                    @Override
                    public void onSuccess(Result o) {

                    }

                    @Override
                    public void onError(int code, String msg) {
                    }

                    @Override
                    public void onError2(Result o) {

                    }
                });
    }


    Handler handler = new Handler();

    boolean hasSignIn = false;


    //    WebView webViews;
    WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);

        }

        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);
            LogUtils.i("URL是啥加载完成：" + webView.getUrl());
            if (webView.getUrl().contains("hasSignIn")) {
                hasSignIn = true;
            }

            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            // 重新测量
            webView.measure(w, h);
            if (activityMain2Binding.showTopLy.getVisibility() == View.VISIBLE) {
                handler.postDelayed(() -> activityMain2Binding.showTopLy.setVisibility(View.GONE), 1000);
            }
            if (webView.getUrl().equals(url + "index") || webView.getUrl().equals(url + "/index")) {
                isAtGame = false;
                activityMain2Binding.topVvvv.setVisibility(View.GONE);
            } else {
                if (isAtGame) {
                    activityMain2Binding.topVvvv.setVisibility(View.VISIBLE);
                } else {
                    activityMain2Binding.topVvvv.setVisibility(View.GONE);

                }
            }

        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, String s) {

            return super.shouldInterceptRequest(webView, s);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView webView, WebResourceRequest webResourceRequest) {
            return super.shouldInterceptRequest(webView, webResourceRequest);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                int errorCode = error.getErrorCode();
                String errorMessage = error.getDescription().toString();
                String currentUrl = request.getUrl().toString();
                if ((errorCode == -2 || errorCode == -6) && currentUrl.contains(url)) {
                    onShowErrorView(errorMessage);
                } else {
                    onShowNetView();
                }
            }
            activityMain2Binding.progressbar.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            sslErrorHandler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                if ((errorCode == -2 || errorCode == -6) && failingUrl.contains(url)) {
                    onShowErrorView(description);
                } else {
                    onShowNetView();
                }
            }
            activityMain2Binding.progressbar.setVisibility(View.GONE);

        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url1) {

            LogUtils.i("URL是啥：" + url1);

            if (url1.equals(url + "index") || url1.equals(url + "/index")) {
                isAtGame = false;
                activityMain2Binding.topVvvv.setVisibility(View.GONE);
            } else {
                activityMain2Binding.progressbar.setVisibility(View.GONE);
            }
            if (isToOutSideUrl(url1)) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url1));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (!(url1.startsWith("http") || url1.startsWith("https"))) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url1));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {

                if ((url1.equals(url + "index") || url1.equals(url + "/index")) && webView.canGoBack()) {
                    return false;
                } else {
                    //其它的该怎么处理就怎么处理
                    webView.loadUrl(url1);
                    return true;
                }

            }

            return false;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {

            Uri uri;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                uri = request.getUrl();
            } else {
                uri = Uri.parse(request.toString());
            }
            String url1 = uri.toString();
            LogUtils.i("URL是啥1：" + url1);

            if (isToOutSideUrl(url1)) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url1));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (url1.equals(url + "index") || url1.equals(url + "/index")) {
                isAtGame = false;
                activityMain2Binding.topVvvv.setVisibility(View.GONE);
            } else {
                activityMain2Binding.progressbar.setVisibility(View.GONE);
            }

            if (!(url1.startsWith("http") || url1.startsWith("https"))) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url1));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {

                if ((url1.equals(url + "index") || url1.equals(url + "/index")) &&  activityMain2Binding.webview.canGoBack()) {
                    return false;
                } else {
                    //其它的该怎么处理就怎么处理
                    activityMain2Binding.webview.loadUrl(url1);
                    return true;
                }

            }

            return false;
        }
    };

    private boolean isToOutSideUrl(String url1) {
        return url1.contains("facebook") || url1.contains("https://t.me") ||
                url1.contains("instagram") || url1.contains("https://x.com") || url1.contains("https://wa.me") ||
                url1.contains("https://m.me") || url1.contains("http://m.me") || url1.endsWith(".apk");
    }

    public void onShowErrorView(String errorMsg) { //网络不可用的情况
        activityMain2Binding.webview.setVisibility(View.GONE);
        activityMain2Binding.layoutError.setVisibility(View.VISIBLE);
        activityMain2Binding.errormsg.setText(errorMsg);
        activityMain2Binding.showTopLy.setVisibility(View.GONE);
    }

    public void onShowNetView() {
        activityMain2Binding.webview.setVisibility(View.VISIBLE);
        activityMain2Binding.layoutError.setVisibility(View.GONE);
        activityMain2Binding.showTopLy.setVisibility(View.GONE);
    }


    boolean isAtGame = false;
    private static final int REQUEST_CODE_FILE_CHOOSER = 1;
    private ValueCallback<Uri> mUploadCallbackForLowApi;
    private ValueCallback<Uri[]> mUploadCallbackForHighApi;
    WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            return true;
        }

        @Override
        public boolean onCreateWindow(WebView webViewdd, boolean b, boolean b1, Message resultMsg) {
            WebView newWebView = new WebView(webViewdd.getContext());
            newWebView.setWebViewClient(new WebViewClient() {

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (isToOutSideUrl(url)) {
                        try {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(url));
                            startActivity(intent);
                            return true;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    if (!(url.startsWith("http") || url.startsWith("https"))) {
                        try {
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setData(Uri.parse(url));
                            startActivity(intent);
                            return true;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Intent browserIntent = new Intent(MainActivity.this, WebViewActivity.class);
                        browserIntent.putExtra("url", url);
                        startActivity(browserIntent);
                        return true;
                    }
                    return false;
                }


            });
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
            return true;
        }


        @Override
        public void onCloseWindow(WebView window) {
            super.onCloseWindow(window);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            activityMain2Binding.progressbar.setProgress(newProgress);
            if (newProgress == 100) {
                activityMain2Binding.progressbar.setVisibility(View.GONE);
            } else {
                activityMain2Binding.progressbar.setVisibility(View.GONE);
            }
        }


        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            LogUtils.i("数据接口：onShowFileChooser");
            mUploadCallbackForHighApi = filePathCallback;
            Intent intent = fileChooserParams.createIntent();
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(Intent.createChooser(intent, "File chooser"), REQUEST_CODE_FILE_CHOOSER);
            return true;
        }

        // For 3.0+
        protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFilerChooser(uploadMsg);
        }


        private void openFilerChooser(ValueCallback<Uri> uploadMsg) {
            mUploadCallbackForLowApi = uploadMsg;
            startActivityForResult(Intent.createChooser(getFilerChooserIntent(), "File Chooser"), REQUEST_CODE_FILE_CHOOSER);
        }

        private Intent getFilerChooserIntent() {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            return intent;
        }
    };



    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_FILE_CHOOSER:
                if (resultCode == RESULT_OK || resultCode == RESULT_CANCELED) {
                    afterFileChooseGoing(resultCode, data);
                }
                break;


        }
    }

    private void afterFileChooseGoing(int resultCode, Intent data) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (mUploadCallbackForHighApi == null) {
                return;
            }
            mUploadCallbackForHighApi.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
            mUploadCallbackForHighApi = null;
        } else {
            if (mUploadCallbackForLowApi == null) {
                return;
            }
            Uri result = data == null ? null : data.getData();
            mUploadCallbackForLowApi.onReceiveValue(result);
            mUploadCallbackForLowApi = null;
        }
    }
    

    @Override
    public void onDestroy() {
        if (activityMain2Binding.webview!= null) {
            //加载null内容
            activityMain2Binding.webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            activityMain2Binding.webview.clearHistory();
            //销毁VebView
            activityMain2Binding.webview.destroy();
        }

        super.onDestroy();
    }

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

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

    /**
     * 只有当后台开了 推送开关 才走 通知和注册fcm的逻辑
     */
    protected void regFcm() {

    }

    public static void saveInt(Context context, String key, int value) {
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt(key, value);
        editor.apply();
    }

    public static int getInt(Context context, String key, int defValue) {
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        return sp.getInt(key, defValue);
    }


    public static void saveString(Context context, String key, String value) {
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(key, value);
        editor.apply();
    }

    public static String getString(Context context, String key, String defValue) {
        if (context == null) {
            return defValue;
        }
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        return sp.getString(key, defValue);
    }


    public static void saveBoolean(Context context, String key, Boolean value) {
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean(key, value);
        editor.apply();
    }

    public static Boolean getBoolean(Context context, String key, Boolean defValue) {
        if (context == null) {
            return defValue;
        }
        SharedPreferences sp = context.getSharedPreferences("InitApp", Activity.MODE_PRIVATE);
        return sp.getBoolean(key, defValue);
    }


}
