//address=""搜索蓝牙//address=设备mac地址，自动配对给出mac地址的设备 安卓
var BleDevice
var device = null,
    BAdapter = null,
    BluetoothAdapter = null,
    uuid = null,
    main = null,
    UUID = null,
    bluetoothSocket = null,
    num = 0;
// 开始gps定位
function getLocationManager(callback) {
    plus.android.requestPermissions(
        ['android.permission.ACCESS_FINE_LOCATION'],
        function (resultObj) {
            var result = 0;
            for (var i = 0; i < resultObj.granted.length; i++) {
                var grantedPermission = resultObj.granted[i]; // 以获取的权限
                result = 1;
            }
            for (var i = 0; i < resultObj.deniedPresent.length; i++) {
                var deniedPresentPermission = resultObj.deniedPresent[i]; // 拒绝本次申请的权限
                num += 1;
                result = 0;
            }
            for (var i = 0; i < resultObj.deniedAlways.length; i++) {
                var deniedAlwaysPermission = resultObj.deniedAlways[i]; // 永久拒绝的权限
                num += 1;
                result = -1;
            }
            // 权限被拒绝，则打开app 设置界面，可以再app设置界面打开相应权限
            if (result !== 1) {
                const Intent = plus.android.importClass("android.content.Intent");
                const Settings = plus.android.importClass("android.provider.Settings");
                const Uri = plus.android.importClass("android.net.Uri");
                var mainActivity=plus.android.runtimeMainActivity();
                const intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                var uri = Uri.fromParts("package",mainActivity.getPackageName(),null);
                intent.setData(uri);
                mainActivity.startActivity(intent);
            } else {
                // 因为安卓手机，授权之后还需要打开定位服务功能 当手机授权之后 调用下面的方法
                var context = plus.android.importClass("android.content.Context");
                var locationManager=plus.android.importClass("android.location.LocationManager");
                var main=plus.android.runtimeMainActivity();
                var mainSvr=main.getSystemService(context.LOCATION_SERVICE);
                var gps = mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER);
                var agps = mainSvr.isProviderEnabled(locationManager.NETWORK_PROVIDER);
                // 只有两个：gps开关和agps开关都是关的情况才算关，有一个开就认为是开
                if (gps || agps) {
                    startBluetoothDiscovery(callback); // 目前发现 荣耀需要弹框允许蓝牙权限 否则无法搜索即使打开蓝牙也没用
                } else {
                    uni.showModal({
                        title: "提示",
                        content: "请授权位置获取附近的蓝牙设备",
                        showCancel: false,
                        success(){
                            if (!mainSvr.isProviderEnabled(locationManager.GPS_PROVIDER)) {
                                var Intent = plus.android.importClass("android.content.Intent");
                                var Settings = plus.android.importClass("android.provider.Settings");
                                var intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                main.startActivity(intent); // 打开系统设置gps服务页面
                            } else {
                                startBluetoothDiscovery(callback); // 目前发现 荣耀需要弹框允许蓝牙权限 否则无法搜索即使打开蓝牙也没用
                                console.log('定位已开启')
                                // uni.showToast({
                                //     title: '定位已开启',
                                //     duration: 2000,
                                // });
                            }
                        }
                    })
                }
            }



        }
    )
}
function startBluetoothDiscovery(callback){
    plus.bluetooth.openBluetoothAdapter({
        success:function(e){
            plus.bluetooth.startBluetoothDevicesDiscovery({
                success:function(e){callback()},
                fail:function(e){console.log('失败2')}
            });
        },
        fail:function(e){
            console.log('open failed: '+JSON.stringify(e));
        }
    });
}
// 搜索设备
function searchDevices(address= '',vlist1 = [],vlist2= []) {
    //注册类
    var main = plus.android.runtimeMainActivity();
    var IntentFilter = plus.android.importClass('android.content.IntentFilter');
    var BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
    var BluetoothDevice = plus.android.importClass("android.bluetooth.BluetoothDevice");
    BAdapter = BluetoothAdapter.getDefaultAdapter();
    // 没有开启蓝牙
    if (!BAdapter.isEnabled()) {
        uni.showToast({
            title: '请开启蓝牙',
            duration: 2000,
            icon:'error'
        });
        return;
    }
    console.log("开始搜索设备");
    var filter = new IntentFilter();
    var bdevice = new BluetoothDevice();
    var on = null;
    var un = null;
    let titleStr = '正在搜索请稍候';
    if (address) {
        titleStr = '正在连接蓝牙';
    }
    uni.showLoading({
        title: titleStr,
        success:()=>{
            setTimeout(function () {
                uni.hideLoading();
            },5000);
        }
    });
    BAdapter.startDiscovery(); //开启搜索
    var receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
        onReceive: function(context, intent) { //实现onReceiver回调函数
            plus.android.importClass(context);
            plus.android.importClass(intent); //通过intent实例引入intent类，方便以后的‘.’操作
            if(intent.getAction() === "android.bluetooth.adapter.action.DISCOVERY_FINISHED"){
                main.unregisterReceiver(receiver);//取消监听
                uni.hideLoading(); // 默认12秒
                // console.log("搜索结束")
            }else{
                BleDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                const name = BleDevice.getName();
                //判断是否配对
                if (BleDevice.getBondState() === bdevice.BOND_NONE) {
                    //参数如果跟取得的mac地址一样就配对
                    if (address === BleDevice.getAddress()) {
                        if (BleDevice.createBond()) { //配对命令.createBond()
                            vlist2.push({name,address:BleDevice.getAddress()});
                            BAdapter.cancelDiscovery();//取消扫描
                            // main.unregisterReceiver(receiver);//取消监听
                            // uni.hideLoading(); //
                        }

                    } else {
                        if(name !== null && name !== on ){ //判断防止重复添加
                            on = name || '未知设备';
                            vlist1.push({name:on,address:BleDevice.getAddress()})
                        }

                    }
                } else {
                    if(name !== un ){ //判断防止重复添加
                        un = name;
                        vlist1.push({name:un,address:BleDevice.getAddress()});
                        vlist2.push({name:un,address:BleDevice.getAddress()});
                        if (address) {
                            BAdapter.cancelDiscovery();//取消扫描
                        }
                    }
                }}

        }
    });
    filter.addAction(bdevice.ACTION_FOUND);
    filter.addAction(BAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BAdapter.ACTION_DISCOVERY_FINISHED);
    filter.addAction(BAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_ACL_DISCONNECTED);

    main.registerReceiver(receiver, filter); //注册监听
}
//开始连接打印
function print(mac_address,data,callback) {
    if (!mac_address) {
        uni.showToast({
            title: '请选择蓝牙设备',
            duration: 2000,
            icon:'error'
        });
        return;
    }

    main = plus.android.runtimeMainActivity();
    BluetoothAdapter = plus.android.importClass("android.bluetooth.BluetoothAdapter");
    UUID = plus.android.importClass("java.util.UUID");
    uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    BAdapter = BluetoothAdapter.getDefaultAdapter();
    device = BAdapter.getRemoteDevice(mac_address);
    plus.android.importClass(device);
    bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
    plus.android.importClass(bluetoothSocket);
    // const isConnected = bluetoothSocket.isConnected();
    // console.log('设备是否连接,',bluetoothSocket.isConnected());

    if (!bluetoothSocket.isConnected()) {
        uni.showToast({
            title: '检测到设备未连接，尝试连接....',
            duration: 2000,
            icon:'none'
        });
        bluetoothSocket.connect();
    }

    if (bluetoothSocket.isConnected()) {
        const outputStream = bluetoothSocket.getOutputStream();
        plus.android.importClass(outputStream);
        // string  直接传输指令就行 哪个打印机需要的指令就传哪个指令 例子(tSPL)：
        // 宽： X800（100mm） 点，高：Y800（100mm）
        // const string2 = `
        // SIZE 100mm, 100mm
        // GAP 3mm, 0mm
        // DIRECTION 1
        // CLS
        // TEXT 291,0,"TSS24.BF2",0,1,1,"货号：0075 0075瑜伽体力库"
        // TEXT 291,40,"TSS24.BF2",0,1,1,"日期：06/30 裁剪：裁剪人"
        // TEXT 291,80,"TSS24.BF2",0,1,1,"编号：952 包号：1"
        // TEXT 291,120,"TSS24.BF2",0,1,1,"床号：91 颜色：白色"
        // TEXT 291,160,"TSS24.BF2",0,1,1,"尺码：S 数量：100"
        // QRCODE 391,200,H,10,A,0,"无效数据-guid"
        // PRINT 1
        // `;
        data.forEach(item=>{
            const bytes = plus.android.invoke(item, 'getBytes', 'gbk');
            outputStream.write(bytes);
        });
        setTimeout(function () {
            outputStream.flush();// 强制把缓冲区内容输出
            device = null //这里关键
            // outputStream.clone(); // 关闭输出流
            bluetoothSocket.close(); //必须关闭蓝牙连接否则意外断开的话打印错误
            callback();
        },500)
    }

}

// 关闭操作
function cancelDiscovery() {
    if (BAdapter) {
        BAdapter.cancelDiscovery();//取消扫描
        if (bluetoothSocket) {
            bluetoothSocket.close(); //关闭蓝牙连接
        }
    }
}



export {searchDevices,print,getLocationManager,cancelDiscovery}