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.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.ruiwenliu.wrapper.SPConstance;
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);
    }

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

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            WebResourceResponse response = super.shouldInterceptRequest(view, request);
            return response;
        }
    };

    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())) {
                Intent intent = LoginRvActivity.getIntent(getContext(),1) ;
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ;
                getContext().startActivity(intent);
                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");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ;
            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, TextUtils.isEmpty(desc) ? " " : desc);
            }
        }

        /*******
         * @param url
         *          跳转url
         * @param imgUrl
         *          活动图片url
         * @param title
         *          标题
         * @param titleCircle
         *        朋友圈标题
         * @param desc
         *          描述
         */
        @JavascriptInterface
        public void share(String url, String imgUrl, String title, String titleCircle, String desc) {
            if (listener != null) {
                listener.share(url, imgUrl, title, titleCircle, TextUtils.isEmpty(desc) ? " " : desc);
            }
        }

        @JavascriptInterface
        public void showShareIcon(String url, String imgUrl, String title, String titleCircle, String desc) {
            if (listener != null) {
                listener.showShareIcon(url, imgUrl, title, titleCircle, TextUtils.isEmpty(desc) ? " " : desc);
            }
        }


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

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

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

        @JavascriptInterface
        public String getUkID() {
            return OkGoUtil.getYkId();
        }

    }

    public interface WebViewListener {

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

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

        void finish();

        void showShareIcon(String url, String imgUrl, String title, String circleTitle, String desc);
    }

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

}
