package com.cooleshow.base.widgets;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cooleshow.base.utils.LogUtils;

/**
 * Author by pq, Date on 2022/4/26.
 */
public class WebClient extends WebViewClient {
    public String webViewUrl = "";
    public String authorization = "";

    public void setAuthorization(String authorization) {
        this.authorization = authorization;
    }

    //页面开始载入时调用
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        webViewUrl = url;
        LogUtils.i("onPageStarted:" + url);
    }

    //页面载入结束时调用
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        webViewUrl = url;
        if (!TextUtils.isEmpty(authorization)) {
            String js = "window.localStorage.setItem('Authorization','" + authorization + "');";
            String jsUrl = "javascript:(function({var localStorage = window.localStorage; localStorage.setItem('Authorization','" + authorization + "') })()";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                view.evaluateJavascript(js, null);
            } else {
                view.loadUrl(jsUrl);
                view.reload();
            }
        }
        LogUtils.e("onPageFinished:" + url);
        LogUtils.e("Authorization:" + authorization);
    }

    //截取url请求，在当前视图加载，避免在跳转到自带浏览器
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String request) {
        if (!(request.startsWith("http://") || request.startsWith("https://"))) {
            try {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(request));
                view.getContext().startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        } else {
            view.loadUrl(request);
            return true;
        }
    }

    //处理报错信息
    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
    }
}
