package com.tjzhxx.union.system;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tjzhxx.union.R;
import com.tjzhxx.union.activity.AuthenticationActivity;
import com.tjzhxx.union.activity.DataEditeDbjzActivity;
import com.tjzhxx.union.activity.DataEditeJtccActivity;
import com.tjzhxx.union.activity.DataEditeWzzjActivity;
import com.tjzhxx.union.activity.DataEditeXcjzActivity;
import com.tjzhxx.union.activity.DataEditeYwsgActivity;
import com.tjzhxx.union.activity.DataEditeZywwActivity;
import com.tjzhxx.union.activity.LoginActivity;
import com.tjzhxx.union.activity.SignatureSureActivity;
import com.tjzhxx.union.dialog.DialogNoMemberDialog;
import com.tjzhxx.union.entity.AuthenticationInfo;
import com.tjzhxx.union.entity.UserInfo;
import com.tjzhxx.union.entity.request.SubnewworkerRequest;
import com.tjzhxx.union.public_store.ConstDefine;
import com.tjzhxx.union.public_store.DownloadThread;
import com.tjzhxx.union.public_store.FileUtils;
import com.tjzhxx.union.public_store.LogUtils;

import java.io.File;
import java.lang.reflect.Type;

import butterknife.BindView;

/**
 * 描述:
 *
 * @author yanghuaxiong
 * @create 2018/8/17  上午10:46
 */
public class WebviewActivity extends BaseActivity {
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.webview)
    WebView webview;
    private String title;
    private String url;
    private AuthenticationInfo authenticationInfo;
    private UserInfo userInfo;
    @Override
    public int getContentViewLayoutID() {
        return R.layout.activity_webview;
    }

    @Override
    public void bindViewAndEvent(Bundle savedInstanceState) {
        title = getIntent().getStringExtra("title");
        authenticationInfo = (AuthenticationInfo) getIntent().getSerializableExtra("AuthenticationInfo");
        userInfo = (UserInfo) getIntent().getSerializableExtra("UserInfo");
        initTitle(title);
        url = getIntent().getStringExtra("url");
        webview.loadUrl(url);//加载url
        webview.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        webview.setWebChromeClient(webChromeClient);
        webview.setWebViewClient(webViewClient);
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setDomStorageEnabled(true);
        webSettings.setBlockNetworkImage(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressbar.setVisibility(View.GONE);
            Gson gson = new Gson();
            if (authenticationInfo != null) {
                webview.loadUrl("javascript:setIdcardInfo('" + gson.toJson(authenticationInfo) + "')");
            }
            if (userInfo != null) {
                webview.loadUrl("javascript:getUserInfo('" + gson.toJson(userInfo) + "')");
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressbar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            if (url.equals("http://www.google.com/")) {
//                return true;//表示我已经处理过了
//            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webview, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webview.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressbar.setProgress(newProgress);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webview.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webview.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 跳转到身份认证界面
     */
    @JavascriptInterface
    public void toAuthentication() {
        Intent intent = new Intent(this, AuthenticationActivity.class);
        startActivity(intent);
        finish();
    }

    /**
     * 跳转到签名页面
     */
    @JavascriptInterface
    public void toSignature(String json) {
        Gson gson = new Gson();
        Type type = new TypeToken<SubnewworkerRequest>() {
        }.getType();
        SubnewworkerRequest request = gson.fromJson(json, type);
        Intent intent = new Intent(this, SignatureSureActivity.class);
        intent.putExtra("SubnewworkerRequest", request);
        startActivity(intent);
        finish();
    }

    /**
     * 跳转到现场救助助上传资料
     */
    @JavascriptInterface
    public void toDataXcjz() {
        if (ConstDefine.userInfo == null) {
            DialogNoMemberDialog dialog = new DialogNoMemberDialog(this);
            dialog.setOnSureListener(new DialogNoMemberDialog.OnSureListener() {
                @Override
                public void onSureListener() {
                    Intent intent = new Intent(WebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
            dialog.show();
        } else {
            if (ConstDefine.userInfo.getIsactive().equals("1")) {
                Intent intent = new Intent(this, DataEditeXcjzActivity.class);
                startActivity(intent);
                finish();
            } else {
                showSnackBar("请先缴费");
            }
        }
    }

    /**
     * 跳转到住院关爱慰问资料填写页面
     */
    @JavascriptInterface
    public void toDataZyww() {
        if (ConstDefine.userInfo == null) {
            DialogNoMemberDialog dialog = new DialogNoMemberDialog(this);
            dialog.setOnSureListener(new DialogNoMemberDialog.OnSureListener() {
                @Override
                public void onSureListener() {
                    Intent intent = new Intent(WebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
            dialog.show();
        } else {
            if (ConstDefine.userInfo.getIsactive().equals("1")) {
                Intent intent = new Intent(this, DataEditeZywwActivity.class);
                startActivity(intent);
                finish();
            } else {
                showSnackBar("请先缴费");
            }
        }
    }

    /**
     * 跳转到大病救助资料填写页面
     */
    @JavascriptInterface
    public void toDataDbjz() {
        if (ConstDefine.userInfo == null) {
            DialogNoMemberDialog dialog = new DialogNoMemberDialog(this);
            dialog.setOnSureListener(new DialogNoMemberDialog.OnSureListener() {
                @Override
                public void onSureListener() {
                    Intent intent = new Intent(WebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
            dialog.show();
        } else {
            if (ConstDefine.userInfo.getIsactive().equals("1")) {
                Intent intent = new Intent();
                intent.setClass(this, WebviewActivity.class);
                intent.putExtra("url", ConstDefine.HttpAdressH5 + "/index.html#/rescueillnessdata");
                intent.putExtra("title", "大病救助资料填写");
                startActivity(intent);
                finish();
            } else {
                showSnackBar("请先缴费");
            }
        }
    }

    /**
     * 跳转到大病救助资料图片上传页
     */
    @JavascriptInterface
    public void toDbRescue(String json) {
        Intent intent = new Intent(this, DataEditeDbjzActivity.class);
        intent.putExtra("json", json);
        startActivity(intent);
    }

    /**
     * 跳转到五种重疾资料填写页面
     */
    @JavascriptInterface
    public void toDataWzzj() {
        if (ConstDefine.userInfo == null) {
            DialogNoMemberDialog dialog = new DialogNoMemberDialog(this);
            dialog.setOnSureListener(new DialogNoMemberDialog.OnSureListener() {
                @Override
                public void onSureListener() {
                    Intent intent = new Intent(WebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
            dialog.show();
        } else {
            if (ConstDefine.userInfo.getIsactive().equals("1")) {
                Intent intent = new Intent(this, DataEditeWzzjActivity.class);
                startActivity(intent);
                finish();
            } else {
                showSnackBar("请先缴费");
            }
        }
    }

    /**
     * 跳转到意外离世资料填写页面
     */
    @JavascriptInterface
    public void toDataYwls() {
        if (ConstDefine.userInfo == null) {
            DialogNoMemberDialog dialog = new DialogNoMemberDialog(this);
            dialog.setOnSureListener(new DialogNoMemberDialog.OnSureListener() {
                @Override
                public void onSureListener() {
                    Intent intent = new Intent(WebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
            dialog.show();
        } else {
            if (ConstDefine.userInfo.getIsactive().equals("1")) {
                Intent intent = new Intent(this, DataEditeYwsgActivity.class);
                startActivity(intent);
                finish();
            } else {
                showSnackBar("请先缴费");
            }
        }
    }

    /**
     * 跳转到家庭财产资料填写页面
     */
    @JavascriptInterface
    public void toDataJtcc() {
        if (ConstDefine.userInfo == null) {
            DialogNoMemberDialog dialog = new DialogNoMemberDialog(this);
            dialog.setOnSureListener(new DialogNoMemberDialog.OnSureListener() {
                @Override
                public void onSureListener() {
                    Intent intent = new Intent(WebviewActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
            dialog.show();
        } else {
            if (ConstDefine.userInfo.getIsactive().equals("1")) {
                Intent intent = new Intent(this, DataEditeJtccActivity.class);
                startActivity(intent);
                finish();
            } else {
                showSnackBar("请先缴费");
            }
        }
    }


    /**
     * 打开文件
     */
    @JavascriptInterface
    public void openFile(String json) {
        LogUtils.e("TAG",json);
        File[] files = FileUtils.getFileList(FileUtils.getNewsFilePath(this));
        for (File file : files) {
            if (json.contains(file.getName())) {
                FileUtils.openFile(mContext, file);
               return;
            }
        }
        String fileName = json.substring(json.lastIndexOf("/")+1);
        LogUtils.e("TAG",fileName);
        showProgressBar("加载中...");
        DownloadThread downloadThread = new DownloadThread(json, FileUtils.getNewsFilePath(mContext), fileName, new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    if (msg.arg1 == 100) {
                        hideProgressBar();
                        FileUtils.openFile(mContext,(File) msg.obj);
                    }
                }
                if (msg.what == -1) {
                    hideProgressBar();
                    showSnackBar("下载失败");
                }
            }
        }, 0);
        downloadThread.start();
    }
    /**
     * 关闭页面
     *
     */
    @JavascriptInterface
    public void closePage() {
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
        webview.destroy();
        webview = null;
    }

}
