package com.rdiot.yx485.webview;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.king.zxing.util.LogUtils;
import com.rdiot.yx485.BaseActivity;
import com.rdiot.yx485.databinding.ActivityWebViewBinding;
import com.rdiot.yx485.util.DialogUtils;
import com.rdiot.yx485.util.LocalCache;

/**
 * @author admin
 */
public class WebViewActivity extends BaseActivity {
    private ActivityWebViewBinding mBinding;
    private String mUrl;
    private String mRichText;
    private Dialog mLoadingDialog;

    public static void newIntent(Context context, String url, String richText) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("richText", richText);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = ActivityWebViewBinding.inflate(getLayoutInflater());
        setContentView(mBinding.getRoot());

        initData();
        initView();
    }

    private void initData() {
        mUrl = getIntent().getStringExtra("url");
        mRichText = getIntent().getStringExtra("richText");
        LogUtils.d(String.format("url=%s; richText=%s", mUrl, mRichText));
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initView() {
        // 创建加载弹窗
        mLoadingDialog = DialogUtils.createLoadingDialog(this, "加载中...");
        mBinding.webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                // 开始加载时显示加载弹窗
                if (mLoadingDialog != null && !mLoadingDialog.isShowing()) {
                    mLoadingDialog.show();
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 加载完成时关闭加载弹窗
                if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
                    mLoadingDialog.dismiss();
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                String s = request.getUrl().getScheme();
                if (TextUtils.isEmpty(s)) {
                    return super.shouldOverrideUrlLoading(view, request);
                }

                if (s != null && s.contains("http")) {
                    view.loadUrl(request.getUrl().toString());
                }
                return super.shouldOverrideUrlLoading(view, request);
            }
        });

        mBinding.webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                Log.d("TAG", "onConsoleMessage: " + consoleMessage.message() + " " + consoleMessage.messageLevel());
                return true;
            }
        });
        mBinding.webView.addJavascriptInterface(new WebAppInterface(), "Android");
        WebSettings webSettings = mBinding.webView.getSettings();
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 允许跨域访问（仅限调试环境）
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportMultipleWindows(true);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setPluginState(WebSettings.PluginState.ON);
        webSettings.setDomStorageEnabled(true);
        WebView.setWebContentsDebuggingEnabled(true);

        if (!TextUtils.isEmpty(mUrl)) {
            mBinding.webView.loadUrl(mUrl);
            return;
        }

        if (!TextUtils.isEmpty(mRichText)) {
            mRichText = mRichText.replace("<img", "<img style=\"max-width:100%;height:auto\"");
            mBinding.webView.loadDataWithBaseURL(null, mRichText, "text/html", "utf-8", null);
        }
    }

    @Override
    public void onBackPressed() {
        if (mBinding.webView.canGoBack()) {
            mBinding.webView.goBack();
            return;
        }

        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保在Activity销毁时关闭加载弹窗
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    // 定义一个接口类
    public class WebAppInterface {

        @JavascriptInterface
        public void closeH5() {
            System.out.println("closeH5");
            finish();
        }

        // 提供一个有返回值的方法
        @JavascriptInterface
        public String getToken() {
            String token = LocalCache.getToken();
            System.out.println("getToken: " + token);
            return token;
        }
    }
}
