package com.ycgis.macall.personalcenter.v.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothDevice;
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.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 com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.DefaultWebClient;
import com.king.zxing.CameraScan;
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.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 com.ycgis.macall.personalcenter.BuildConfig;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityOpenAppBinding;
import com.ycgis.macall.personalcenter.m.datamodel.PrintModel;
import com.ycgis.macall.personalcenter.m.model.SelectFileOptions;
import com.ycgis.macall.personalcenter.p.app.CrashHandler;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.app.UserData;
import com.ycgis.macall.personalcenter.p.callback.BluetoothFragmentListener;
import com.ycgis.macall.personalcenter.p.callback.GPSLocationListener;
import com.ycgis.macall.personalcenter.p.callback.WebActivityCallback;
import com.ycgis.macall.personalcenter.p.presenter.WebViewPresenter;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.DownloadUtil;
import com.ycgis.macall.personalcenter.util.BluetoothManage;
import com.ycgis.macall.personalcenter.util.FileUtils;
import com.ycgis.macall.personalcenter.util.JiaMi;
import com.ycgis.macall.personalcenter.util.LocationGPSManage;
import com.ycgis.macall.personalcenter.v.fragment.BluetoothDialogFragment;
import com.ycgis.zpSDK.BluetoothSocket;


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

import java.util.ArrayList;
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 GPSLocationListener gpsLocationListener;


    ///////////////// 接收参数的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();
            }
        });
        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);

        /**
         * 需要进行检测的权限数组
         */
        List<String> needPermissions = new ArrayList<>();
        needPermissions.add(Manifest.permission.CAMERA);
        needPermissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        needPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        needPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
        needPermissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        needPermissions.add(Manifest.permission.READ_PHONE_STATE);
        needPermissions.add(Manifest.permission.CALL_PHONE);
        needPermissions.add(Manifest.permission.ACCESS_NETWORK_STATE);

        if (Build.VERSION.SDK_INT >= 31) {
            needPermissions.add("android.permission.BLUETOOTH_SCAN");
            needPermissions.add("android.permission.BLUETOOTH_CONNECT");
            needPermissions.add("android.permission.BLUETOOTH_ADVERTISE");
        }

        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);
        ApiModel.uploadOperationLog("3", "3", "用户打开H5应用：" + appName);
    }

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == -55) {//刷新頁面
            if (!isDestroyed() && mAgentWeb != null) {
                mAgentWeb.getWebCreator().getWebView().reload();
            }
            return;
        }
    }

    @Override
    protected boolean isEventBus() {
        return false;
    }


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

    @Override
    protected void onResume() {
        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();
        }
        BluetoothSocket.getInstance().disconnect();
        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 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);
//            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();
    }

    @SuppressLint("SetJavaScriptEnabled")
    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 (BuildConfig.DEBUG) {
            mAgentWeb.getWebCreator().getWebView().setWebContentsDebuggingEnabled(true);
        }

        mAgentWeb.getWebCreator().getWebView().setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength) -> {
            if (StringUtil.isNullOrEmpty(url1)) {
                ToastUtil.showTest(getContext(), "下载链接为空，请检查链接是否真实！");
                return;
            }
            String s1 = url1.toLowerCase();
            if (!s1.startsWith("http://") && !s1.startsWith("https://")) {
                ToastUtil.showTest(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 {
                baseShowDialog(String.format("正在下载'%s'，请稍后...", fileName));
                webViewPresenter.downloadFile(url1, fileName, new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        baseDismissDialog();
                        if (file.exists()) {
                            //打开文件
                            ToastUtil.centered(getContext(), "文件下载成功！");
                            FileUtils.openFileByPath(getActivity(), file.getAbsolutePath());
                        } else {
                            ToastUtil.centered(getContext(), "文件下载失败！");
                        }
                    }

                    @Override
                    public void onDownloading(int progress) {

                    }

                    @Override
                    public void onDownloadFailed(String msg) {
                        baseDismissDialog();
                        ToastUtil.centered(getContext(), "文件下载失败:" + msg);
                    }
                });
            }
        });
    }

    /**
     * 统一服务组件回调
     */
    private USMListener uscListener = new USMListener() {
        @Override
        public void onUSCSuccess(String operationType, ComponentBaseBean resultBean) {
            LogUtils.d(TAG, operationType);
            if (resultBean == null) {
                ToastUtil.showTest(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.showTest(getContext(), "NFC返回：" + bean.getName());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callNFCResult", new Gson().toJson(bean));
                return;
            }
            if (resultBean instanceof FaceIdentifyBean) {
                FaceIdentifyBean bean = (FaceIdentifyBean) resultBean;
                ToastUtil.showTest(getContext(), "人像：" + bean.getName());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callFaceIdentifyResult", new Gson().toJson(bean));
                return;
            }
            if (resultBean instanceof OcrSfzBean) {
                OcrSfzBean bean = (OcrSfzBean) resultBean;
                ToastUtil.showTest(getContext(), "OCR身份证返回：" + bean.getName());
                mAgentWeb.getJsAccessEntrace().quickCallJs("callCORSfzResult", new Gson().toJson(bean));
                return;
            }
            if (resultBean instanceof CarOcrDataBean) {
                CarOcrDataBean bean = (CarOcrDataBean) resultBean;
                ToastUtil.showTest(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.showTest(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 (requestCode == 15015 && resultCode == Activity.RESULT_OK) {
            if (data == null) return;
            String stringExtra = data.getStringExtra(CameraScan.SCAN_RESULT);
            mAgentWeb.getJsAccessEntrace().quickCallJs("callScanCodeResult", stringExtra);
            return;
        }
        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 (requestCode == BluetoothManage.REQUEST_OPEN_BLUETOOTH) {
            if (resultCode == Activity.RESULT_OK) {
                if (!BluetoothManage.getInstance().isBluetoothOpen(getActivity(), false)) {
                    ToastUtil.centered(getContext(), "请打开蓝牙功能后使用！");
                    return;
                }
            }
        }
        if (webViewPresenter.mFilePathCallback != null) {
            webViewPresenter.onActivityResultAboveL(requestCode, resultCode, data);
//            webViewPresenter.mFilePathCallback.onReceiveValue(null);
            webViewPresenter.mFilePathCallback = null;
        }
        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 getGPSLocationListener() {
        return new GPSLocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                ToastUtil.showTest(getContext(), "调用位置更新" + location.toString());
                if (location != null) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs("callLocationResult", location.getLongitude() + "", location.getLatitude() + "");
                }
            }

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


    @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.showTest(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 "";
//            }
            UserData userData = RuanseeApplication.getUserData();
            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);
        }

        /**
         * TODO 该方法不能弹出选择框，此方法是在JS调用选择文件方法之前调用的。在使用JS调选择文件时将根据此方法的配置做对应操作
         * 配置上传文件选择项。此方法再调用上传文件的事件之前调用，如果不调用则默认 selfRealization = false , 其他参数默认为 true
         * 详情查看 {@link WebViewPresenter#mWebChromeClient} 的 onShowFileChooser(WebView, ValueCallback<Uri[]> , FileChooserParams ) 方法
         *
         * @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时弹出框将没有文件选择选项
         *                        TODO 当且仅当 selfRealization = true && (isCamera | isDCIM | isFileSelection ) 只有一个为 true 时 将没有弹框，直接跳转对应操作
         */
        @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) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (isShow) {
                        visibleView(viewBinding.baseTitle);
                    } 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.leftImage.setImageDrawable(getDrawable(R.drawable.ic_back_b));
                            viewBinding.rightImage.setImageDrawable(getDrawable(R.drawable.icon_over_back));
                            viewBinding.btnRefresh.setImageDrawable(getDrawable(R.drawable.icon_refresh_grad));
                        } else {
                            viewBinding.contentTitle.setTextColor(getColors(R.color.colorWhite));
                            viewBinding.leftImage.setImageDrawable(getDrawable(R.drawable.back_cliener));
                            viewBinding.rightImage.setImageDrawable(getDrawable(R.drawable.icon_over));
                            viewBinding.btnRefresh.setImageDrawable(getDrawable(R.drawable.icon_refresh));
                        }
                    } 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();
        }

        /**
         * 扫码
         */
        @JavascriptInterface
        public void scanCode() {
            Intent intent = new Intent(getContext(), ScanCodeActivity.class);
            startActivityForResult(intent, 15015);
        }

        /**
         * 刷新页面
         */
        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() {
            usComponentSDK.openFaceIdentifyComponent(OpenAppActivity.this);
        }

        /**
         * 打开NFC组件
         */
        @JavascriptInterface
        public void goNFCModule() {
            usComponentSDK.openNFCComponent(OpenAppActivity.this);
        }

        /**
         * 打开OCR组件
         */
        @JavascriptInterface
        public void goOCRCarModule() {
            usComponentSDK.openOcrCarComponent(OpenAppActivity.this);
        }

        /**
         * 打开OCR组件
         */
        @JavascriptInterface
        public void goOCRSfzModule() {
            usComponentSDK.openOcrSfzComponent(OpenAppActivity.this);
        }

        @JavascriptInterface
        public void openBluetooth() {
            BluetoothManage instance = BluetoothManage.getInstance();
            if (!instance.init()) {
                ToastUtil.centered(getContext(), "当前设备不支持蓝牙！");
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", "-1", "当前设备不支持蓝牙");
                return;
            }
            if (!instance.isBluetoothOpen(getActivity(), true)) {
                ToastUtil.centered(getContext(), "请先打开蓝牙！");
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", "-2", "蓝牙未打卡");
                return;
            }
            BluetoothDevice remoteDevice = BluetoothSocket.getInstance().getRemoteDevice();
            if (remoteDevice!=null){
                ToastUtil.centered(getContext(),"蓝牙已连接");
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothResult", "1", "蓝牙已连接！");
            }else {
                openBluetoothFragment();
            }
        }

        /**
         * [
         * {"content":"文字内容",
         * "printType":1,
         * "pageWidth":100,
         * "pageHeight":100
         * },
         * {"content":"二维码内容",
         * "printType":2,
         * "zoomLevel":5,
         * "pageWidth":100,
         * "pageHeight":100
         * },
         * {"content":"base64",
         * "printType":3,
         * "contentWidth:":90,
         * "contentHeight:":90,
         * "pageWidth":100,
         * "pageHeight":100
         * }
         * ]
         * @param json
         */
        @JavascriptInterface
        public void printContentsJSON(String json) {
            ToastUtil.centered(getContext(),"JS调起打印事件");
            LogUtils.w(TAG,"打印内容："+json);
            if (StringUtil.isNullOrEmpty(json)) {
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", "-3", "没有打印内容！");
                return;
            }
            Type type = new TypeToken<List<PrintModel>>() {
            }.getType();
            List<PrintModel> data = new Gson().fromJson(json, type);
            boolean b = BluetoothSocket.getInstance().sendData(data);
            if (b) {
                ToastUtil.centered(getContext(),"打印完成");
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothResult", "2", "打印完成！");
            } else {
                ToastUtil.centered(getContext(),"打印失败");
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", "-4", "打印失败！");
            }
        }
    }

    private void openBluetoothFragment() {
// 在Activity中
        BluetoothDialogFragment dialog = new BluetoothDialogFragment();
        dialog.setBluetoothFragmentListener(new BluetoothFragmentListener() {
            @Override
            public void onClickBluetoothDevice(BluetoothDevice device) {
                    linkBluetooth(device);
            }

            @Override
            public void onError(int code, String msg) {
                mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", code+"",msg);
            }
        });
        dialog.show(getSupportFragmentManager(), "MyDialog");
    }

    private boolean isLinkPrinter = false;

    /*
     *链接蓝牙
     */
    private void linkBluetooth(BluetoothDevice device) {
        baseShowDialog("正在链接");
        if (!BluetoothSocket.getInstance().ConnectPrinter(device.getAddress())) {
            ToastUtil.centered(getContext(),"蓝牙连接失败");
            //Toast.makeText(this, "Connect Fail", Toast.LENGTH_SHORT).show();
            baseDismissDialog();
            mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothError", "-3", "蓝牙连接失败！");
            isLinkPrinter = false;
        } else {
            ToastUtil.centered(getContext(),"蓝牙已连接");
            mAgentWeb.getJsAccessEntrace().quickCallJs("callBluetoothResult", "1", "蓝牙已连接！");
            baseDismissDialog();
            isLinkPrinter = true;
        }
    }
}