package com.sheep.gamegroup.view.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;

import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;
import com.sheep.jiuyan.samllsheep.utils.SpUtils;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.yalantis.ucrop.util.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.sheep.gamegroup.util.Jump2View.EXTRA_WEBVIEW_NO_TITLE;


/**
 * web页面--含有所有js及url后添加authorization
 * Created by zengjiebin on 2018/4/27.
 */
public class ActWeb extends BaseActivity {

    @BindView(R.id.webview)
    WebView mWebView;
    @BindView(R.id.layout_navigationBar)
    View layout_navigationBar;

    private String title;//title为空时，不显示整个标题栏
    private String url;
    private WebSettings webViewSettings;

    @Override
    protected int getLayoutId() {
        return R.layout.act_web;
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void initView() {
        url = getIntent().getStringExtra("url");
        title = getIntent().getStringExtra("title");//title为空时，不显示整个标题栏
        if (!TextUtils.isEmpty(url)) {
            url = url.trim();
        }
        ButterKnife.bind(this);
        TitleBarUtils
                .getInstance()
                .setTitle(this, TextUtils.isEmpty(title) ? "加载中" : title)
                .setTitleFinish(this);
        initWebViewSettings(mWebView);
        webViewSettings = mWebView.getSettings();
        webViewSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        try {
            if (TestUtil.isTest())
                WebView.setWebContentsDebuggingEnabled(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            webViewSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        loadUrl();
    }

    @Override
    public void initListener() {
        mWebView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType, long contentLength) {
                //去下载
                CommonUtil.getInstance().showDownLoad(ActWeb.this, url, url.substring(url.lastIndexOf("/") + 1));
            }
        });
    }

    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();
        if (mWebView != null) {
            mWebView.setVisibility(View.GONE);
            mWebView.removeAllViews();
            mWebView.destroy();
        }
    }

    /**
     *
     */
    public static final int INPUT_FILE_REQUEST_CODE = 1;
    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 2;
    private ValueCallback<Uri[]> mFilePathCallback;

    private String mCameraPhotoPath;

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

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;

                /*PhotoPicker.builder()
                        .setPhotoCount(1)
                        .setShowCamera(true)
                        .setShowGif(false)
                        .setPreviewEnabled(true)
                        .start(ActWeb.this, PhotoPicker.REQUEST_CODE);*/
                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                    // Create the File where the photo should go
                    File photoFile;
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(photoFile));
                    } else {
                    }
                }

                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");

                Intent[] intentArray;
                takePictureIntent = null;//步调用相机
                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "图片选择");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

                startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

                return /*super.onShowFileChooser(webView, filePathCallback, fileChooserParams)*/true;
            }

            //For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                ActWeb.this.startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);

            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    String action = "javascript:imgsrc('" + url + "')";
                    runWebviewUrl(action);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //微信H5支付核心代码
                if (url.startsWith("weixin://wap/pay?")) {
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                } else if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {
                        new AlertDialog.Builder(ActWeb.this)
                                .setMessage("未检测到支付宝客户端，请安装后重试。")
                                .setPositiveButton("立即安装", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Uri alipayUrl = Uri.parse("https://d.alipay.com");
                                        startActivity(new Intent("android.intent.action.VIEW", alipayUrl));
                                    }
                                }).setNegativeButton("取消", null).show();
                    }
                    return true;
                } else if(url.contains("17xmy.com")){
                    Map<String, String> extraHeaders = new HashMap<>();
                    extraHeaders.put("Referer", "http://17xmy.com");
                    view.loadUrl(url, extraHeaders);
                } else {
                    return false;
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                imgReset();
            }
        });
        webViewSettings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new KFZSJs(), "kfzsjs");
        String loadUrl = addUrlToken(url);
        LogUtil.println("ActWeb loadUrl = " + loadUrl);
        if (CommonUtil.getInstance().judgeUrlPicture(url)) {
            runWebviewUrl("file:///android_asset/loadImg.html");
        } else {
            mWebView.loadUrl(loadUrl);
        }
    }

    //在sdcard卡创建缩略图
    //createImageFileInSdcard
    @SuppressLint("SdCardPath")
    private File createImageFile() {
        //mCameraPhotoPath="/mnt/sdcard/tmp.png";
        File file = new File(Environment.getExternalStorageDirectory() + "/", "tmp.png");
        mCameraPhotoPath = file.getAbsolutePath();
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static String addUrlToken(String url) {
        return addUrl(url, "authorization", SpUtils.getToken(SheepApp.getInstance()));
    }

    public static String addUrl(String url, String key, String value) {
        return url + ((url.contains("?") || url.contains("#") && url.contains("=")) ? "&" : "?") + key + "=" + value;
    }

    public class KFZSJs {
        @JavascriptInterface
        public void setTitle(final String title) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    TitleBarUtils
                            .getInstance()
                            .setTitle(ActWeb.this, title);
                }
            });
        }

        /**
         * 是否响应返回键
         */
        @JavascriptInterface
        public boolean isResponseBack() {
            return responseBack;
        }

        /**
         * 设置是否响应返回键
         */
        @JavascriptInterface
        public void setResponseBack(boolean responseBack) {
            ActWeb.this.responseBack = responseBack;
        }

        @JavascriptInterface
        public void downloadFile(final String url, final String name) {
            CommonUtil.getInstance().showDownLoad(ActWeb.this, url, name);
        }

        @JavascriptInterface
        public void startApp(String pkg, String cls) {
            PackageUtil.startApp(ActWeb.this, pkg);
        }

        @JavascriptInterface
        public void gotoLogin() {
            mWebView = null;
            Jump2View.getInstance().gotoLoginAgain();
        }

        @JavascriptInterface
        public void gotoWeb(String url, String title) {
            if (!TextUtils.isEmpty(url)) {
                if (TextUtils.isEmpty(title)) {
                    Jump2View.getInstance().goWeb(ActWeb.this, url);//启动浏览器h5
                } else {
                    Jump2View.getInstance().goWeb(ActWeb.this, url, title);//进入小绵羊h5界面
                }
            }
        }

        @JavascriptInterface
        public void gotoRecharge() {
            Jump2View.getInstance().goRechargeAct(ActWeb.this, "内部H5");//进入充值绵羊币界面
        }

        @JavascriptInterface
        public String getInvitationCode() {
            return DataUtil.getInstance().getInvitationCode();
        }

        @JavascriptInterface
        public String popShare(String url, String type) {
            CommonUtil.getInstance().popShare(ActWeb.this, url, type);
            return "";
        }

        @JavascriptInterface
        public String getHeader() {
            return SpUtils.getToken(ActWeb.this);
        }

        @JavascriptInterface
        public String getWcUrl(String url) {
            if (!TextUtils.isEmpty(url)) {
                Jump2View.getInstance().goWeb(ActWeb.this, url);
            }
            return "";
        }

        @JavascriptInterface
        public void showTitleBar(final boolean isShow) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    layout_navigationBar.setVisibility(isShow ? View.VISIBLE : View.GONE);
                }
            });
        }

        @JavascriptInterface
        public void goBack() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            });
        }

        @JavascriptInterface
        public void finishAct() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ActWeb.super.finish();
                }
            });
        }

    }

    /**
     * 是否响应返回键
     */
    private boolean responseBack = true;

    @Override
    public void onBackPressed() {
        if (responseBack)
            super.onBackPressed();
        else {
            loadJs("onBackPressed()");
        }
    }

    private void loadJs(String js) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebView.evaluateJavascript("javascript:" + js, new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    //此处为 js 返回的结果
                }
            });
        } else {
            mWebView.loadUrl("javascript:" + js);
        }
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return;
            Uri result = data == null || resultCode != RESULT_OK ? null
                    : data.getData();
            if (result != null) {
                String imagePath = FileUtils.getPath(this, result);
                if (!TextUtils.isEmpty(imagePath)) {
                    result = Uri.parse("file:///" + imagePath);
                }
            }
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        } else if (requestCode == INPUT_FILE_REQUEST_CODE && mFilePathCallback != null) {
            // 5.0的回调
            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[]{Uri.parse(mCameraPhotoPath)};
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[]{Uri.parse(dataString)};
                    }
                }
            }

            mFilePathCallback.onReceiveValue(results);
            mFilePathCallback = null;
        } else {
            super.onActivityResult(requestCode, resultCode, data);
            return;
        }
    }

    private void imgReset() {
        mWebView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "var img = objs[i];   " +
                " img.style.maxWidth = '100%';" +
                "}" +
                "})()");
    }

    private void runWebviewUrl(final String url) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mWebView != null && !TextUtils.isEmpty(url)) {
                    mWebView.loadUrl(url);
                }
            }
        });
    }

}
