package com.naz.sdkdemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.naz.sdkdemo.activity.ble.comm.ObserverManager;
import com.naz.sdkdemo.base.BaseActivity;
import com.naz.sdkdemo.bean.PrintModule;
import com.naz.sdkdemo.bean.PrintModule2;
import com.naz.sdkdemo.bean.PrintModule3;
import com.naz.sdkdemo.helper.SerialPortManager;
import com.naz.sdkdemo.http.ApiHelper;
import com.naz.sdkdemo.utils.MyTools;
import com.naz.sdkdemo.weight.UserCache;
import com.naz.sdkdemo.weight.XToast;
//import com.tencent.smtt.export.external.interfaces.WebResourceError;
//import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
//import com.tencent.smtt.sdk.WebSettings;
//import com.tencent.smtt.sdk.WebView;
//import com.tencent.smtt.sdk.WebViewClient;

import net.posprinter.IConnectListener;
import net.posprinter.IDeviceConnection;
import net.posprinter.POSConnect;
import net.posprinter.TSPLConst;
import net.posprinter.TSPLPrinter;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import androidx.annotation.NonNull;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.video.MediaStoreOutputOptions;
import androidx.camera.video.Recorder;
import androidx.camera.video.Recording;
import androidx.camera.video.VideoCapture;
import androidx.camera.video.VideoRecordEvent;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;

import static net.posprinter.TSPLConst.FNT_SIMPLIFIED_CHINESE;
import static net.posprinter.TSPLConst.ROTATION_90;

import android_serialport_api.SerialPortFinder;

public class MainActivity extends BaseActivity {
    private final String TAG = "HomeActivity";

    private WebView mWebView;
    private LinearLayout ll_nonet;
    private LinearLayout ll_web;

    private Button printBtn;
    private LinearLayout bottomToolBar;
    private Button connectBtn;
    private Button connectLight;
    private Button turnOnLight;
    private Button closeLight;
    private TSPLPrinter printer;

    String savePath;
    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
    private PreviewView previewView;
    private RelativeLayout previewViewLayout;
    private ProcessCameraProvider cameraProvider;
    private ImageCapture imageCapture;

    private VideoCapture videoCapture;
    private Recording recording;

    private String bleName;
    private int code=0;//0默认值，1未搜索到设备，2连接失败，3连接成功，4断开了，5打开通知失败，6打开通知成功

    // 相机现在是否正在打开, 用于处理用户在照相机预览页面点击返回按钮的情况
    private boolean cameraIsOpening = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_home_web;
    }

    @Override
    protected void initView() {

        ll_nonet = findViewById(R.id.ll_nonet);
        ll_web = findViewById(R.id.ll_web);
        mWebView = findViewById(R.id.webview);
        previewView = findViewById(R.id.previewView);
        previewViewLayout = findViewById(R.id.rl_preview);

        checkNet();
        findViewById(R.id.bt_ref).setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                getUrl();
            }
        });
        getUrl();
        WebSettings ws = mWebView.getSettings();
        // 网页内容的宽度是否可大于WebView控件的宽度
        ws.setLoadWithOverviewMode(false);
        // 保存表单数据
        ws.setSaveFormData(true);
        // 是否应该支持使用其屏幕缩放控件和手势缩放
        ws.setSupportZoom(true);
        ws.setBuiltInZoomControls(true);
        ws.setDisplayZoomControls(false);
        // 启动应用缓存
        ws.setAppCacheEnabled(true);
        // 设置缓存模式
        ws.setCacheMode(WebSettings.LOAD_DEFAULT);
        // setDefaultZoom  api19被弃用
        // 设置此属性，可任意比例缩放。
        ws.setUseWideViewPort(true);
        // 不缩放
        mWebView.setInitialScale(100);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        // 告诉WebView启用JavaScript执行。默认的是false。
        ws.setJavaScriptEnabled(true);
        //  页面加载好以后，再放开图片
        ws.setBlockNetworkImage(false);
        // 使用localStorage则必须打开
        ws.setDomStorageEnabled(true);
        // WebView是否新窗口打开(加了后可能打不开网页)
        ws.setSupportMultipleWindows(true);
//        String systemUserAgent = MyTools.getUserAgent(ws, getApplicationContext());
        //        ws.setUserAgentString(systemUserAgent + "Zuyu_Android");
        ws.setAllowContentAccess(true);
        ws.setJavaScriptCanOpenWindowsAutomatically(true);
        ws.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        /** 设置字体默认缩放大小(改变网页字体大小,setTextSize  api14被弃用) */
        ws.setTextZoom(100);
        aIn = new AndroidInterface();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 允许javascript出错
            try {
                Method method = Class.forName("android.webkit.WebView").
                        getMethod("setWebContentsDebuggingEnabled", Boolean.TYPE);
                if (method != null) {
                    method.setAccessible(true);
                    method.invoke(null, true);
                }
            } catch (Exception e) {
                // do nothing
            }
        }
        mWebView.addJavascriptInterface(aIn, "androidJs");
        mWebView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                ll_nonet.setVisibility(View.GONE);
                ll_web.setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                if (mUrl.startsWith("http://") || mUrl.startsWith("https://")) { // 4.0以上必须要加
                    view.loadUrl(mUrl);
                    return true;
                }
                return false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Log.e("----------->","------->request="+request);
                Log.e("----------->","------->error="+error);
            }
        });

        // 照相机预览框底部工具栏
        bottomToolBar = findViewById(R.id.ll_bottom_tool_bar);
        bottomToolBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toCloseCamera();
            }
        });
        printBtn = findViewById(R.id.print);
        printBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                String json = "[{\"created_date_lt\":\"2024-03-09T10:05:07.000Z\",\"created_date\":\"2024-03-09T10:05:07.632Z\",\"last_modified_by_show\":\"李晓\",\"device_code\":\"DV00001\",\"material_code\":\"40010101000001\",\"last_modified_by\":\"3\",\"unit_code_show\":\"张\",\"bus_type_dk\":\"SUPPLIER\",\"created_by\":\"3\",\"unit_code\":\"ST\",\"dynamic_form_value_id\":\"554243331748798464\",\"supplier_code_show\":\"湖北鹰冠新型材料科技有限公司\",\"device_code_show\":\"测试设备\",\"belong_org\":\"S000233\",\"bus_type_dk_show\":\"工厂\",\"created_by_show\":\"李晓\",\"id\":\"554243331786547200\",\"supplier_code\":\"S000233\",\"main_table_id\":null,\"last_modified_date_lt\":\"2024-03-09T10:05:07.000Z\",\"material_code_show\":\"尊贵免漆板E0小标\",\"qty\":1984,\"specs\":null,\"box_code\":\"CK00001\",\"request_id\":null,\"detail_table_id\":null,\"last_modified_date\":\"2024-03-09T10:05:07.637Z\",\"box_code_show\":\"设备仓\",\"in_stock_qty\":496,\"use_qty\":-1488,\"safe_stock_qty\":1000,\"min_stock_qty\":500,\"is_choose\":true,\"old_roll_qr_code\":\"\",\"roll_qr_code\":\"1711532698000\"}]";
//                Gson gson=new Gson();
//                Type type = new TypeToken<List<PrintModule3>>(){}.getType();
//                List<PrintModule3> data = gson.fromJson(json, type);
//                if (data == null) {
//                    return;
//                }
//                startPrint3(data);
                String json = "[{\n" +
                        "\t\"now_date\": \"2024-04-14\",\n" +
                        "\t\"box_date\": \"2024-03-27T08:55:01.569Z\",\n" +
                        "\t\"delivery_flag\": 0,\n" +
                        "\t\"status_dk_show\": \"已包\",\n" +
                        "\t\"status_dk\": \"PACKAGED\",\n" +
                        "\t\"print_flag\": 0,\n" +
                        "\t\"no\": \"BZ2024032700001\",\n" +
                        "\t\"device_code_show\": \"测试设备\",\n" +
                        "\t\"device_code\": \"DV00001\",\n" +
                        "\t\"dynamic_form_value_id\": \"560748673298993152\",\n" +
                        "\t\"id\": \"560748673403850752\",\n" +
                        "\t\"main_table_id\": null,\n" +
                        "\t\"request_id\": null,\n" +
                        "\t\"box_order_product\": {\n" +
                        "\t\t\"customer_no\": \"C00912\",\n" +
                        "\t\t\"process_title_two\": null,\n" +
                        "\t\t\"customer_name\": \"信息中心客户-测试\",\n" +
                        "\t\t\"color_two\": null,\n" +
                        "\t\t\"dealer_name\": \"信息中心经销商-测试\",\n" +
                        "\t\t\"order_item_id\": \"553451940644175872\",\n" +
                        "\t\t\"process_title\": \"同步\",\n" +
                        "\t\t\"material_title\": \"大王椰1800尊贵型E0指接香杉木-银盾抗菌生态免漆板W\",\n" +
                        "\t\t\"order_no\": \"SO202403070001\",\n" +
                        "\t\t\"box_num\": 50,\n" +
                        "\t\t\"dealer_no\": \"C00911\",\n" +
                        "\t\t\"color\": \"春华秋实\",\n" +
                        "\t\t\"material_no\": \"BC170202000001\",\n" +
                        "\t\t\"material_size\": \"3300-4\",\n" +
                        "\t\t\"dynamic_form_value_id\": \"560748673298993152\",\n" +
                        "\t\t\"id\": \"560748673416433664\",\n" +
                        "\t\t\"main_table_id\": \"560748673403850752\",\n" +
                        "\t\t\"request_id\": null\n" +
                        "\t},\n" +
                        "\t\"is_choose\": true\n" +
                        "}]";
                Gson gson=new Gson();
                Type type = new TypeToken<List<PrintModule2>>(){}.getType();
                List<PrintModule2> data = gson.fromJson(json, type);
                if (data == null) {
                    return;
                }
                startPrint2(data);
            }
        });
        connectBtn = findViewById(R.id.connect);
        connectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectUSB(searchUsb());
            }
        });
        connectLight = findViewById(R.id.connect2);
        turnOnLight = findViewById(R.id.light);
        connectLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toConnectLight(UserCache.getSerialName());
            }
        });
        turnOnLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (serialPortManager != null){
                    serialPortManager.turnOnLight(6);
                }
            }
        });
        closeLight = findViewById(R.id.closeLight);
        closeLight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (serialPortManager!=null){
                    serialPortManager.close();
                    serialPortManager = null;
                }
            }
        });

        findViewById(R.id.take_photo).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Log.e("-------->","------->path="+getImagePath("123.jpg"));
                savePicture(new File(getImagePath("123.jpg")), "ceshi", "202119");
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        savePicture(new File(getImagePath("234.jpg")), "ceshi", "202119");
//                    }
//                }, 20000);
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        savePicture(new File(getImagePath("345.jpg")), "ceshi", "202119");
//                    }
//                }, 30000);
//                startActivity(new Intent(MainActivity.this, CaremaActivity.class));
            }
        });

        findViewById(R.id.start_scan).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                checkPermissions("dawangye");
//                startActivity(new Intent(MainActivity.this, CaremaActivity.class));
            }
        });

        findViewById(R.id.close_scan).setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                toCloseScan();
//                startActivity(new Intent(MainActivity.this, CaremaActivity.class));
            }
        });

        Log.e("------->","-------->"+UserCache.getSerialName());
    }

    private AndroidInterface aIn;

    private class AndroidInterface {

        @JavascriptInterface
        public void takePhoto(String path, String name) {
            Log.e(TAG, "takePhoto");
            toTakePhoto(path, name);
        }

        @JavascriptInterface
        public void openRecorder(boolean isShowPreview) {
            Log.e(TAG, "openRecorder");
            toOpenRecorder(isShowPreview);
        }

        @JavascriptInterface
        public void getAllPort() {
            // 遍历串口
            SerialPortFinder finder = new SerialPortFinder();
            String[] allDevicesPath = finder.getAllDevicesPath();
            String str = String.join(",", allDevicesPath);
            // 将结果返回给web页面
            runOnUiThread(() -> mWebView.loadUrl("javascript:getAllPort('" + str + "')"));
        }

        @JavascriptInterface
        public void refreshData() {
            Log.e(TAG, "clearCache");
            mWebView.clearCache(false);
            mWebView.reload();
        }

        //打印
        @JavascriptInterface
        public void printF(String json) {
            Log.e(TAG, "printF json"+json);

            Gson gson=new Gson();
            Type type = new TypeToken<List<PrintModule>>(){}.getType();
            List<PrintModule> data = gson.fromJson(json, type);
            if (data == null) {
                return;
            }
            startPrint(data);
        }

        @JavascriptInterface
        public void printF2(String json) {
            Log.e(TAG, "printF2 json"+json);

            Gson gson=new Gson();
            Type type = new TypeToken<List<PrintModule2>>(){}.getType();
            List<PrintModule2> data = gson.fromJson(json, type);
            if (data == null) {
                return;
            }
            startPrint2(data);
        }

        @JavascriptInterface
        public void printF3(String json) {
            Log.e(TAG, "printF3 json"+json);

            Gson gson=new Gson();
            Type type = new TypeToken<List<PrintModule3>>(){}.getType();
            List<PrintModule3> data = gson.fromJson(json, type);
            if (data == null) {
                return;
            }
            startPrint3(data);
        }

        @JavascriptInterface
        public void startScan(String name) {
            Log.e(TAG, "startScan name"+name);
            checkPermissions(name);
        }

        @JavascriptInterface
        public void closeScan() {
            Log.e(TAG, "closeScan");
            toCloseScan();
        }

        @JavascriptInterface
        public void openCamera(boolean isShowPreview) {
            Log.e(TAG, "openCamera");
            // 打开摄像头
            toOpenCamera(isShowPreview);
        }
        @JavascriptInterface
        public void closeCamera() {
            Log.e(TAG, "closeCamera");
            toCloseCamera();
        }

        @JavascriptInterface
        public void openPrinter() {
            Log.e(TAG, "openPrinter");
            connectUSB(searchUsb());
        }

        @JavascriptInterface
        public void closePrinter() {
            Log.e(TAG, "closePrinter");
            closeUSB();
        }

        @JavascriptInterface
        public void connectLight(String name) {
            Log.e(TAG, "connectLight");
            toConnectLight(name);
        }

        @JavascriptInterface
        public void controlLight(int address, int type) {
            Log.e(TAG, "openLight"+"address="+address+",type="+type);
            if (serialPortManager != null){
                serialPortManager.turnOnLight(address, type);
            }
        }

        @JavascriptInterface
        public void disConnectLight() {
            Log.e(TAG, "closeLight");
            if (serialPortManager!=null){
                serialPortManager.close();
                serialPortManager = null;
            }
        }

        @JavascriptInterface
        public void getPort() {
            Log.e(TAG, "getPort");
            mWebView.loadUrl("javascript:getPort('" + UserCache.getSerialPortName() + "')");
        }

        @JavascriptInterface
        public void connectPort(String name) {
            Log.e(TAG, "connectPort");
            toConnectPort(name);
        }

        @JavascriptInterface
        public void disConnectPort(String name) {
            Log.e(TAG, "disConnectPort");
            for (SerialPortManager port:mPortList) {
                if (port.serialHelper.getPort().equals(name)) {
                    port.close();
                    return;
                }
            }
        }

        @JavascriptInterface
        public void disConnectPortAll() {
            Log.e(TAG, "disConnectPortAll");
            mPortList.clear();
//            for (SerialPortManager port:mPortList) {
//                port.close();
//            }
        }
    }

    private void toCloseCamera() {
        // 如果相机预览还开着, 则关闭
        cameraIsOpening = false;
        if(previewViewLayout.getVisibility() == View.VISIBLE) {
            previewViewLayout.setVisibility(View.GONE);
        }
        // 关闭的时候摄像头还在录像
        if(recording!=null) {
            openAndCloseVideo();
        }
        if (cameraProvider!=null){
            cameraProvider.unbindAll();
        }
    }

    private void toOpenCamera(boolean isShowPreview) {
        cameraIsOpening = true;
        // 请求 CameraProvider
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        //检查 CameraProvider 可用性，验证它能否在视图创建后成功初始化
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider, isShowPreview, 1);
            } catch (Exception e) {
                // No errors need to be handled for this Future.
                // This should never be reached.
                Log.i(TAG, "toOpenCamera: exception: " + e.getMessage());
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void toOpenRecorder(boolean isShowPreview) {
        cameraIsOpening = true;
        // 请求 CameraProvider
        cameraProviderFuture = ProcessCameraProvider.getInstance(this);
        //检查 CameraProvider 可用性，验证它能否在视图创建后成功初始化
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider, isShowPreview, 2);
            } catch (Exception e) {
                // No errors need to be handled for this Future.
                // This should never be reached.
                Log.i(TAG, "toOpenRecorder: exception: " + e.getMessage());
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void toTakePhoto(String path, String name) {
        Log.e("-------->","------>toTakePhoto");
        long timeStamp = System.currentTimeMillis();
        savePath = timeStamp+".jpg";

        // 通过 ContentValues 对象设置文件名和文件类型
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, savePath);
        contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");

        File dir = new File(Environment.getExternalStorageDirectory() + "/camera/");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //创建文件
        File file = new File(dir,savePath);
        ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(file).build();

        imageCapture.takePicture(
                // 第一个参数 OutputFileOptions 指定了照片保存的位置和格式等信息。
                outputFileOptions,
                // 第二个参数 Executor 指定了保存照片时要运行的线程。
                ContextCompat.getMainExecutor(this),
                // 第三个参数 OnImageSavedCallback 指定了保存照片完成后的回调函数，可以在其中进行一些提示或其他操作。
                new ImageCapture.OnImageSavedCallback() {
                    @SuppressLint("RestrictedApi")
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        Log.e("-------->","------>savePath="+outputFileResults.getSavedUri().getPath());
                        Log.e("-------->","------>保存成功");
//                        Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                        savePicture(file, path, name);
                        mWebView.loadUrl("javascript:uploadPhotoPath('" + outputFileOptions.getFile().getAbsolutePath() + "')");
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        Log.e("----------->","------->"+exception.getMessage());
//                        Toast.makeText(MainActivity.this, "Error: " + exception.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void openAndCloseVideo() {
        if (videoCapture != null) {
            if (recording != null) {
                recording.stop();
                recording = null;
                return;
            }
            String name = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS", Locale.SIMPLIFIED_CHINESE).format(System.currentTimeMillis()) + ".mp4";
            ContentValues contentValues = new ContentValues();
            contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, name);
            contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "video/mp4");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, "Movies/CameraX-Video");
            }
            MediaStoreOutputOptions mediaStoreOutputOptions = new MediaStoreOutputOptions
                    .Builder(getContentResolver(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI)
                    .setContentValues(contentValues)
                    .build();
            Recorder recorder = (Recorder) videoCapture.getOutput();
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            recording = recorder.prepareRecording(this, mediaStoreOutputOptions)
                    .withAudioEnabled()
                    .start(ContextCompat.getMainExecutor(this), videoRecordEvent -> {
                        if (videoRecordEvent instanceof VideoRecordEvent.Start) {
                           // 开始录像
                            XToast.showToast("开始录制");
                        } else if (videoRecordEvent instanceof VideoRecordEvent.Finalize) {
                            if (((VideoRecordEvent.Finalize) videoRecordEvent).hasError()) {
                                // 中途意外结束
                                if (recording != null) {
                                    recording.close();
                                    recording = null;
                                }
                            } else {
                                // 正常结束
                                String msg = "视频为" + ((VideoRecordEvent.Finalize) videoRecordEvent).getOutputResults().getOutputUri();
                                XToast.showToast("录像保存成功");
                            }
                        }
                    });
        }
    }

    boolean isStart = false;
    ExecutorService fixedThreadPool;
    private void savePicture(File file, String path, String name) {
        if (!isStart){
            isStart = true;
            int numberOfCores = Runtime.getRuntime().availableProcessors();
            Log.i("--------->", "-------->cpu核心数" + numberOfCores);
            fixedThreadPool = Executors.newFixedThreadPool(2*numberOfCores+1);
        }
        try {
            fixedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    Log.i("--------->", "-------->uploadPicture" + file.getAbsolutePath());
                    ApiHelper.uploadPicture(MainActivity.this, file, path, name);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void checkNet() {
        if (!MyTools.isNetworkAvailable(getApplicationContext())) {
            ll_nonet.setVisibility(View.VISIBLE);
            ll_web.setVisibility(View.GONE);
        } else {
            ll_nonet.setVisibility(View.GONE);
            ll_web.setVisibility(View.VISIBLE);
        }
    }

    String mUrl = "https://dwytb.qingyaokeji.com/index.html#/";
    private void getUrl() {
        mWebView.loadUrl(mUrl);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    static int mPot = 8;//mm转像素8倍
    static int mWFont = 24;//字体宽度
    static int mHFont = 24;//字体高度
    static int mPaperWidth = 78;//纸张宽度78mm
    static int mPaperHeight = 132;//纸张高度132mm
    static int fontSizeMultiple = 2;//字体倍数
    static int mOffsetY = 5;//打印开始点离左边的距离（Y轴）,5mm
    static int mOffsetX = mPaperWidth-5;//打印开始点离上边的距离（X轴）,5mm
    static int mFontWidth = mWFont * fontSizeMultiple;//文字的宽度
    static int mFontHeight = mHFont * fontSizeMultiple;//文字的高度
    static int mSpace = 4;//行列间隔-----5mm
    static int mTextSpace = 1;//换行间距----2mm
    static int mCodeSize = 30;//二维码宽高----30mm

    private void startPrint(List<PrintModule> data) {
        for (PrintModule module:data) {
            printer.sizeMm(mPaperWidth, mPaperHeight)
                    .density(10)
                    .reference(mPaperWidth*mPot, 0)
                    .direction(TSPLConst.DIRECTION_FORWARD)
                    .cls()
                    .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "销售订单号：")
                    .text(mOffsetX*mPot, mOffsetY*mPot+(6*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.exe_sale_order_b.no)
                    .text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "产品名称：");
            String[] productName = getStrs(module.material_code_show, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot-5*mFontWidth);
            printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
            int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
            if (!TextUtils.isEmpty(productName[1])){
                currentHeight = currentHeight-mTextSpace*mPot;
                printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
                currentHeight = currentHeight-mFontHeight;
            }
            if (!TextUtils.isEmpty(productName[2])){
                currentHeight = currentHeight-mTextSpace*mPot;
                printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
                currentHeight = currentHeight-mFontHeight;
            }
            currentHeight = currentHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "经销商：")
                    .text(currentHeight, mOffsetY*mPot+(4*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.exe_sale_order_b.customer_name);
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装单号：")
                    .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_no)
                    .text(currentHeight, mOffsetY*mPot+(5*mFontWidth)+getStrLength(module.box_no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装数量：")
                    .text(currentHeight, mOffsetY*mPot+(10*mFontWidth)+getStrLength(module.box_no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_num);
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "花色：")
                    .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.decor_code_show);
            if (module.decor_two_code_show!=null){
                printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.decor_code_show)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.decor_two_code_show);
            }
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "工艺：")
                    .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.craft_type_code_show);
            if (module.craft_type_two_code_show!=null){
                printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.craft_type_code_show)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.craft_type_two_code_show);
            }
            printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
            printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.box_no);
            printer.print();
        }
    }

    private void startPrint2(List<PrintModule2> data) {
        for (PrintModule2 module:data) {
            printer.sizeMm(mPaperWidth, mPaperHeight)
                    .density(10)
                    .reference(mPaperWidth*mPot, 0)
                    .direction(TSPLConst.DIRECTION_FORWARD)
                    .cls()
                    .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "销售订单号：")
                    .text(mOffsetX*mPot, mOffsetY*mPot+(6*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.order_no)
                    .text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "产品名称：");
            String[] productName = getStrs(module.box_order_product.material_title, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot-5*mFontWidth);
            printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
            int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
            if (!TextUtils.isEmpty(productName[1])){
                currentHeight = currentHeight-mTextSpace*mPot;
                printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
                currentHeight = currentHeight-mFontHeight;
            }
            if (!TextUtils.isEmpty(productName[2])){
                currentHeight = currentHeight-mTextSpace*mPot;
                printer.text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
                currentHeight = currentHeight-mFontHeight;
            }
            currentHeight = currentHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "经销商：")
                    .text(currentHeight, mOffsetY*mPot+(4*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.customer_name);
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装单号：")
                    .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.no)
                    .text(currentHeight, mOffsetY*mPot+(5*mFontWidth)+getStrLength(module.no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "包装数量：")
                    .text(currentHeight, mOffsetY*mPot+(10*mFontWidth)+getStrLength(module.no)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.box_num);
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "花色：")
                    .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.color);
            if (module.box_order_product.color_two!=null){
                printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.box_order_product.color)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.color_two);
            }
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "工艺：")
                    .text(currentHeight, mOffsetY*mPot+(3*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.process_title);
            if (module.box_order_product.process_title_two!=null){
                printer.text(currentHeight, mOffsetY*mPot+(3*mFontWidth)+getStrLength(module.box_order_product.process_title)+mSpace*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_order_product.process_title_two);
            }
            printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
            printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.no);
            printer.print();
        }
    }

    private void startPrint3(List<PrintModule3> data) {
        for (PrintModule3 module:data) {
            printer.sizeMm(mPaperWidth, mPaperHeight)
                    .density(10)
                    .reference(mPaperWidth*mPot, 0)
                    .direction(TSPLConst.DIRECTION_FORWARD)
                    .cls()
                    .text(mOffsetX*mPot, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.box_code_show);
            String[] productName = getStrs(module.material_code_show, (mPaperHeight-2*mOffsetY-mSpace-mCodeSize)*mPot);
            printer.text((mOffsetX-mSpace)*mPot-mFontHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[0]);
            int currentHeight = (mOffsetX-mSpace)*mPot-2*mFontHeight;
            if (!TextUtils.isEmpty(productName[1])){
                currentHeight = currentHeight-mTextSpace*mPot;
                printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[1]);
            }
            if (!TextUtils.isEmpty(productName[2])){
                currentHeight = currentHeight-mTextSpace*mPot-mFontHeight;
                printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, productName[2]);
            }
            currentHeight = currentHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "商标编码：")
                    .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.material_code);
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, mOffsetY*mPot, FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, "余标：")
                    .text(currentHeight, mOffsetY*mPot+(5*mFontWidth), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.qty);
            printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.roll_qr_code), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.roll_qr_code);
            currentHeight = currentHeight-mFontHeight-mSpace*mPot;
            printer.text(currentHeight, (mPaperHeight-5)*mPot-getStrLength(module.now_date), FNT_SIMPLIFIED_CHINESE, ROTATION_90, fontSizeMultiple,fontSizeMultiple, module.now_date);
            printer.qrcode((mOffsetX-30)*mPot, (mPaperHeight-5-30)*mPot, TSPLConst.EC_LEVEL_H, 10, TSPLConst.QRCODE_MODE_MANUAL, TSPLConst.ROTATION_0, module.roll_qr_code);

            printer.print();
        }
    }

    // 选择相机并绑定生命周期和用例
    // bindType: 1-绑定照相机, 2-绑定录像机
    private void bindPreview(@NonNull ProcessCameraProvider cp, boolean isShowPreview, int bindType) {
        this.cameraProvider=cp;
        Preview preview = new Preview.Builder()
                .build();

        @SuppressLint("UnsafeOptInUsageError")
        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)//CameraSelector.LENS_FACING_EXTERNAL
                .build();
        // 打开摄像头的同时是否显示预览界面
        if(isShowPreview) {
           preview.setSurfaceProvider(previewView.getSurfaceProvider());
           previewViewLayout.setVisibility(View.VISIBLE);
        }
        cameraProvider.unbindAll();//解绑组件
        if(bindType == 1) {
            // 创建一个 ImageCapture 对象，用于拍摄照片。
            // 设置拍照模式为最小化延迟模式，这意味着拍照时将尽可能快地捕获图像。
            videoCapture = null;
            imageCapture = new ImageCapture.Builder()
                    .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                    // 设置JPEG的质量为85%
                    .setJpegQuality(85)
                    .build();
            cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, imageCapture);
        }else if(bindType == 2) {
            // 创建一个 videoCapture 对象，用于录像
            // 打开后自动录像
            boolean isAutoTake = true;
            imageCapture = null;
            Recorder recorder = new Recorder.Builder().build();
            videoCapture = VideoCapture.withOutput(recorder);
            cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview, videoCapture);
            if(isAutoTake) {
                openAndCloseVideo();
            }
        }
//        preview.setSurfaceProvider(previewView.getSurfaceProvider());
    }

    public static int getStrLength(String xm){
        int xmLength = 0;
        for (int i = 0; i < xm.length(); i++) {
            char chr = xm.charAt(i);
            if (isChinese(chr)){
                xmLength+=(mWFont*fontSizeMultiple);
            }else {
                xmLength+=(mWFont*fontSizeMultiple/2);
            }
        }
        Log.e("------->","----->xmStrLength="+xmLength);
        return xmLength;
    }

    public static String[] getStrs(String xm, int maxLength){
        Log.e("------->","----->maxLength="+maxLength);
        String[] resultStrs = new String[3];
        int xmLength = 0;
        int xmIndex = 0;
        String xmStr1 = "", xmStr2 = "", xmStr3 = "";
        boolean isLn = false;
        for (int i = 0; i < xm.length(); i++) {
            char chr = xm.charAt(i);
            if (isChinese(chr)){
                xmLength+=(mWFont*fontSizeMultiple);
            }else {
                xmLength+=(mWFont*fontSizeMultiple/2);
            }
            if (!isLn){
                if (xmLength>maxLength){
                    isLn = true;
                    xmIndex = i;
                }
            }
        }
        Log.e("------->","----->index="+xmIndex);
        String str = xm;
        if (xmLength>maxLength){
            xmStr1 = str.substring(0, xmIndex);
            String xmStr = xm.substring(xmIndex);

            int xmLength2 = 0;
            int xmIndex2 = 0;
            boolean isLn2 = false;
            for (int i = 0; i < xmStr.length(); i++) {
                char chr = xmStr.charAt(i);
                if (isChinese(chr)){
                    xmLength2+=24*fontSizeMultiple;
                }else {
                    xmLength2+=12*fontSizeMultiple;
                }
                if (!isLn2){
                    String str2 = xmStr;
                    if (xmLength2>maxLength){
                        isLn2 = true;
                        xmIndex2 = i;

                        xmStr2 = str2.substring(0, xmIndex2);
                        xmStr3 = xmStr.substring(xmIndex2);
                    }else{
                        xmStr2 = str2;
                        xmStr3 = "";
                    }
                }
            }
        }else {
            xmStr1 = str;
            xmStr2 = "";
            xmStr3 = "";
        }
        Log.e("------->","----->xmStr1="+xmStr1);
        Log.e("------->","----->xmStr2="+xmStr2);
        Log.e("------->","----->xmStr3="+xmStr3);
        resultStrs[0] = xmStr1;
        resultStrs[1] = xmStr2;
        resultStrs[2] = xmStr3;
        return resultStrs;
    }

    public static boolean isChinese(char chr) {
        boolean isChinese = false;
        //if ((int)str[i] > 127)//判断是否是汉字
        if ((int)chr > 0x4E00 && (int)chr < 0x9FA5) {
            isChinese = true;
        } else {
            isChinese = false; ;
        }
        return isChinese;
    }

    public static String getImagePath(String imageName) {
        File picturesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File imageFile = new File(picturesDir, imageName);
        return imageFile.exists() ? imageFile.getAbsolutePath() :"";
    }

    private static final int REQUEST_CODE_OPEN_GPS = 1;
    private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
    private void checkPermissions(String name) {
        bleName = name;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
            return;
        }

        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            Log.e("------->","----->checkPermissions permissionDeniedList="+permissionDeniedList);
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }

    private void onPermissionGranted(String permission) {
        Log.e("------->","----->onPermissionGranted permission="+permission);
        switch (permission) {
            case Manifest.permission.ACCESS_FINE_LOCATION:
                setScanRule();
                startScan(bleName);
//                Log.e("------->","----->checkGPSIsOpen="+checkGPSIsOpen());
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
//                    new AlertDialog.Builder(this)
//                            .setTitle(R.string.notifyTitle)
//                            .setMessage(R.string.gpsNotifyMsg)
//                            .setNegativeButton(R.string.cancel,
//                                    new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            finish();
//                                        }
//                                    })
//                            .setPositiveButton(R.string.setting,
//                                    new DialogInterface.OnClickListener() {
//                                        @Override
//                                        public void onClick(DialogInterface dialog, int which) {
//                                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                                            startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
//                                        }
//                                    })
//
//                            .setCancelable(false)
//                            .show();
//                } else {
//                    setScanRule();
//                    startScan(bleName);
//                }
                break;
        }
    }

    //关闭蓝牙扫码器
    BleDevice mBleDevice;
    BluetoothGattCharacteristic mCharacteristic;
    private void toCloseScan(){
        if (mBleDevice!=null){
            if (BleManager.getInstance().isConnected(mBleDevice)) {
                BleManager.getInstance().disconnect(mBleDevice);
            }
            BleManager.getInstance().removeNotifyCallback(mBleDevice, mCharacteristic.getService().getUuid().toString());
            BleManager.getInstance().clearCharacterCallback(mBleDevice);
            BleManager.getInstance().removeConnectGattCallback(mBleDevice);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_GPS) {
//            if (checkGPSIsOpen()) {
                setScanRule();
                startScan(bleName);
//            }
        }
    }

    @Override
    public void onBackPressed() {
        if(cameraIsOpening) {
            // 当前的摄像头正在打开状态
            toCloseCamera();
            return;
        }
        super.onBackPressed();
    }

    private boolean checkGPSIsOpen() {
//        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//        if (locationManager == null)
//            return false;
//        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGpsEnabled || isNetworkEnabled;
    }

    private void setScanRule() {
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setScanTimeOut(10000)              // 扫描超时时间，可选，默认10秒
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
    }

    //开始蓝牙扫码器
    private void startScan(String name) {
//        Toast.makeText(MainActivity.this, "开始连接", Toast.LENGTH_SHORT).show();
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {

            }

            @Override
            public void onLeScan(BleDevice bleDevice) {
                super.onLeScan(bleDevice);
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if ((name+"BLE").equals(bleDevice.getName())){
//                    Toast.makeText(MainActivity.this, "名字匹配去链接", Toast.LENGTH_SHORT).show();
                    if (!BleManager.getInstance().isConnected(bleDevice)) {
                        BleManager.getInstance().cancelScan();
                        connect(bleDevice);
                    }
                }else {
//                    Toast.makeText(MainActivity.this, "名字不匹配", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                boolean isScanSuccess = false;
                for (int i = 0; i < scanResultList.size(); i++) {
                    BleDevice bleDevice = scanResultList.get(i);
                    if ((name+"BLE").equals(bleDevice.getName())){
                        isScanSuccess = true;
                    }
                }
//                Toast.makeText(MainActivity.this, "扫描完成，是否成功="+isScanSuccess, Toast.LENGTH_SHORT).show();
                if (isScanSuccess){
                    mWebView.loadUrl("javascript:responseCode('1')");
                }
            }
        });
    }

    private void connect(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e("-------->","------>连接失败");
//                Toast.makeText(MainActivity.this, "连接失败", Toast.LENGTH_SHORT).show();
                mWebView.loadUrl("javascript:responseCode('2')");
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                Log.e("-------->","------>连接成功");
//                Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                mBleDevice = bleDevice;
                mWebView.loadUrl("javascript:responseCode('3')");
                if (BleManager.getInstance().isConnected(bleDevice)) {
                    BluetoothGattService bluetoothGattService = null;
                    for (BluetoothGattService service : gatt.getServices()) {
                        if (service.getUuid().toString().contains("0000feea")){
                            bluetoothGattService = service;
                        }
                    }
                    if (bluetoothGattService!=null){
                        List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
                        for (int i = 0; i < characteristics.size(); i++) {
                            BluetoothGattCharacteristic characteristic = characteristics.get(i);
                            if (characteristic.getUuid().toString().contains("00002aa1")){
                                mCharacteristic = characteristic;
                                BleManager.getInstance().notify(
                                        bleDevice,
                                        characteristic.getService().getUuid().toString(),
                                        characteristic.getUuid().toString(),
                                        new BleNotifyCallback() {

                                            @Override
                                            public void onNotifySuccess() {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
//                                                        Toast.makeText(MainActivity.this, "打开通知成功", Toast.LENGTH_SHORT).show();
                                                        Log.e("-------->","-------->打开通知成功");
                                                        mWebView.loadUrl("javascript:responseCode('6')");
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onNotifyFailure(final BleException exception) {
                                                Log.e("-------->","------>打开通知失败");
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
//                                                        Toast.makeText(MainActivity.this, "连接通知失败", Toast.LENGTH_SHORT).show();
                                                        mWebView.loadUrl("javascript:responseCode('5')");
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onCharacteristicChanged(byte[] data) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
//                                                        Log.e("-------->","-------->data="+(HexUtil.formatHexString(data, true)));
                                                        Log.e("-------->","-------->接收数据data="+(hexStringToGbk(HexUtil.formatHexString(data, false))));
//                                                        Toast.makeText(MainActivity.this, "接收数据="+(hexStringToGbk(HexUtil.formatHexString(characteristic.getValue(), false))), Toast.LENGTH_SHORT).show();
                                                        mWebView.loadUrl("javascript:responseData('"+(hexStringToGbk(HexUtil.formatHexString(data, false)))+"')");
//                                                        Log.e("-------->","-------->接收数据data="+(hexStringToGbk(HexUtil.formatHexString(characteristic.getValue(), false))));
//                                                        Log.e("-------->","-------->data="+(HexUtil.formatHexString(characteristic.getValue(), true)));
                                                    }
                                                });
                                            }
                                        });
                            }
                        }
                    }
                }
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
                mBleDevice = null;
                if (isActiveDisConnected) {
                    Log.e("-------->","------>断开了");
                    mWebView.loadUrl("javascript:responseCode('4')");
                } else {
                    Log.e("-------->","------>连接断开");
                    mWebView.loadUrl("javascript:responseCode('5')");
                    ObserverManager.getInstance().notifyObserver(bleDevice);
                }
            }
        });
    }

    public String hexStringToGbk(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i+1), 16));
        }

        try {
            return new String(bytes, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    IDeviceConnection curConnect = null;
    private void connectUSB(String pathName){
        if (curConnect!=null){
            curConnect.close();
        }
        curConnect = POSConnect.createDevice(POSConnect.DEVICE_TYPE_USB);
        curConnect.connect(pathName, connectListener);
        printer = new TSPLPrinter(curConnect);
    }

    public String searchUsb() {
        List<String> usbNames = POSConnect.getUsbDevices(this);
//        XToast.showToast("usbNames="+usbNames.size());
        String ret = "";
        if (usbNames.size()>0) {
            ret = usbNames.get(0);
        }
        Log.e("-------->","------>ret="+ret);
        return ret;
    }

    private void closeUSB() {
        if (curConnect!=null){
            curConnect.close();
        }
    }

    private IConnectListener connectListener = new IConnectListener() {
        @Override
        public void onStatus(int code, String connInfo, String msg) {
            switch (code){
                case POSConnect.CONNECT_SUCCESS:
                    Log.e("-------->","------>CONNECT_SUCCESS");
                    mWebView.loadUrl("javascript:printerCode('1')");
                    break;
                case POSConnect.CONNECT_FAIL:
                    Log.e("-------->","------>CONNECT_FAIL");
                    mWebView.loadUrl("javascript:printerCode('2')");
                    break;
                case POSConnect.CONNECT_INTERRUPT:
                    Log.e("-------->","------>CONNECT_INTERRUPT");
                    mWebView.loadUrl("javascript:printerCode('3')");
                    break;
                case POSConnect.SEND_FAIL:
                    Log.e("-------->","------>SEND_FAIL");
                    mWebView.loadUrl("javascript:printerCode('4')");
                    break;
                case POSConnect.USB_DETACHED:
                    Log.e("-------->","------>USB_DETACHED");
                    mWebView.loadUrl("javascript:printerCode('5')");
                    break;
                case POSConnect.USB_ATTACHED:
                    Log.e("-------->","------>USB_ATTACHED");
                    mWebView.loadUrl("javascript:printerCode('6')");
                    break;
            }
        }
    };

    private SerialPortManager serialPortManager;

    private void toConnectLight(String name){
        if (serialPortManager == null){
            serialPortManager = new SerialPortManager();
            serialPortManager.init(MainActivity.this, name, UserCache.getSerialRate(), new SerialPortManager.SerialCallBack() {
                @Override
                public void dataCallBack(String data) {
                    Log.e("--------->","------->data="+data);
                }

                @Override
                public void openCallBack(int code) {
                    Log.e("--------->","------->openCallBack code="+code);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl("javascript:responseLightCode('"+code+"')");
                            if (code == 1){

                            }else {
                                Toast.makeText(MainActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                @Override
                public void closeCallBack(int code) {

                }
            });
        }else {
            serialPortManager.open();
        }
    }

    private List<SerialPortManager> mPortList = new ArrayList<>();
    private void toConnectPort(String name){
        Log.i("===","------->toConnectPort name="+name);
        if (mPortList.size()==0){
            SerialPortManager serialPortManager = new SerialPortManager();
            serialPortManager.init(MainActivity.this, name, 9600, new SerialPortManager.SerialCallBack() {
                @Override
                public void dataCallBack(String data) {
                    Log.e("--------->","------->data1="+data);
                    mWebView.loadUrl("javascript:responsePortData('"+data+"')");
                }

                @Override
                public void openCallBack(int code) {
                    Log.e("--------->","------->toConnectPort code="+code);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mWebView.loadUrl("javascript:responsePortCode('"+name+","+code+"')");
                            Log.e("===","------->toConnectPort code="+code);
                            if (code == 1){
                                mPortList.add(serialPortManager);
                            }else {
                                Toast.makeText(MainActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }

                @Override
                public void closeCallBack(int code) {

                }
            });
        }else {
            Log.i("===","------->toConnectPort else="+name);
            for (SerialPortManager port:mPortList) {
                if (port.serialHelper.getPort().equals(name)){
                    port.open();
                    return;
                }
                SerialPortManager serialPortManager = new SerialPortManager();
                serialPortManager.init(MainActivity.this, name, 9600, new SerialPortManager.SerialCallBack() {
                    @Override
                    public void dataCallBack(String data) {
                        Log.e("--------->","------->data1="+data);
                        mWebView.loadUrl("javascript:responsePortData('"+data+"')");
                    }

                    @Override
                    public void openCallBack(int code) {
                        Log.e("--------->","------->toConnectPort code="+code);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mWebView.loadUrl("javascript:responsePortCode('"+name+","+code+"')");
                                if (code == 1){
                                    mPortList.add(serialPortManager);
                                }else {
                                    Toast.makeText(MainActivity.this, "串口未打开", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }

                    @Override
                    public void closeCallBack(int code) {

                    }
                });

            }
        }
        Log.i("===","------->toConnectPort end="+name);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cameraProvider!=null){
            cameraProvider.unbindAll();
        }
        if (fixedThreadPool!=null){
            fixedThreadPool.shutdown();
        }
    }
}
