package com.cooleshow.student.widgets.dialog;

import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;


import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.student.BuildConfig;
import com.cooleshow.student.R;
import com.cooleshow.student.api.APIService;
import com.cooleshow.usercenter.helper.UserHelper;

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

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import androidx.annotation.NonNull;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * Author by pq, Date on 2022/5/16.
 */
public class LiveRoomShopCarDialog extends Dialog {
    public static final String OPEN_DETAIL = "openUrl";

    private WebView mWebView;
    private String authorization;
    private TextView mTvTitle;
    private OnEventListener mEventListener;
    private String webUrl;

    public LiveRoomShopCarDialog(@NonNull Context context) {
        super(context, R.style.MyBottomDialogStyle);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_live_room_shop_car_layout);
        Window window = getWindow();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出
        window.setWindowAnimations(com.cooleshow.base.R.style.BottomAnimation);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.horizontalMargin = 0;
        lp.verticalMargin = 0;
        //将设置好的属性set回去
        window.setAttributes(lp);

        mWebView = findViewById(R.id.webView);
        mTvTitle = findViewById(R.id.tv_title);
        initWebSetting();
    }

    public void changeGoods(String str) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("api", "cardChange");
            JSONArray json = new JSONArray(str);
            jsonObject.put("content", json);
            String message = jsonObject.toString();
            Log.i("LiveRoomShopCarDialog", "jsonObject:" + jsonObject.toString());
            mWebView.evaluateJavascript("postMessage('" + message + "','*')", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String s) {
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void setRoomId(String roomId) {
        if (TextUtils.isEmpty(webUrl)) {
            webUrl = WebConstants.STUDENT_LIVE_SHOP_CAR_URL + "?liveId=" + roomId;
            if (!TextUtils.isEmpty(authorization)) {
                try {
                    authorization = URLEncoder.encode(authorization, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                boolean status = webUrl.contains("?");
                if (status) {
                    webUrl = (webUrl + "&Authorization=" + authorization);
                } else {
                    webUrl = (webUrl + "?Authorization=" + authorization);
                }
            }
            mWebView.loadUrl(webUrl);
        }
    }

    private void initWebSetting() {
        mWebView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void postMessage(String message) {
                handleMessage(message);
            }
        }, "DAYA");
        authorization = UserHelper.getUserToken();

        mWebView.setWebViewClient(new WebClient());
        mWebView.setWebChromeClient(new MyWebChromeClient());

        //声明WebSettings子类
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setUserAgentString(webSettings.getUserAgentString() + WebConstants.WEB_UA_PARAMS);
        webSettings.setGeolocationDatabasePath(getContext().getFilesDir().getPath());
        webSettings.setGeolocationEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        webSettings.setMediaPlaybackRequiresUserGesture(false);//false允许自动播放音视频
        //是否启用缓存
        webSettings.setAppCacheEnabled(true);

        // 开启DOM缓存,默认状态下是不支持LocalStorage的
        webSettings.setDomStorageEnabled(true);
        // 开启数据库缓存
        webSettings.setDatabaseEnabled(true);
        // 地址跨域导致视频预览图片加载不出来 无法播放：
        webSettings.setAllowUniversalAccessFromFileURLs(false);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        //缩放操作
        webSettings.setSupportZoom(false); //支持缩放，默认为true。是下面那个的前提。
        // 设置允许JS弹窗
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("UTF-8");//设置编码格式

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);  //富文本适配
        webSettings.setAppCacheMaxSize(Long.MAX_VALUE);
        webSettings.setAppCachePath(getContext().getDir("appcache", 0).getPath());
        webSettings.setDatabasePath(getContext().getDir("databases", 0).getPath());
        webSettings.setGeolocationDatabasePath(getContext().getDir("geolocation", 0)
                .getPath());
        webSettings.setPluginState(WebSettings.PluginState.ON_DEMAND);
        if (BuildConfig.DEBUG) {
            mWebView.setWebContentsDebuggingEnabled(true);
        }
        webSettings.setTextZoom(100);//设置字体默认的缩放比例，以避免手机系统的字体修改对页面字体及布局造成影响。
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setDownloadListener((url, userAgent, contentDisposition, mimetype, contentLength) -> {

        });
    }

    private void handleMessage(String message) {
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                JSONObject jsonObject = new JSONObject(message);
                String api = jsonObject.getString("api");
                if (TextUtils.equals(api, OPEN_DETAIL)) {
                    JSONObject content = jsonObject.getJSONObject("content");
                    String url = content.optString("url");
                    if (!TextUtils.isEmpty(url)) {
                        emitter.onNext(url);
                    }
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String url) {
                        if (mEventListener != null) {
                            mEventListener.onOpenDetail(url);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    private class WebClient extends WebViewClient {
        //页面开始载入时调用

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            LogUtils.e("onPageStarted:" + url);
        }

        //页面载入结束时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, 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));
                    getContext().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    ToastUtil.getInstance().show(getContext(), "未安装该应用");
                }
                return true;
            } else {
                view.loadUrl(request);
                return true;
            }
        }

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


    private class MyWebChromeClient extends WebChromeClient {
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            LogUtils.e(newProgress + "");
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        // Android > 5.0.1
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            return true;
        }


        // 点击全屏按钮时，调用的方法
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
        }

        // 取消全屏调用的方法
        @Override
        public void onHideCustomView() {
            super.onHideCustomView();
        }
    }


    public void setOnEventListener(OnEventListener listener) {
        this.mEventListener = listener;
    }

    public interface OnEventListener {
        void onOpenDetail(String url);
    }
}
