package com.efounder.chat.activity;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.utils.UshareHelper;
import com.efounder.chat.utils.WebParamUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.OSPPlugin;
import com.efounder.util.AppContext;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.AndroidBug5497Workaround;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.tamic.jswebview.browse.BridgeWebView;
import com.tamic.jswebview.browse.JsWeb.CustomWebChromeClient;
import com.tamic.jswebview.browse.JsWeb.CustomWebViewClient;
import com.tamic.jswebview.view.NumberProgressBar;
import com.tamic.jswebview.view.ProgressBarWebView;
import com.utilcode.util.ReflectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 聊天打开的webview
 *
 * @author yqs
 */
public class ChatWebViewActivity extends BaseActivity {

    private final static int TYPE_GALLERY = 121;
    //5.0以上系统
    private final static int TYPE_GALLERY_5 = 122;

    private ProgressBarWebView webView;
    private String url;

    private ImageView ivBack;
    private TextView tvTitle;
    //是否支持分享功能
    private boolean isSupportShare = false;
    private ImageView ivShareView;

    private QMUIEmptyView qmuiEmpty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_chat_webview);
        AndroidBug5497Workaround.assistActivity(this);
        initView();
        initData();
    }

    public static void start(Context context, String url) {
        Intent starter = new Intent(context, ChatWebViewActivity.class);
        starter.putExtra("url", url);
        context.startActivity(starter);
    }


    private void initView() {
        qmuiEmpty = (QMUIEmptyView) findViewById(R.id.qmui_empty);
        qmuiEmpty.setDetailColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        qmuiEmpty.setTitleColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        webView = (ProgressBarWebView) findViewById(R.id.webView);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ivShareView = (ImageView) findViewById(R.id.iv_share);
        WebSettings setting = webView.getWebView().getSettings();
        setting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        setting.setUseWideViewPort(true);
        setting.setLoadWithOverviewMode(true);
        setting.setJavaScriptEnabled(true);
        setting.setBuiltInZoomControls(true);
        setting.setDisplayZoomControls(false);
        setting.setAllowFileAccess(true);
        setting.setCacheMode(WebSettings.LOAD_DEFAULT);

        // 增加userAgent字段
        String ua = setting.getUserAgentString();
        setting.setUserAgentString(ua + " Platform/" + ResStringUtil.getString(R.string.web_user_agent_plat_form) + " UserName/" + EnvironmentVariable.getUserName());

        setting.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        setting.setDatabaseEnabled(true);   //开启 database storage API 功能
        setting.setAppCacheEnabled(true);//开启 Application Caches 功能
        setting.setJavaScriptCanOpenWindowsAutomatically(true);//允许js弹出窗口
        webView.setWebChromeClient(new MyWebChromeClient(webView.getProgressBar()));
        webView.setWebViewClient(new MyWebViewClient(webView.getWebView()));
        String username = EnvironmentVariable.getUserName();
        String userpass = EnvironmentVariable.getPassword();
        webView.getWebView().addJavascriptInterface(new OSPPlugin(username, userpass, this), "OSPPlugin");
        // webView.getWebView().setDownloadListener(new MyWebViewDownLoadListener(this));
        webView.getWebView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_DOWN && webView.getWebView().canGoBack()) {
                    webView.getWebView().goBack();
                    return true;
                }
                return false;
            }
        });

    }

    private void initData() {
        if (EnvSupportManager.isSupportShareWebUrl()) {
            isSupportShare = true;
            ivShareView.setVisibility(View.VISIBLE);
            ivShareView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    shareUrl();
                }
            });
        }

        url = getIntent().getStringExtra("url");
        if (!url.toLowerCase().startsWith("http")) {
            url = "http://" + url;
        }

        String param = getIntent().getStringExtra("param");
        String value = getIntent().getStringExtra("value");
        if (null != param && !"".equals(param) && null != value && !"".equals(value)) {
            String urlParam = WebParamUtils.dealUrlParams(param, value);
            String appendChar = WebParamUtils.getAppendChar(url);
            url = url + appendChar + urlParam;
        }
        webView.loadUrl(url);
    }


    //变量
    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private WebChromeClient.FileChooserParams fileChooserParams;

    public class MyWebChromeClient extends CustomWebChromeClient {

        public MyWebChromeClient(NumberProgressBar progressBar) {
            super(progressBar);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.d("ANDROID_LAB", "TITLE=" + title);
            tvTitle.setText(title);
        }

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

            uploadMessageAboveL = filePathCallback;
            fileChooserParams = fileChooserParams1;
//            Intent intent = new Intent(
//                    Intent.ACTION_PICK,
//                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 调用android的图库
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, TYPE_GALLERY_5);
            return true;
        }


        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
            uploadMessage = valueCallback;
            Intent intent = new Intent(
                    Intent.ACTION_PICK,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 调用android的图库
            startActivityForResult(intent, TYPE_GALLERY);
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TYPE_GALLERY) {
            if (null == uploadMessageAboveL) return;
            if (null == data) {
                uploadMessage.onReceiveValue(null);
                uploadMessage = null;
            } else {
                Uri result = data == null || resultCode != Activity.RESULT_OK ? null
                        : data.getData();
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        } else if (requestCode == TYPE_GALLERY_5) {
            // 处理5.0的callback
            if (uploadMessageAboveL != null) {
                if (null != data) {
                    ArrayList<String> resultList = data.getStringArrayListExtra("data");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                        uploadMessageAboveL.onReceiveValue(
                                fileChooserParams.parseResult(resultCode, data));
                    }
                    uploadMessageAboveL = null;
                } else {
                    uploadMessageAboveL.onReceiveValue(null);
                }
            }
        }
    }

    private class MyWebViewClient extends CustomWebViewClient {
        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webView.setVisibility(View.VISIBLE);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            initErrorPage();
        }

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

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            // view.loadUrl(url);


            if (ChatWebViewActivity.this.isDestroyed()) {
                return false;
            }
            if (url.startsWith("http") || url.startsWith("https")) { //http和https协议开头的执行正常的流程
                return false;
            } else {  //其他的URL则会开启一个Acitity然后去调用原生APP urlschme

                List<ResolveInfo> list = getSupportResolveInfoList(url);
                if (list == null) {
                    return false;
                }
                if (list.size() == 0) {
                    return false;
                }

                String appName = "";

                if (list.size() > 1) {
                    appName = getResources().getString(R.string.chat_webview_android_app);
                } else {
                    ResolveInfo resolve = list.get(0);
                    appName = resolve.loadLabel(AppContext.getInstance().getPackageManager()).toString();
                }
                String content = getResources().getString(R.string.chat_allow_open_three_app1, appName);
                new AlertDialog.Builder(ChatWebViewActivity.this).setTitle(R.string.common_text_hint)
                        .setMessage(content)
                        .setNegativeButton(R.string.common_text_cancel, null)
                        .setPositiveButton(R.string.common_text_open, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                try {
                                    Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                                    startActivity(in);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    ToastUtil.showToast(ChatWebViewActivity.this, R.string.chat_jump_fail_not_app);
                                }
                            }
                        }).show();


                return true;
            }
        }

        @Override
        public String onPageError(String url) {
            return null;

        }

        @NonNull
        @Override
        public Map<String, String> onPageHeaders(String url) {
            return null;
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            return null;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//            webView.setVisibility(View.VISIBLE);
//            qmuiEmpty.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            ReflectUtils reflectUtils = ReflectUtils.reflect(EnvironmentVariable.getProperty("shareClass", ""));
            reflectUtils.newInstance().method("release", this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查允许打开该urlsche的应用
     *
     * @param urlScheme
     * @return
     */
    private List<ResolveInfo> getSupportResolveInfoList(String urlScheme) {
        PackageManager manager = AppContext.getInstance().getPackageManager();
        Intent action = new Intent(Intent.ACTION_VIEW);
        action.setData(Uri.parse(urlScheme));
        List list = manager.queryIntentActivities(action, PackageManager.GET_RESOLVED_FILTER);
        return list;
    }

    /**
     * 分享网页
     */
    private void shareUrl() {

        try {
            //UshareHelper OpenShareHelper
            ReflectUtils reflectUtils = ReflectUtils.reflect(EnvironmentVariable.getProperty("shareClass", ""));
            reflectUtils.newInstance().method("share", this, url, tvTitle.getText().toString(), R.drawable.wechat_icon_launcher, "",
                    new UshareHelper.ShareListener() {
                        @Override
                        public void share(int type) {

                        }
                    });
//            String shareClassNmae = EnvironmentVariable.getProperty("shareClass", "");
//            ClassLoader loader = Thread.currentThread().getContextClassLoader();
//            Class<?> clazz = loader.loadClass(shareClassNmae);
//            Constructor<?> cons1 = clazz.getDeclaredConstructor(null);
//            UshareHelper helper = (UshareHelper) cons1.newInstance(null);
//            helper.share(this, url, tvTitle.getText().toString(), R.drawable.wechat_icon_launcher, "",
//                    new UshareHelper.ShareListener() {
//                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //webview下载
    private static class MyWebViewDownLoadListener implements DownloadListener {
        private Context mContext;

        public MyWebViewDownLoadListener(Context mContext) {
            this.mContext = mContext;
        }

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            String dirNameString = url.substring(url.lastIndexOf("/") + 1);
            DownloadManager downloadManager = (DownloadManager) mContext.getApplicationContext().getSystemService(Context.DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            //下载时，下载完成后显示通知
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            //下载的路径，第一个参数是文件夹名称，第二个参数是下载的文件名
            request.setDestinationInExternalPublicDir("Download", dirNameString);
            request.setVisibleInDownloadsUi(true);
            downloadManager.enqueue(request);
        }
    }

    /**
     * 显示加载错误页
     */
    private void initErrorPage(){
        webView.setVisibility(View.GONE);
        qmuiEmpty.show(false, getResources().getString(R.string.emptyView_mode_desc_fail_title), getResources().getString(R.string.emptyView_mode_desc_fail_desc), getResources().getString(R.string.emptyView_mode_desc_retry),new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                qmuiEmpty.hide();
                webView.loadUrl(url);
            }
        });
    }
}