package com.ruansee.macall.testwebview.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.widget.LinearLayout;

import androidx.lifecycle.Lifecycle;

import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;
import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.callback.PermissionListener;
import com.rs.macall.androidx.basemodel.utils.HandlerUtils;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StatusBarUtil;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ruansee.macall.testwebview.BuildConfig;
import com.ruansee.macall.testwebview.R;
import com.ruansee.macall.testwebview.app.AppCacheData;
import com.ruansee.macall.testwebview.app.CrashHandler;
import com.ruansee.macall.testwebview.app.GPSLocationListener;
import com.ruansee.macall.testwebview.app.RuanseeApp;
import com.ruansee.macall.testwebview.app.WebActivityCallback;
import com.ruansee.macall.testwebview.app.WebViewPresenter;
import com.ruansee.macall.testwebview.databinding.ActivityOpenAppBinding;
import com.ruansee.macall.testwebview.model.SelectFileOptions;
import com.ruansee.macall.testwebview.provider.DownloadUtil;
import com.ruansee.macall.testwebview.utils.FileUtils;
import com.ruansee.macall.testwebview.utils.JiaMi;
import com.ruansee.macall.testwebview.utils.LocationGPSManage;
import com.ruansee.macall.unifyservemodulesdk.ErrorMsg;
import com.ruansee.macall.unifyservemodulesdk.USMComponentSDK;
import com.ruansee.macall.unifyservemodulesdk.USMConfigure;
import com.ruansee.macall.unifyservemodulesdk.USMListener;
import com.ruansee.macall.unifyservemodulesdk.bean.CarOcrDataBean;
import com.ruansee.macall.unifyservemodulesdk.bean.ComponentBaseBean;
import com.ruansee.macall.unifyservemodulesdk.bean.FaceIdentifyBean;
import com.ruansee.macall.unifyservemodulesdk.bean.NFCBean;
import com.ruansee.macall.unifyservemodulesdk.bean.OcrSfzBean;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OpenAppActivity extends BaseViewBindActivity<ActivityOpenAppBinding> implements PermissionListener {
    private WebViewPresenter webViewPresenter;
    /*统一服务组件SDK*/
    private USMComponentSDK usComponentSDK;
    private AndroidMethodInterface androidMethodInterface;
    private Handler myHandler;
//    private CalculateInterface calculateInterface;

    ///////////////// 接收参数的KEY //////////////////
    /*第三方应用appId*/
    public static final String paramKey9 = "appName";
    /*第三方应用appId*/
    public static final String paramKey1 = "APPId";
    /*第三方应用的秘钥  */
    public static final String paramKey2 = "secret";
    /*第三方应用的链接地址*/
    public static final String paramKey3 = "LinkUrl";
    /*第三方应用对应的消息ID*/
    public static final String paramKey4 = "msgId";
    /*第三方应用对应的消息类型：当有的应用有多个消息类型时根据此参数判断*/
    public static final String paramKey5 = "msgType";
    /*第三方应用的操作类型 默认为 ：login ，查看消息为： readMessage  查看搜索内容为：search */
    public static final String paramKey6 = "operationType";
    /*搜索类型 car / person*/
    public static final String paramKey7 = "searchType";
    /*搜索得到的数据Json 格式 */
    public static final String paramKey8 = "searchJson";

    /*搜 联系人 */
    public static final String paramKey10 = "ywry";
    /*联系人电话  */
    public static final String paramKey11 = "ywrylxdh";

    ///////////////// 接收参数的KEY //////////////////

    private AgentWeb mAgentWeb;
    private String appID;
    private String secret, appName;
    private String msgId, msgType, operationType;
    private String searchType, searchJson;
    private String intoUrl = "http://20.90.1.150:8888/";

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

    @Override
    protected ActivityOpenAppBinding getViewBinding() {
        return ActivityOpenAppBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void init() {
        Log.w(TAG, "init");
        webViewPresenter = new WebViewPresenter(getContext(), new WebActivityCallback() {
            @Override
            public void onShowOperationSelectDialog(String[] split, int whit) {
                webViewPresenter.onShowOperationSelectDialog(getActivity(), whit, split);
            }

            @Override
            public void onFinish() {
                finish();
            }
        });
        //统一服务组件
//        USMConfigure.getDefault().init("16854", "stegst");
        viewBinding.tvTestJs.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                mAgentWeb.getJsAccessEntrace().quickCallJs("callErrorResult", operationType, "test", "aseg");
//                mAgentWeb.getJsAccessEntrace().quickCallJs("callJS","a");
            }
        });
        androidMethodInterface = new AndroidMethodInterface();
        viewBinding.titleleft.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                androidMethodInterface.onBack();
            }
        });
        viewBinding.titleright.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                androidMethodInterface.exitToHome();
            }
        });
        viewBinding.btnRefresh.setOnClickListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                androidMethodInterface.reloadPage();
            }
        });
        myHandler = HandlerUtils.getActivity(this);
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {
        Log.w(TAG, "readInstanceState");
        if (savedInstanceState == null) {
            appID = getIntent().getStringExtra(paramKey1);
            secret = getIntent().getStringExtra(paramKey2);
            intoUrl = getIntent().getStringExtra(paramKey3);
            msgId = getIntent().getStringExtra(paramKey4);
            msgType = getIntent().getStringExtra(paramKey5);
            operationType = getIntent().getStringExtra(paramKey6);
            appName = getIntent().getStringExtra(paramKey9);
            searchType = getIntent().getStringExtra(paramKey7);
            searchJson = getIntent().getStringExtra(paramKey8);
            webViewPresenter.ywryName = getIntent().getStringExtra(paramKey10);
            webViewPresenter.ywryPhone = getIntent().getStringExtra(paramKey11);
            savePageCacheData(paramKey1, appID);
            savePageCacheData(paramKey2, secret);
            savePageCacheData(paramKey3, intoUrl);
            savePageCacheData(paramKey4, msgId);
            savePageCacheData(paramKey5, msgType);
            savePageCacheData(paramKey6, operationType);
            savePageCacheData(paramKey7, searchType);
            savePageCacheData(paramKey8, searchJson);
            savePageCacheData(paramKey9, appName);
            savePageCacheData(paramKey10, webViewPresenter.ywryName);
            savePageCacheData(paramKey11, webViewPresenter.ywryPhone);
        } else {
            appID = savedInstanceState.getString(paramKey1);
            secret = savedInstanceState.getString(paramKey2);
            intoUrl = savedInstanceState.getString(paramKey3);
            msgId = savedInstanceState.getString(paramKey4);
            msgType = savedInstanceState.getString(paramKey5);
            operationType = savedInstanceState.getString(paramKey6);
            appName = savedInstanceState.getString(paramKey9);
            searchType = savedInstanceState.getString(paramKey7);
            searchJson = savedInstanceState.getString(paramKey8);
            webViewPresenter.ywryName = savedInstanceState.getString(paramKey10);
            webViewPresenter.ywryPhone = savedInstanceState.getString(paramKey11);
        }
        usComponentSDK = USMConfigure.getDefault().getUsmComponentSDK(appID, secret);
        viewBinding.contentTitle.setText(appName);
        handInit();
    }

    @Override
    protected void start() {
        Log.w(TAG, "start");
//        initService();
        initWebView();
        usComponentSDK.setUSMListener(uscListener);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(needPermissions, this);
        } else {
            initData();
        }
    }

    private void initData() {
        FileUtils.initFilePath(getContext());
        createFileDir(FileUtils.FILE_DIR);
        createFileDir(FileUtils.DB_DIR);
        createFileDir(FileUtils.DOWNLOADS_DIR);
        createFileDir(FileUtils.IMAGE_DIR);
        createFileDir(FileUtils.VOID_DIR);
        createFileDir(FileUtils.LOG_DIR);
        Log.w("Log目录", FileUtils.LOG_DIR);
        CrashHandler.getInstance().init(getApplication(), FileUtils.LOG_DIR);

        String url = getUrl();
        LogUtils.d(TAG, url);
//        mAgentWeb.getUrlLoader().loadUrl("file:///android_asset/TestJs.html");
        mAgentWeb.getUrlLoader().loadUrl(url);
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == -55) {//刷新頁面
            if (!isDestroyed() && mAgentWeb != null) {
                mAgentWeb.getWebCreator().getWebView().reload();
                return;
            }
        }
        if (msg.what == -101) {
            baseDismissDialog();
            return;
        }
        if (msg.what == 200) {
            downFileError("下载成功！", "文件下载成功！");
            myHandler.sendEmptyMessageDelayed(103,800);
            return;
        }
        if (msg.what == -200) {
            downFileError("下载失败！", msg.obj+"");
            return;
        }
        if (msg.what == 102) {
            downFileError("文件下载中！", msg.obj+"");
            return;
        }
        if (msg.what == 103) {
            downDiag.dismiss();
        }

    }

    @Override
    protected void onPause() {
        if (mAgentWeb.getWebCreator() != null) {
            mAgentWeb.getWebLifeCycle().onPause();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
//        if (mResultCode == Activity.RESULT_CANCELED && isPermissionRequest) {
//            try {
//                if (mUploadMessageLollipop != null) {
//                    mUploadMessageLollipop.onReceiveValue(null);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        if (mAgentWeb.getWebCreator() != null) {
            mAgentWeb.getWebLifeCycle().onResume();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.w(TAG, "onDestroy");
        AgentWebConfig.clearDiskCache(this.getContext());
        LocationGPSManage.getInstance().stopLocation();
        if (mAgentWeb.getWebCreator() != null) {
            mAgentWeb.getWebLifeCycle().onDestroy();
        }
        androidMethodInterface = null;
        appID = "";
        secret = "";
//        if (mConn != null) {
//            unbindService(mConn);
//        }
    }

    /**
     * 绑定远程服务RemoteService
     */
//    private void initService() {
//        Log.w(TAG, "initService");
//        Intent intent = new Intent(getContext(), RemoteService.class);
////        intent.setComponent(new ComponentName("com.hongri.webview", "com.hongri.webview.service.RemoteService"));
//        bindService(intent, mConn, BIND_AUTO_CREATE);
//    }
//
//    private final ServiceConnection mConn = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
////            Log.w(TAG, "onServiceConnected");
//            //当Service绑定成功时，通过Binder获取到远程服务代理
//            calculateInterface = CalculateInterface.Stub.asInterface(service);
//
//            String url = getUrl();
//            LogUtils.d(TAG, url);
////            mAgentWeb.getUrlLoader().loadUrl("file:///android_asset/TestJs.html");
//            mAgentWeb.getUrlLoader().loadUrl(url);
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
////            Log.d(TAG, "onServiceDisconnected");
//            calculateInterface = null;
//        }
//    };
    private void createFileDir(String fileDirName) {
        File file = new File(fileDirName);
        if (file.exists()) return;
        file.mkdirs();
    }

    private void handInit() {
        if (StringUtil.isNullOrEmpty(operationType)) {
            operationType = "login";
        }
        if (StringUtil.isNullOrEmpty(intoUrl)) {
            intoUrl = "https://www.baidu.com/my/index";
        }
        webViewPresenter.intoUrl = intoUrl;
    }

    private void showJimi(String... content) {
        StringBuilder builder = new StringBuilder();
        String sp = "";
        for (String cont : content) {
            builder.append(sp);
            builder.append(cont);
            sp = "\n";
        }
        new AlertDialog.Builder(getContext())
                .setTitle("加密解密信息")
                .setMessage(builder.toString())
                .create()
                .show();
    }

    private String getUrl() {
        StringBuilder builder = new StringBuilder();
        builder.append(intoUrl);
        if (intoUrl.contains("?")) {
            builder.append("&userInfo=");
        } else {
            builder.append("?userInfo=");
        }
        String userInfo = new AndroidMethodInterface().getUserInfo();
        try {
            String decrypt1 = JiaMi.decrypt(userInfo, appID, secret);
            showJimi("加密内容:" + userInfo, "id:" + appID, "secret:" + secret, "解密后:" + decrypt1);
            LogUtils.w("解密", decrypt1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        builder.append(userInfo);
        if (operationType.equals("readMessage")) {
            if (StringUtil.hasContent(msgId)) {
                builder.append("&operation_type=readMessage");
                builder.append("&msg_id=");
                builder.append(msgId);
                if (StringUtil.hasContent(msgType)) {
                    builder.append("&msg_type=");
                    builder.append(msgType);
                }
            } else {
                builder.append("&operation_type=login");
            }
        } else if (operationType.equals("search")) {
            builder.append("&search_type=");
            builder.append(searchType);
            builder.append("&operation_type=search");
        } else {
            builder.append("&operation_type=login");
        }
        return builder.toString();
    }

    private void initWebView() {
        mAgentWeb = AgentWeb.with(getActivity())
                .setAgentWebParent(viewBinding.viewGroup, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .useDefaultIndicator()
                .setWebViewClient(webViewPresenter.mWebViewClient)
                .setWebChromeClient(webViewPresenter.mWebChromeClient)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .addJavascriptInterface(androidMethodInterface.toName(), androidMethodInterface)
                .createAgentWeb()
                .ready().get();
        WebSettings webSettings = mAgentWeb.getAgentWebSettings().getWebSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
//        webSettings.setLoadWithOverviewMode(true);
//        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setBlockNetworkImage(false);
//        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        // 设置支持本地存储
//        webSettings.setDatabaseEnabled(true);
//        //设置存储模式
//        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        webSettings.setAppCacheEnabled(true);


        mAgentWeb.getWebCreator().getWebView().setHorizontalScrollBarEnabled(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && BuildConfig.DEBUG) {
            mAgentWeb.getWebCreator().getWebView().setWebContentsDebuggingEnabled(true);
        }

        mAgentWeb.getWebCreator().getWebView().setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength) -> {
            ToastUtil.centered(getContext(), "下载监听被触发，请求地址：" + url1);
            if (StringUtil.isNullOrEmpty(url1)) {
                ToastUtil.centered(getContext(), "下载链接为空，请检查链接是否真实！");
                return;
            }
            String s1 = url1.toLowerCase();
            if (!s1.startsWith("http://") && !s1.startsWith("https://")) {
                ToastUtil.centered(getContext(), "URL缺少请求头，将默认使用Http协议下载");
                url1 = "http://" + url1;
            }

            String fileName = "";
            if (StringUtil.hasContent(contentDisposition)) {
                String[] split = contentDisposition.split("=");
                fileName = split[split.length - 1];
            }
            if (StringUtil.isNullOrEmpty(fileName)) {
                fileName = url1.substring(url1.lastIndexOf("/") + 1);
            }
            String jm = URLDecoder.decode(fileName);
            if (fileName.length() > jm.length()) {
                fileName = jm;
            }
            fileName = fileName.replace("/","_").replace("\\","_");

            String s = FileUtils.DOWNLOADS_DIR + fileName;
            File file = new File(s);
            //打开文件
            if (file.exists())
                FileUtils.openFileByPath(getActivity(), file.getAbsolutePath());
            else {
                downFileError("下载文件", "开始下载：" + fileName);
//                baseShowFaseDialog("温馨提示", String.format("正在下载'%s'，请稍后...", fileName));
                webViewPresenter.downloadFile(url1, fileName, new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        lastProgress = 0;
                        myHandler.sendEmptyMessage(-101);
                        if (file.exists()) {
                            //打开文件
                            myHandler.obtainMessage(200, "文件下载成功！").sendToTarget();
//                            downFileError("下载成功！", "文件下载成功！");
//                            ToastUtil.centered(getContext(), "文件下载成功！");
                            FileUtils.openFileByPath(getActivity(), file.getAbsolutePath());
                        } else {
                            myHandler.obtainMessage(-200, "文件保存失败！").sendToTarget();
//                            downFileError("下载失败！", "文件报错失败！");
//                            ToastUtil.centered(getContext(), "文件下载失败！");
                        }
                    }

                    @Override
                    public void onDownloading(int progress) {
                        if (progress == lastProgress){
                            return;
                        }
                        lastProgress = progress;
                        myHandler.obtainMessage(102, "开始下载进度：" + lastProgress + "%").sendToTarget();
//                        downFileError("下载文件","开始下载进度："+progress+"%s");
                    }

                    @Override
                    public void onDownloadFailed(String msg) {
                        lastProgress = 0;
                        myHandler.sendEmptyMessage(-101);
                        myHandler.obtainMessage(-200, msg).sendToTarget();
//                        downFileError("下载失败！", msg);
//                        ToastUtil.centered(getContext(), "文件下载失败:" + msg);
                    }
                });
            }
        });
    }
    private int lastProgress = 0;

    private AlertDialog downDiag;

    private void downFileError(String title, String msg) {
        if (downDiag == null) {
            downDiag = new AlertDialog.Builder(getContext())
                    .setTitle(title)
                    .setMessage(msg)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
        }
        if (!downDiag.isShowing()) {
            downDiag.show();
        }
        downDiag.setMessage(msg);
        downDiag.setTitle(title);
    }

    private final USMListener uscListener = new USMListener() {
        @Override
        public void onUSCSuccess(String operationType, ComponentBaseBean resultBean) {
            LogUtils.d(TAG, operationType);
            if (resultBean == null) {
                ToastUtil.centered(getContext(), "错误的返回值！");
                mAgentWeb.getJsAccessEntrace().quickCallJs("callErrorResult", operationType, String.valueOf(ErrorMsg.ERROR_RESULT.getIndex()), ErrorMsg.ERROR_RESULT.getName());
                return;
            }
            if (resultBean instanceof NFCBean) {
                NFCBean bean = (NFCBean) resultBean;
                ToastUtil.centered(getContext(), "NFC返回：" + bean.getName());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callNFCResult", new Gson().toJson(bean));
                return;
            }
            if (resultBean instanceof FaceIdentifyBean) {
                FaceIdentifyBean bean = (FaceIdentifyBean) resultBean;
                ToastUtil.centered(getContext(), "人像：" + bean.getName());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callFaceIdentifyResult", new Gson().toJson(bean));
                return;
            }
            if (resultBean instanceof OcrSfzBean) {
                OcrSfzBean bean = (OcrSfzBean) resultBean;
                ToastUtil.centered(getContext(), "OCR身份证返回：" + bean.getName());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callCORSfzResult", new Gson().toJson(bean));
                return;
            }
            if (resultBean instanceof CarOcrDataBean) {
                CarOcrDataBean bean = (CarOcrDataBean) resultBean;
                ToastUtil.centered(getContext(), "OCRCar返回：" + bean.getData().get(0).getPlateNumber());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callOCRCarResult", new Gson().toJson(bean));
            }
        }

        @Override
        public void onUSCError(String operationType, int code, String msg) {
            if (ErrorMsg.ERROR_USER_CANCEL.getIndex() != code) {
                ToastUtil.centered(getContext(), String.format("错误码%s || %s", code, msg));
            }
            mAgentWeb.getJsAccessEntrace().quickCallJs("callErrorResult", operationType, String.valueOf(code), msg);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        usComponentSDK.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (null == webViewPresenter.mFilePathCallback) return;
            switch (requestCode) {
                case WebViewPresenter.RESULT_CODE:
                    if (webViewPresenter.photoFile == null || !webViewPresenter.photoFile.exists())
                        return;
                    webViewPresenter.ysBitmap();
                    return;
                case WebViewPresenter.SELECT_IMG_CODE:
                case WebViewPresenter.SELECT_FILE_CODE:
                    webViewPresenter.onActivityResultAboveL(requestCode, resultCode, data);
                    return;
            }
        }
        if (webViewPresenter.mFilePathCallback != null) {
            webViewPresenter.onActivityResultAboveL(requestCode, resultCode, data);
//            webViewPresenter.mFilePathCallback.onReceiveValue(null);
            webViewPresenter.mFilePathCallback = null;
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mAgentWeb.handleKeyEvent(keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }

    private GPSLocationListener gpsLocationListener;

    private GPSLocationListener getGPSLocationListener() {
        return new GPSLocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                ToastUtil.centered(getContext(), "调用位置更新" + location.toString());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callLocationResult", location.getLongitude() + "", location.getLatitude() + "");
            }

            @Override
            public void stopLocation() {
                ToastUtil.centered(getContext(), "调用停止位置更新");
                if (mAgentWeb == null) return;
                try {
                    mAgentWeb.getJsAccessEntrace().quickCallJs("callLocationError", "-102", "停止定位");
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtil.centered(getContext(), "ERROR:" + e.getMessage());
                    finish();
                }
            }
        };
    }

    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CALL_PHONE,
            Manifest.permission.ACCESS_NETWORK_STATE
    };

    @Override
    public void onGranted() {
        initData();
    }

    @Override
    public void onDenied(List<String> deniDPermission) {
        showMissingPermissionDialog();
    }

    private class AndroidMethodInterface {

        @JavascriptInterface
        public void startLocation() {
            LocationGPSManage manage = LocationGPSManage.getInstance();
            if (gpsLocationListener == null) {
                gpsLocationListener = getGPSLocationListener();
            }
            manage.addGPSLocationListener(gpsLocationListener);
            try {
                manage.startGPSLocation(getContext());
            } catch (RuntimeException e) {
                ToastUtil.centered(getContext(), "没有权限，请先授权定位权限！");
                showMissingPermissionDialog();
            }
        }

        @JavascriptInterface
        public void stopLocation() {
//            ToastUtil.centered(getContext(),"H5调用了停止定位");
            LocationGPSManage manage = LocationGPSManage.getInstance();
            if (gpsLocationListener == null) {
                gpsLocationListener = getGPSLocationListener();
            }
            manage.removeGPSLocationListener(gpsLocationListener);
            manage.stopLocation();
        }

        /**
         * 获取用户信息，为Base64转码的Json对象
         * Json格式：{"userCode":"警号","userName":"姓名","idCardNum":"身份证号","deptCode":"组织机构代码","deptName":"组织机构代码名称"}
         */
        @JavascriptInterface
        public String getUserInfo() {
//            try {
//                return calculateInterface.getJiaMi(appID, secret);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//                return "";
//            }
            AppCacheData userData = RuanseeApp.getAppCacheData();
            Map<String, String> param = new HashMap<>();
            param.put("userCode", userData.getUserCode());
            param.put("userName", userData.getUserName());
            param.put("idCardNum", userData.getIdCardNum());
            param.put("deptCode", userData.getDeptCode());
            param.put("deptName", userData.getDeptName());
            String s = new Gson().toJson(param);
            return JiaMi.desCrypto(s.getBytes(), appID, secret);
        }

        /**
         * 配置上传文件选择项。此方法再调用上传文件的事件之前调用，如果不调用则默认 selfRealization = false , 其他参数默认为 true
         *
         * @param selfRealization 是否由JS自己实现文件选择上传。
         *                        PS: true:由JS自己实现，Android原生不做操作，不会弹出选择框,.值为false时将原生代码将拦截操作并根据下面参数配置弹出选择框。
         * @param isCamera        PS:是否支持相机拍照：  true =  支持相机拍照上传，false = 不支持相机拍照上传，值为false时弹出框将没有相机选项
         * @param isDCIM          PS:是否支持相册选择：  true =  支持相册选择上传，false = 不支持相册选择上传，值为false时弹出框将没有相册选项
         * @param isFileSelection PS:是否支持文件选择：  true =  支持文件选择上传，false = 不支持文件选择上传，值为false时弹出框将没有文件选择选项
         */
        @JavascriptInterface
        public void setUploadFileOptions(boolean selfRealization, boolean isCamera, boolean isDCIM, boolean isFileSelection) {
            if (webViewPresenter.selectFileOptions == null) {
                webViewPresenter.selectFileOptions = new SelectFileOptions(selfRealization, isCamera, isDCIM, isFileSelection);
            } else {
                webViewPresenter.selectFileOptions.configureOptions(selfRealization, isCamera, isDCIM, isFileSelection);
            }
        }

        /**
         * 调用返回按钮
         */
        @JavascriptInterface
        public void onBack() {
            if (mAgentWeb.back()) return;
            finish();
        }

        /**
         * 控制APP标题栏显示隐藏
         *
         * @param isShow true = 显示 ||  false = 隐藏
         */
        @JavascriptInterface
        public void isTitleBlock(boolean isShow) {
            isTitleBlock(isShow, false);
        }


        /**
         * 控制APP标题栏显示隐藏
         *
         * @param isShow true = 显示 ||  false = 隐藏
         */
        @JavascriptInterface
        public void isTitleBlock(boolean isShow, boolean showMsg) {
            if (isShow) {
                visibleView(viewBinding.baseTitle);
                if (showMsg) {
                    visibleView(viewBinding.btnMsg);
                    setViewOnClickListener(viewBinding.btnMsg);
                } else {
                    goneView(viewBinding.btnMsg);
                }
            } else {
                goneView(viewBinding.baseTitle);
            }
        }

        /**
         * 退出到主页
         */
        @JavascriptInterface
        public void exitToHome() {
            finish();
        }

        /**
         * 设置状态栏颜色及状态栏图标字体颜色深浅模式
         *
         * @param statusBarColor   状态栏颜色 值为字符串 格式为：#ffffff
         * @param isBlackFontColor 是否为   true 为黑色字体   |    false 为白色字体
         */
        @JavascriptInterface
        public void setSystemStatusBarStyle(String statusBarColor, boolean isBlackFontColor) {
            int i = strToTextColor(statusBarColor, "#3255E3");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    StatusBarUtil.setStatusBarColor(getActivity(), i, isBlackFontColor);
                    try {
                        ColorDrawable drawable = new ColorDrawable(i);
                        viewBinding.vTopSeize.setBackground(drawable);
                        viewBinding.baseTitle.setBackground(drawable);
                        if (isBlackFontColor) {
                            viewBinding.contentTitle.setTextColor(getColors(R.color.colorGrey8));
                            viewBinding.btnMsg.setImageDrawable(getDrawable(R.drawable.icon_msg_ld_back));
                            viewBinding.leftImage.setImageDrawable(getDrawables(R.drawable.ic_back_b));
                            viewBinding.rightImage.setImageDrawable(getDrawables(R.drawable.icon_over_back));
                            viewBinding.btnRefresh.setImageDrawable(getDrawables(R.drawable.icon_refresh_grad));
                        } else {
                            viewBinding.contentTitle.setTextColor(getColors(R.color.colorWhite));
                            viewBinding.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
                            viewBinding.rightImage.setImageDrawable(getDrawables(R.drawable.icon_over));
                            viewBinding.btnRefresh.setImageDrawable(getDrawables(R.drawable.icon_refresh));
                            viewBinding.btnMsg.setImageDrawable(getDrawable(R.drawable.icon_msg_ld_white));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        /**
         * @color:后台返回的色值
         * @defaultColor:ui默认的色值
         */
        private int strToTextColor(String color, String defaultColor) {
            if (StringUtil.isNullOrEmpty(color)) {
                return Color.parseColor(defaultColor);
            }
            if (!StringUtil.isNullOrEmpty(color) && (color.length() == 7) && (color.startsWith("#"))) {
                return Color.parseColor(color);
            } else {
                return Color.parseColor(defaultColor);
            }
        }

        @JavascriptInterface
        public String toName() {
            return "callByAndroid";
        }

        /**
         * 弹出提示框
         *
         * @param title     提示标题
         * @param msg       提示内容
         * @param lxryName  联系人员
         * @param lxryPhone 联系电话
         */
        @JavascriptInterface
        public void showNetPermission(String title, String msg, String lxryName, String lxryPhone) {
            webViewPresenter.showLoadWebError(title, msg, lxryName, lxryPhone);
        }

        @JavascriptInterface
        public void reloadPage() {
            reloadPageAndroid();
        }

        /**
         * 刷新页面
         */
        private void reloadPageAndroid() {
            if (mAgentWeb == null) return;
            //拿到这个页面，最后一次加载的url
            String lastLoadUrl = mAgentWeb.getWebCreator().getWebView().getUrl();
            LogUtils.w("最后加载链接", lastLoadUrl);
            //停止上次刷新
            mAgentWeb.getUrlLoader().stopLoading();
//            AgentWebConfig.removeAllCookies();
            AgentWebConfig.clearDiskCache(getContext());
            mAgentWeb.getUrlLoader().loadUrl(lastLoadUrl);
            if (myHandler != null && lastLoadUrl != null) {
                myHandler.sendEmptyMessageDelayed(-55, 50);
            }
        }

        /**
         * 打开人像比对
         */
        @JavascriptInterface
        public void goPersonFaceModule() {
            ToastUtil.centered(getContext(), "Android 原生方法 goPersonFaceModule() 被调用，该功能将打开人像比对功能！");
            usComponentSDK.openFaceIdentifyComponent(OpenAppActivity.this);
        }

        /**
         * 打开NFC组件
         */
        @JavascriptInterface
        public void goNFCModule() {
            ToastUtil.centered(getContext(), "Android 原生方法 goNFCModule() 被调用，该功能将打开NFC识别功能！");
            usComponentSDK.openNFCComponent(OpenAppActivity.this);
        }

        /**
         * 打开OCR组件
         */
        @JavascriptInterface
        public void goOCRCarModule() {
            ToastUtil.centered(getContext(), "Android 原生方法 goOCRCarModule() 被调用，该功能将打开OCR车牌识别功能！");
            usComponentSDK.openOcrCarComponent(OpenAppActivity.this);
        }

        /**
         * 打开OCR组件
         */
        @JavascriptInterface
        public void goOCRSfzModule() {
            ToastUtil.centered(getContext(), "Android 原生方法 goOCRSfzModule() 被调用，该功能将打开OCR车牌识别功能！");
            usComponentSDK.openOcrSfzComponent(OpenAppActivity.this);
        }
    }


}