package com.cooleshow.teacher.ui.main;

import android.os.Build;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.FrameLayout;

import com.cooleshow.base.BuildConfig;
import com.cooleshow.base.common.WebConstants;
import com.cooleshow.base.ui.fragment.BaseMVPFragment;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.widgets.LollipopFixedWebView;
import com.cooleshow.base.widgets.WebClient;
import com.cooleshow.teacher.contract.ShopMallContract;
import com.cooleshow.teacher.databinding.FragmentShopmalBinding;
import com.cooleshow.teacher.presenter.main.ShopMallPresenter;
import com.cooleshow.teacher.widgets.helper.JsInterfaceHelper;
import com.cooleshow.usercenter.helper.UserHelper;

import org.json.JSONObject;

/**
 * 创建日期：2022/5/23 15:59
 *
 * @author Ryan
 * 类说明：
 */
public class ShopMallFragment extends BaseMVPFragment<FragmentShopmalBinding, ShopMallPresenter> implements ShopMallContract.ShopMallView, JsInterfaceHelper.OnJsMethodCallListener {
    private WebView webView;
    private String url;
    private WebClient mWebClient;
    private JsInterfaceHelper mInterfaceUtils;
    private ValueCallback mUploadCallbackAboveL;

    @Override
    protected FragmentShopmalBinding getLayoutView() {
        return FragmentShopmalBinding.inflate(getLayoutInflater());
    }

    @Override
    protected ShopMallPresenter createPresenter() {
        return new ShopMallPresenter();
    }

    private View view_status_bar;

    @Override
    protected void initView(View rootView) {
        view_status_bar = mViewBinding.viewStatusBar;
        try {
            if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT < 23) {
                webView = new LollipopFixedWebView(getContext());
            } else {
                webView = new WebView(getContext());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null == webView) {

            return;
        }
        url = WebConstants.TEACHER_SHOPMALL;

        mViewBinding.viewParent.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));
        initWebView();
        mInterfaceUtils = new JsInterfaceHelper(getActivity());
        mInterfaceUtils.setOnJsCallListener(this);
        webView.addJavascriptInterface(mInterfaceUtils, WebConstants.WEB_JS_INTERFACE);
        mWebClient = new WebClient();
        webView.setWebViewClient(mWebClient);
        webView.setWebChromeClient(new MyWebChromeClient());

        loadUrl();
    }

    private void loadUrl() {
        String userToken = UserHelper.getUserToken();
        mWebClient.setAuthorization(userToken);
        boolean status = url.contains("?");
        if (status) {
            url = (url + "&Authorization=" + userToken);
        } else {
            url = (url + "?Authorization=" + userToken);
        }
        webView.loadUrl(url);
    }

    private void initWebView() {
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();
        webSettings.setUserAgentString(webSettings.getUserAgentString() + WebConstants.WEB_UA_PARAMS);
        webSettings.setGeolocationDatabasePath(getActivity().getApplicationContext().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。是下面那个的前提。
        //其他细节操作
        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) {
            webView.setWebContentsDebuggingEnabled(true);
        }
        webSettings.setTextZoom(100);//设置字体默认的缩放比例，以避免手机系统的字体修改对页面字体及布局造成影响。
        webView.setHorizontalScrollBarEnabled(false);
        webView.setVerticalScrollBarEnabled(false);
    }

    @Override
    public void onSendMessage(String message) {

    }

    @Override
    public void setBarStatus(JSONObject message) {

    }

    @Override
    public void backIconChange(JSONObject message) {

    }

    @Override
    public void chooseFile(JSONObject message) {

    }

    @Override
    public void getNavHeight(JSONObject message) {

    }



    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 + "");
            if (newProgress == 100 && null != mViewBinding.progressBar) {
                mViewBinding.progressBar.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                if (null != mViewBinding.progressBar) {
                    mViewBinding.progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    mViewBinding.progressBar.setProgress(newProgress);//设置进度值
                }

            }
        }

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

    }

    @Override
    protected void initData() {

    }

    public void clickBack() {
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            ((MainActivity) getActivity()).clickBackPressed();
        }
    }
}
