package com.rv.share.view;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
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 android.widget.ProgressBar;

import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.rv.component.utils.Cookie;
import com.rv.component.utils.LogUtil;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.yuyife.okgo.OkGoUtil;

import static com.ruiwenliu.wrapper.weight.webview.SafeWebView.hasKitkat;

public class RvWebView extends WebView {

    private ProgressBar progressBar;
    private WebViewListener listener;

    public RvWebView(Context context, WebViewListener listener) {
        super(context);
        this.listener = listener;
        progressBar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressBar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 3));//设置宽高属性
        addView(progressBar);
        initWebview();
    }

    private void initWebview() {
        WebSettings webSettings = getSettings();
        if (webSettings == null) return;
        // 支持 Js 使用
        webSettings.setJavaScriptEnabled(true);
        // 开启DOM缓存,默认状态下是不支持LocalStorage的
        webSettings.setDomStorageEnabled(true);
        // 开启数据库缓存
        webSettings.setDatabaseEnabled(true);
        // 支持自动加载图片
        webSettings.setLoadsImagesAutomatically(hasKitkat());
        // 设置 WebView 的缓存模式
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        // 支持启用缓存模式
        webSettings.setAppCacheEnabled(true);
        // 设置 AppCache 最大缓存值(现在官方已经不提倡使用，已废弃)
//        webSettings.setAppCacheMaxSize(8 * 1024 * 1024);
        // Android 私有缓存存储，如果你不调用setAppCachePath方法，WebView将不会产生这个目录
        webSettings.setAppCachePath(getContext().getCacheDir().getAbsolutePath());
        // 数据库路径
//        if (!hasKitkat()) {
//            webSettings.setDatabasePath(getDatabasePath("html").getPath());
//        }
        // 关闭密码保存提醒功能
//        webSettings.setSavePassword(false);
        // 支持缩放
        webSettings.setSupportZoom(true);
        // 设置 UserAgent 属性
        webSettings.setUserAgentString("");
        // 允许加载本地 html 文件/false
        webSettings.setAllowFileAccess(true);
        // 允许通过 file url 加载的 Javascript 读取其他的本地文件,Android 4.1 之前默认是true，在 Android 4.1 及以后默认是false,也就是禁止
        webSettings.setAllowFileAccessFromFileURLs(true);
        // 允许通过 file url 加载的 Javascript 可以访问其他的源，包括其他的文件和 http，https 等其他的源，
        // Android 4.1 之前默认是true，在 Android 4.1 及以后默认是false,也就是禁止
        // 如果此设置是允许，则 setAllowFileAccessFromFileURLs 不起做用
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        addJavascriptInterface(new AndroidJs(), "AndroidJs");
        setWebViewClient(webViewClient);
        setWebChromeClient(webChromeClient);
    }

    public WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }
    };

    public WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            LogUtil.d("h5", consoleMessage.message() + ";" + consoleMessage.sourceId() + ";" + consoleMessage.lineNumber());
            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                progressBar.setProgress(newProgress);//设置进度值
            }
        }
    };

    private class AndroidJs {
        @JavascriptInterface
        public String getToken() {
            String token = OkGoUtil.getToken();
            return token;
        }

        @JavascriptInterface
        public String getTokenOrLogin() {
            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                getContext().startActivity(LoginRvActivity.getIntent(getContext()));
                return "";
            }
            return OkGoUtil.getToken();
        }

        @JavascriptInterface
        public void toMyCoupons() {
            ComponentName name = new ComponentName(getContext(), "com.xxfc.rv.MainActivity");
            Intent intent = new Intent();
            intent.setComponent(name);
            intent.putExtra("to", "mine_coupons");
            getContext().startActivity(intent);
        }

        @JavascriptInterface
        public String getUserName() {
            String name = Cookie.getStringValue(getContext(), SPConstance.USER_JSON_NAME, "");
            return name;
        }

        @JavascriptInterface
        public String getHeadUrl() {
            String url = Cookie.getStringValue(getContext(), SPConstance.USER_JSON_HEADERURL, "");
            return url;
        }

        @JavascriptInterface
        public void share(String url, String title, String desc) {
            if (listener != null) {
                listener.share(url, title, desc);
            }
        }

        @JavascriptInterface
        public void toMyWallet() {

        }

        @JavascriptInterface
        public String getCode() {
            String code = Cookie.getStringValue(getContext(), "my_code", "");
            return code;
        }

        @JavascriptInterface
        public void finish() {
            listener.finish();
        }

    }

    public interface WebViewListener {

        void share(String url, String title, String desc);

        void finish();
    }

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

}
