package com.navinfo.outdoor.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.navinfo.outdoor.R;
import com.navinfo.outdoor.api.UserApplication;
import com.navinfo.outdoor.base.BaseActivity;
import com.gyf.immersionbar.ImmersionBar;

import java.util.ArrayList;

/**
 * 详情页
 */
public class WebActivity extends BaseActivity implements View.OnClickListener {

    private ImageView ivIcon;
    private WebView nWebView;
    private String content = "<div>\n" +
            "<a>测试</a>\n" +
            "\n" +
            "<p>\n" +
            "\t<img  src=\"https://exp-picture.cdn.bcebos.com/560be432939c2cf72dff4caa452c5b1b1fde12e1.jpg?x-bce-process=image%2Fresize%2Cm_lfit%2Cw_500%2Climit_1%2Fformat%2Cf_jpg%2Fquality%2Cq_80\">\n" +
            "</p>\n" +
            "\n" +
            "<p style=\"color: red; margin-left: 20px\">&lt;style&gt; 标签用于为 HTML 文档定义样式信息。</p>\n" +
            "\n" +
            "<p style=\"background-color: lightblue; margin-left: 20px\">在 style 中，您可以规定在浏览器中如何呈现 HTML 文档。</p>\n" +
            "\n" +
            "<p style=\"font-family: verdana; margin-left: 20px\">type 属性是必需的，定义 style 元素的内容。唯一可能的值是 \"text/css\"。</p>\n" +
            "\n" +
            "<p style=\"font-size: 20px; margin-left: 20px\">style 元素位于 head 部分中。</p>\n" +
            "</div>";
    @Override
    protected int getLayout() {
        return R.layout.activity_web;
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                //原理：如果当前设备支持状态栏字体变色，会设置状态栏字体为黑色，如果当前设备不支持状态栏字体变色，会使当前状态栏加上透明度，否则不执行透明度
                .init();
        nWebView = findViewById(R.id.news_webView);
        nWebView.getSettings().setBlockNetworkImage(false);
        WebSettings settings = nWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            nWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        nWebView.setWebViewClient(new MyWebViewClient());
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);//用于设置webView 放大
        settings.setBuiltInZoomControls(false);
        nWebView.addJavascriptInterface(new JavascriptInterface(UserApplication.getUserApplication()),"imagelistner");
        content = content.replace("<img", "<img style='max-width: 100%'");

        nWebView.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        ivIcon = findViewById(R.id.iv_icon);
        ivIcon.setOnClickListener(this::onClick);
    }

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

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_icon:
                finish();
                break;
        }
    }

    // 注入js函数监听
    private void addImageClickListener() {
        Log.d("TAG", "addImageClickListener: 注入代码");
        // 这段js函数的功能就是，遍历所有的img几点，并添加onclick函数，在还是执行的时候调用本地接口传递url过去
        nWebView.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName(\"img\");"
                + "var imgurl=''; "
                + "for(var i=0;i<objs.length;i++)  "
                + "{"
                + "imgurl+=objs[i].src+',';"
                + "    objs[i].onclick=function()  "
                + "    {  "
                + "        imagelistner.openImage(imgurl);  "
                + "    }  " + "}" + "})()");
    }
    // js通信接口
    public class JavascriptInterface {

        private Context context;

        public JavascriptInterface(Context context) {
            this.context = context;
        }
        @android.webkit.JavascriptInterface  //注解 很重要，必不可少
        public void openImage(String img) {
            System.out.println(img);
            Log.d("TAG", "openImage-------------------------: "+img);
            String[] imgs = img.split(",");
            ArrayList<String> imgsUrl = new ArrayList<String>();
            for (String s : imgs) {
                imgsUrl.add(s);
                Log.d("TAG", "openImage-------------------------: "+s);
            }
            Intent intent = new Intent();
            intent.putStringArrayListExtra("info", imgsUrl);
            intent.setClass(context, ImageShowActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        }
    }



    // 监听
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
            // html加载完成之后，添加监听图片的点击js函数
            addImageClickListener();

        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);
            Log.d("TAG", "addImageClickListener: 开始加载");
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            super.onReceivedError(view, errorCode, description, failingUrl);

        }
    }
}
