package com.sheep.gamegroup.view.activity;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.kfzs.duanduan.BaseCompatActivity;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.kfzs.duanduan.bean.KFIntentKeys.EXTRA_WEBVIEW_NO_TITLE;

/**
 * web页面
 * Created by zengjiebin on 2018/4/27.
 */
public class ActWeb extends BaseCompatActivity {

    @BindView(R.id.webview)
    WebView mWebView;
    @BindView(R.id.tv_next)
    TextView tv_next;

    private String title;
    private String url;
    private WebSettings webViewSettings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide_on_hook);

        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");

        ButterKnife.bind(this);
        TitleBarUtils
                .getInstance()
                .setTitle(this, title == null ? "加载中" : title)
                .setTitleFinish(this);
        initWebViewSettings(mWebView);
        webViewSettings = mWebView.getSettings();
        webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webViewSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if (getIntent().hasExtra(EXTRA_WEBVIEW_NO_TITLE)) {//不显示标题
            findViewById(R.id.appbar_act_webview).setVisibility(View.GONE);
        }
        tv_next.setVisibility(View.GONE);
        loadUrl();
    }

    public static void initWebViewSettings(WebView webView) {
        webView.setClickable(true);
        WebSettings webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的设计
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.setVisibility(View.GONE);
        mWebView.removeAllViews();
        mWebView.destroy();
    }

    private void loadUrl() {
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if(title == null)
                    TitleBarUtils
                            .getInstance()
                            .setTitle(ActWeb.this, title);
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                try {
                    view.loadUrl(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return true;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        webViewSettings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new KFZSJs(), "kfzsjs");
        mWebView.loadUrl(addUrl(url,"authorization", SpUtils.getOpenId(this)));
    }
    private String addUrl(String url, String key, String value){
        return  url + (url.contains("?") || url.contains("#") ? "&" : "?")+key+"="+value;
    }
    public class KFZSJs{
        @JavascriptInterface
        public void setTitle(String title){
            TitleBarUtils
                    .getInstance()
                    .setTitle(ActWeb.this, title);
        }
        @JavascriptInterface
        public void setCanGoBack(){
        }
        @JavascriptInterface
        public void downloadFile(final String url, final String name){
            OkHttpUtils.get()
                    .url(url)
                    .build()
                    .execute(new FileCallBack(ClassFileHelper.DIR, name) {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            G.showToast("下载文件失败");
                        }

                        @Override
                        public void onResponse(File response, int id) {
                            if(name.endsWith(".png") || name.endsWith(".jpg")) {//图片
                                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                Uri uri = Uri.fromFile(response);
                                intent.setData(uri);
                                sendBroadcast(intent); // 发送广播通知相册
                            }
                            G.showToast("下载文件成功");
                        }
                    });
        }
        @JavascriptInterface
        public void startApp(String pkg, String cls){
            PackageUtil.startApp(ActWeb.this, pkg);
        }

    }

    @Override
    public void finish() {
        if(mWebView.canGoBack()){
            mWebView.goBack();
            return;
        }
        super.finish();
    }
}
