package com.yyrh.ui.dialog;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;

import cn.yyxx.support.DensityUtils;
import cn.yyxx.support.ResUtils;
import cn.yyxx.support.device.DeviceInfoUtils;

/**
 * @author #Suyghur.
 * Created on 2021/10/20
 */
public class AgreementDialog extends Dialog {

    private Button btnConfirm;
    private ImageView ivLoading;
    private WebView webView;
    private Animation rotateAnimation;


    public AgreementDialog(Context context, String url, boolean isLandscape) {
        super(context);
        initView(context, isLandscape);
        initWebView(context, url);
    }

    private void initView(Context context, boolean isLandscape) {
        setCanceledOnTouchOutside(false);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        View view = LayoutInflater.from(context).inflate(ResUtils.getResId(context, "hnyy_agreement_dialog", "layout"), null);
        setContentView(view);

        WindowManager.LayoutParams attr = getWindow().getAttributes();
        attr.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        if (isLandscape) {
            attr.width = DensityUtils.getHeightAndWidth(context)[0] / 2;
        } else {
            attr.width = DensityUtils.getHeightAndWidth(context)[0] - 80;
        }
        attr.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        attr.gravity = Gravity.CENTER;

        webView = view.findViewById(ResUtils.getResId(context, "hnyy_webview", "id"));

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

        btnConfirm = view.findViewById(ResUtils.getResId(context, "hnyy_btn_confirm", "id"));
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
    }

    private void initWebView(Context context, String url) {
        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(context.getDir("appcache", 0).getPath());
        settings.setDatabasePath(context.getDir("databases", 0).getPath());
        settings.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath());
        settings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        CookieSyncManager.createInstance(context);
        CookieSyncManager.getInstance().sync();

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

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String 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);
                }
                return false;
            }
        });

        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);
                }
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
        ivLoading.clearAnimation();
        ivLoading.setVisibility(View.GONE);
    }
}
