package cn.zhios.zhiying_base_widget_example;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
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 com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.baichuan.trade.biz.core.taoke.AlibcTaokeParams;
import com.alibaba.baichuan.trade.biz.login.AlibcLogin;
import com.alibaba.baichuan.trade.biz.login.AlibcLoginCallback;

import java.util.HashMap;
import java.util.Map;

public class WebActivity extends Activity {
    WebView mainWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_bc);
        mainWeb = findViewById(R.id.webview_main);
        mainWeb.getSettings().setJavaScriptEnabled(true);
        mainWeb.getSettings().setDomStorageEnabled(true);
        mainWeb.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        mainWeb.getSettings().setLoadWithOverviewMode(true);
        mainWeb.getSettings().setAllowFileAccess(true);
        mainWeb.getSettings().setDatabaseEnabled(true);
        MyWebClient myWebClient = new MyWebClient();
        MyWebChromeClient myWebChromeClient = new MyWebChromeClient();
        mainWeb.setWebViewClient(myWebClient);
        mainWeb.setWebChromeClient(myWebChromeClient);

        Map<String, String> exParams = new HashMap<>();//yhhpass参数
//                AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams("", "", "");
//                alibcTaokeParams.pid = SPUtils.getPrefString(mActivity, Pkey.pid, "");
//                alibcTaokeParams.adzoneid = SPUtils.getPrefString(mActivity, Pkey.APP_adzoneId, "");
//                alibcTaokeParams.extraParams = new HashMap<>();
//                alibcTaokeParams.extraParams.put("taokeAppkey", SPUtils.getPrefString(mActivity, Pkey.APP_alliance_appkey, ""));
        AlibcShowParams showParams = new AlibcShowParams();
        showParams.setBackUrl("alisdk://");
        AlibcTrade.openByUrl(WebActivity.this, "", "http://www.izhim.com/comm/tb_callback.php?_ctrl=domain&domain_state=MTI2&domain_return_url=aHR0cDovLzE5Mi4xNjguMC4xMTM6NTAwMC9hcGkvdjEvdGFvYmFvL2F1dGgvY2FsbGJhY2s%2FdGltZT0xNjAyNDk4MjA3",
                mainWeb, new MyBaichuanWebClient(), new MyWebChromeClient(), showParams,
                new AlibcTaokeParams("", "", ""), exParams, new AlibcTradeCallback() {
                    @Override
                    public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
    }

    //用于百川授权的简化的WebClient
    @SuppressLint("AddJavascriptInterface")
    private class MyBaichuanWebClient extends WebViewClient {
        @SuppressLint("AddJavascriptInterface")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            Log.d("百川拦截", url);
            //绑定会员关系时获取网页内容关闭网页
            if (url.contains("comm/tbredirect.php") && !url.contains("oauth.m.taobao.com") && url.contains("track_id")) {
                Log.d("百川系时获取网页内容关闭网页", url);
                mainWeb.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");

            }
            if (url.contains("oauth.taobao.com/authorize") || url.contains("oauth.m.taobao.com/authorize")) {
                //渠道授权改动测试
                Log.d("百川渠道授权改动测试", url);
                Map<String, String> exParams = new HashMap<>();//yhhpass参数
                AlibcShowParams showParams = new AlibcShowParams();
                showParams.setBackUrl("alisdk://");
                AlibcTrade.openByUrl(WebActivity.this, "", url,
                        mainWeb, new MyBaichuanWebClient(), new MyWebChromeClient(), showParams,
                        new AlibcTaokeParams("", "", ""), exParams, new AlibcTradeCallback() {
                            @Override
                            public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {
                                Log.d("cg", alibcTradeResult.toString());
                            }

                            @Override
                            public void onFailure(int i, String s) {
                                Log.d("sb", s);
                            }
                        });
            }
            return super.shouldOverrideUrlLoading(view, url);
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // WebLoad.setVisibility(View.GONE);
            mainWeb.setVisibility(View.GONE);
            //开始加载设置为透明
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // WebLoad.setVisibility(View.GONE);
            mainWeb.setVisibility(View.VISIBLE);
            // 获取页面内容
            view.loadUrl("javascript:window.java_obj.showSource("
                    + "document.documentElement.innerText);");

            // 获取解析<meta name="share-description" content="获取到的值">
            view.loadUrl("javascript:window.java_obj.showDescription("
                    + "document.querySelector('meta[name=\"share-description\"]').getAttribute('content')"
                    + ");");
            // quanyikaText();
            super.onPageFinished(view, url);
        }

        //处理 [Android]用WebView访问证书有问题的SSL网页
        //http://blog.sina.com.cn/s/blog_4cd978f90102vrxk.html
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

    }

    /**
     * 绑定渠道
     */
    private final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void showSource(final String html) {
            //获取网页内容，用于判断是否成功绑定关系id

            try {
                if (html.contains("成功")) {//成功
                    Toast.makeText(WebActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {//失败
                    mainWeb.setAlpha(0);

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void showDescription(String str) {


        }
    }


    public class MyWebChromeClient extends WebChromeClient {

        private CustomViewCallback mCustomViewCallback;
        //  横屏时，显示视频的view
        private View mCustomView;

        // 点击全屏按钮时，调用的方法
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            //isFullPlayVedio = true;
            //如果view 已经存在，则隐藏
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }

            mCustomView = view;
            mCustomView.setVisibility(View.VISIBLE);
            mCustomViewCallback = callback;


        }

        // 取消全屏调用的方法
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();

            if (mCustomView == null) {
                return;
            }
            mCustomView.setVisibility(View.GONE);

            mCustomView = null;

            try {
                mCustomViewCallback.onCustomViewHidden();
            } catch (Exception e) {
            }
//            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏


        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
//            Logger.wtf("我的url" + view.getUrl());
            String url = view.getUrl();
            if (Patterns.WEB_URL.matcher(title).matches()) {
                //网址不显示为标题

            } else {

                //不是网址
                if (!url.contains("api.ejiayou.com/pages/platform/soulList/index.html")) {

                }
            }
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {


            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }


        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {


        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, "");
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {

            openFileChooser(uploadMsg, acceptType);
        }

        // For Android > 5.0
        @Override
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> filePathCallback,
                                         FileChooserParams fileChooserParams) {

            return true;
        }


    }

    @SuppressLint("AddJavascriptInterface")
    private class MyWebClient extends WebViewClient {

        @SuppressLint("AddJavascriptInterface")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {

            if (url.startsWith("tel:")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
            if (url.startsWith("bdnetdisk:")) {
                return true;
            }


            if (url.contains("tmast://")) {
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {

                }
                return true;
            }
            if (url.startsWith("http://ditu.amap.com") ||
                    url.startsWith("https://ditu.amap.com")) {
                return true;
            }
            if (url.contains("oauth.taobao.com/authorize") || url.contains("oauth.m.taobao.com/authorize")) {

//                mainWeb.addJavascriptInterface(new InJavaScriptLocadeUpgralObj(), "java_obj");
                Map<String, String> exParams = new HashMap<>();//yhhpass参数
//                AlibcTaokeParams alibcTaokeParams = new AlibcTaokeParams("", "", "");
//                alibcTaokeParams.pid = SPUtils.getPrefString(mActivity, Pkey.pid, "");
//                alibcTaokeParams.adzoneid = SPUtils.getPrefString(mActivity, Pkey.APP_adzoneId, "");
//                alibcTaokeParams.extraParams = new HashMap<>();
//                alibcTaokeParams.extraParams.put("taokeAppkey", SPUtils.getPrefString(mActivity, Pkey.APP_alliance_appkey, ""));
                AlibcShowParams showParams = new AlibcShowParams();
                showParams.setBackUrl("alisdk://");
                AlibcTrade.openByUrl(WebActivity.this, "", url, mainWeb, new MyBaichuanWebClient(), new MyWebChromeClient(), showParams,
                        new AlibcTaokeParams("", "", ""), exParams, new AlibcTradeCallback() {
                            @Override
                            public void onTradeSuccess(AlibcTradeResult alibcTradeResult) {

                            }

                            @Override
                            public void onFailure(int i, String s) {

                            }
                        });
            }

            if (url.contains("tbopen://") || url.contains("tmall://") || url.contains("taobaotravel://")) {
                return true;
            }


            if (url.contains("dianping://")) {
                return true;
            }
            if (url.contains("aliim:")) {
                return true;
            }
            if (url.contains("?mod=appapi&act=miandan_course&ctrl=close")) {
                finish();
                return true;
            }
            if (url.contains("vipma.net/quickapp.html?")) {
                return true;
            }


            // 如下方案可在非微信内部WebView的H5页面中调出微信支付
            if (url.startsWith("weixin://wap/pay?")) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();

                }
                return true;
            }
            if (url.startsWith("weixin://")) {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();

                }
                return true;
            }
            if (url.endsWith("native://wechat")) {
                Intent intent = new Intent();
                ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
                intent.setAction(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_LAUNCHER);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setComponent(cmp);
                startActivity(intent);
                return true;
            }
            if (url.contains("navite://save#")) {

            }
            //不拦截的话绑定淘宝关系id的时候会因为下面login.m.taobao.com的拦截而唤醒手淘授权之后导致不能切换帐号
//            if (url.contains("client_id") && url.contains("login.m.taobao.com/logout.htm?")) {
//                view.loadUrl(url);
//                return true;
//            }
            if (url.contains("client_id")) {
                view.loadUrl(url);
                return true;
            }
//            if (url.contains("login.m.taobao.com")) {
//                if (!AlibcLogin.getInstance().isLogin()) {
//                    AlibcLogin.getInstance().showLogin(new AlibcLoginCallback() {
////                        @Override
////                        public void onSuccess(int i) {
////                        }
//
//                        @Override
//                        public void onSuccess(int i, String s, String s1) {
//
//                        }
//
//                        @Override
//                        public void onFailure(int i, String s) {
//                        }
//                    });
//                }
//                return true;
//            }
            if (url.contains("maliprod.alipay.com") && !url.contains("confirmGoods.do")) {
                AlibcLogin.getInstance().showLogin(new AlibcLoginCallback() {
                    @Override
                    public void onSuccess(int i, String s, String s1) {

                    }

                    @Override
                    public void onFailure(int i, String s) {

                    }
                });
            }

            if (url.contains("intent://go/ju/webview?")) {
                return true;
            }
//            if (url.contains("s.click.taobao.com")) {
//                Logger.wtf(SPUtils.getPrefString(WebActivity.this, Pkey.IS_OPEN_TAOBAO, ""));
//                if (SPUtils.getPrefString(WebActivity.this, Pkey.IS_OPEN_TAOBAO, "").equals("shoutao")) {
//                    if (!Token.isLogin()) {
//                        if (isFirst2Login) {
//                            ActivityJump.toLogin(WebActivity.this);
//                        }
//                        isFirst2Login = false;
//                        finish();
//                    } else {
//                        if (isInstallTaoBao(WebActivity.this)) {
//                            jump2TaoBao(url);
//                            finish();
//                        } else {
//                            view.loadUrl(url);
//                        }
//                    }
//                    return true;
//                }
//            }


//            if (url.contains("kingcard.dgunicom.com") && url.contains("newMsg") && url.contains("fill.html")) {
//                getItf(url);
//            }


//            else {
//                Logger.wtf("123");
//                mainWeb.loadUrl(url);
//            }
            return super.shouldOverrideUrlLoading(view, url);
        }


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // WebLoad.setVisibility(View.GONE);
            //开始加载设置为透明
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            // WebLoad.setVisibility(View.GONE);
//			// 获取页面内容
            view.loadUrl("javascript:window.java_obj.showSource("
                    + "document.documentElement.innerText);");

            // 获取解析<meta name="share-description" content="获取到的值">
            view.loadUrl("javascript:window.java_obj.showDescription("
                    + "document.querySelector('meta[name=\"share-description\"]').getAttribute('content')"
                    + ");");
            //  quanyikaText();
            super.onPageFinished(view, url);
        }

        //处理 [Android]用WebView访问证书有问题的SSL网页
        //http://blog.sina.com.cn/s/blog_4cd978f90102vrxk.html
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

    }

}


