package com.webclip.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.webclip.base.databinding.ActivityMain2Binding;

public class WebViewActivity extends AppCompatActivity {
    ActivityMain2Binding activityMain2Binding;
    private String url;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setNavigationBarColor(getColor(R.color.white));
        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);
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        activityMain2Binding = ActivityMain2Binding.inflate(getLayoutInflater());
        setContentView(activityMain2Binding.getRoot());
        activityMain2Binding.backIv.setOnClickListener(view -> finish());
        url = getIntent().getStringExtra("url");
        initView();
    }

    private ValueCallback<Uri[]> mUploadCallbackForHighApi;

    public void initView() {
        WebSettings settings = activityMain2Binding.webview.getSettings();
        settings.setDomStorageEnabled(true);
//        settings.setAppCacheEnabled(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(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        activityMain2Binding.webview.setHorizontalScrollBarEnabled(true);
        activityMain2Binding.webview.requestFocus();
        settings.setJavaScriptCanOpenWindowsAutomatically(false);
        // Android 4.1前默认允许，4.1后默认禁止
        settings.setAllowFileAccessFromFileURLs(true);
        // Android 4.1前默认允许，4.1后默认禁止
        settings.setAllowUniversalAccessFromFileURLs(true);



        activityMain2Binding.webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

                WebView newWebView = new WebView(WebViewActivity.this);
                activityMain2Binding.topVvvv.setVisibility(View.VISIBLE);
                activityMain2Binding.webview.addView(newWebView);
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                transport.setWebView(newWebView);
                resultMsg.sendToTarget();

                newWebView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        activityMain2Binding.progressbar.setVisibility(View.GONE);
                        activityMain2Binding.webview.loadUrl(url);
                        return true;
                    }
                });

                return true;
            }


            @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) {
                LogUtils.i("数据接口：openFileChooseracceptType");
                openFilerChooser(uploadMsg);
            }


            private void openFilerChooser(ValueCallback<Uri> uploadMsg) {
                LogUtils.i("数据接口：openFileChooser");
                mUploadCallbackForLowApi = uploadMsg;
                startActivityForResult(Intent.createChooser(getFilerChooserIntent(), "File Chooser"), REQUEST_CODE_FILE_CHOOSER);
            }



        });
        activityMain2Binding.webview.setWebViewClient(new WebViewClient() {


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                activityMain2Binding.showTopLy.setVisibility(View.GONE);
                activityMain2Binding.progressbar.setVisibility(View.GONE);
                activityMain2Binding.topVvvv.setVisibility(View.VISIBLE);

            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                activityMain2Binding.progressbar.setVisibility(View.VISIBLE);
                activityMain2Binding.topVvvv.setVisibility(View.VISIBLE);
            }

            @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();
                    LogUtils.d("onReceivedError2  url==" + url + "  errorCode ==" + errorCode);
                    if ((errorCode == -2 || errorCode == -6) && currentUrl.contains(url)) {
                        onShowErrorView(errorMessage);
                    } else {
                        onShowNetView();
                    }
                }
                activityMain2Binding.topVvvv.setVisibility(View.GONE);
            }

            @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) {
                    LogUtils.d("onReceivedError2  url==" + failingUrl + "  errorCode ==" + errorCode);
                    if ((errorCode == -2 || errorCode == -6) && failingUrl.contains(url)) {
                        onShowErrorView(description);
                    } else {
                        onShowNetView();
                    }
                }
                activityMain2Binding.topVvvv.setVisibility(View.GONE);

            }


            @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();
                if (url1.equals(url + "index") || url1.equals(url + "/index")) {
                    activityMain2Binding.topVvvv.setVisibility(View.GONE);
                } else {
                    activityMain2Binding.topVvvv.setVisibility(View.VISIBLE);
                }

                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 {
                        if (url1.contains(".apk")) {  //下载
                            Toast.makeText(WebViewActivity.this, "下载开始，请稍后...", Toast.LENGTH_SHORT).show();
                            checkUpdate(url1);
                            return false;
                        }
                        //其它的该怎么处理就怎么处理
                        activityMain2Binding.webview.loadUrl(url1);
                        return true;
                    }

                }
                return false;
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url1) {
                if (url1.equals(url + "index") || url1.equals(url + "/index")) {
                    activityMain2Binding.topVvvv.setVisibility(View.GONE);
                } else {
                    activityMain2Binding.progressbar.setVisibility(View.VISIBLE);
                }

                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 {
                        if (url1.contains(".apk")) {  //下载
                            checkUpdate(url1);
                            return false;
                        }
                        //其它的该怎么处理就怎么处理
                        activityMain2Binding.webview.loadUrl(url1);
                        return false;
                    }

                }

                return false;
            }


        });
        activityMain2Binding.webview.setOnGenericMotionListener(new View.OnGenericMotionListener() {
            @Override
            public boolean onGenericMotion(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        if (url != null) {
            activityMain2Binding.webview.loadUrl(url);
        }
    }


    @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;


        }
    }


    /**
     * onActivityResult方法
     */

    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;
        }
    }



    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();
        }
    }

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


    private static final int REQUEST_CODE_FILE_CHOOSER = 1;
    private ValueCallback<Uri> mUploadCallbackForLowApi;
    private boolean isNetError = false;

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

    }

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


    @Override
    public void onBackPressed() {
        if (activityMain2Binding.webview.canGoBack()) {//当webview有多级能返回的时候
            onShowNetView();
            activityMain2Binding.webview.goBack();
        } else {//不能返回了
            WebViewActivity.this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        if (activityMain2Binding.webview != null) {
            //销毁VebView
            activityMain2Binding.webview.destroy();
        }
        super.onDestroy();
    }
}
