package com.yyrh.core.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.yyrh.Version;
import com.yyrh.core.internal.IJsFeature;
import com.yyrh.core.network.SdkJsImpl;
import com.yyrh.factory.SdkManager;
import com.yyrh.utils.YYLog;

import org.json.JSONException;
import org.json.JSONObject;

import cn.yyxx.support.AndroidBug5497Workaround;
import cn.yyxx.support.AppUtils;
import cn.yyxx.support.ResUtils;
import cn.yyxx.support.device.DeviceInfoUtils;

/**
 * @author #Suyghur.
 * Created on 2021/10/22
 */
public class HybridActivity extends Activity {

    private ImageView ivLoading, ivClose;
    private WebView webView;
    private Animation rotateAnimation;
    private static String mUrl = "";
    private final IJsFeature feature = new IJsFeature() {
        @Override
        public void onJsInvoke(int feature, String data) {
            YYLog.d("feature: " + feature + " ,data: " + data);
            switch (feature) {
                case SdkJsImpl.SdkJsFeature.FEATURE_CLOSE:
                    HybridActivity.this.finish();
                    break;
                case SdkJsImpl.SdkJsFeature.FEATURE_ZF_ORDER:
                    YYLog.i("order: " + data);
                    break;
                case SdkJsImpl.SdkJsFeature.FEATURE_SWITCH_ACCOUNT:
                    SdkManager.defaultManager().logOut();
                    break;
            }
        }

        @Override
        public String onJsCallback(int feature, String data) {
            if (feature == SdkJsImpl.SdkJsFeature.FEATURE_WEB_EXT) {
                JSONObject jsonObject = new JSONObject();
                try {
                    if (SdkManager.defaultManager().isLandscape) {
                        jsonObject.put("orientation", "landscape");
                    } else {
                        jsonObject.put("orientation", "portrait");
                    }
                    jsonObject.put("version", Version.VERSION_NAME);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return jsonObject.toString();
            }
            return "";
        }
    };


    public static void start(Activity activity, String url) {
        mUrl = url;
        activity.startActivity(new Intent(activity, HybridActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initWebView();
    }

    private void initView() {
        if (SdkManager.defaultManager().isLandscape) {
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        }
        setContentView(ResUtils.getResId(this, "hnyy_hybrid", "layout"));

        if (!SdkManager.defaultManager().isLandscape) {
            AndroidBug5497Workaround.assistActivity(this);
        }

        ivLoading = findViewById(ResUtils.getResId(this, "hnyy_iv_loading", "id"));
        rotateAnimation = AnimationUtils.loadAnimation(this, ResUtils.getResId(this, "hnyy_rotate_anim", "anim"));
        ivLoading.startAnimation(rotateAnimation);

        ivClose = findViewById(ResUtils.getResId(this, "hnyy_iv_close", "id"));
        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HybridActivity.this.finish();
            }
        });

        webView = findViewById(ResUtils.getResId(this, "hnyy_webview", "id"));
    }

    private void initWebView() {
        webView.setVerticalScrollBarEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.addJavascriptInterface(new SdkJsImpl(feature), "yyrhsdk");
        webView.setBackgroundColor(Color.TRANSPARENT);

        WebSettings settings = webView.getSettings();
        settings.setAllowFileAccess(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        settings.setSupportZoom(true);
        settings.setSaveFormData(true);
        settings.setSavePassword(true);
        settings.setBuiltInZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setSupportMultipleWindows(false);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setJavaScriptEnabled(true);
        settings.setGeolocationEnabled(true);
        settings.setAppCacheMaxSize(Long.MAX_VALUE);
        settings.setAppCachePath(this.getDir("appcache", 0).getPath());
        settings.setDatabasePath(this.getDir("databases", 0).getPath());
        settings.setGeolocationDatabasePath(this.getDir("geolocation", 0).getPath());
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();

        if (DeviceInfoUtils.isNetworkConnected(this)) {
            webView.loadUrl(mUrl);
        } else {
            webView.loadData("网络异常,请检查重试", "text/html; charset=UTF-8", null);
        }

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                YYLog.d("url: " + url);
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    if (!view.canGoBack()) {
                        return false;
                    }
                    if (view.getHitTestResult().getType() == WebView.HitTestResult.UNKNOWN_TYPE) {
                        return false;
                    }
                    view.loadUrl(url);
                }
                if (url.startsWith("weixin://wap/pay")) {
                    if (AppUtils.isPackageInstalled(HybridActivity.this, "com.tencent.mm")) {
                        try {
                            startActivity(Intent.parseUri(url, Intent.URI_INTENT_SCHEME));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        webView.loadData("请先安装微信", "text/html;charset=UTF-8", null);
                        return false;
                    }
                    return true;
                }
                if (url.startsWith("alipays://")) {
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100 && ivLoading != null && ivLoading.getVisibility() == View.VISIBLE) {
                    ivLoading.clearAnimation();
                    ivLoading.setVisibility(View.GONE);
                }
            }
        });
    }
}
