const common = require('./common.js');
// const permisson = require('./permisson.js');
import SystemInfoUtil from './SystemInfoUtil.js';
// 蓝牙对应的权限名称
// 蓝牙权限对应的中文名称

// var app = null;
const bluetoothDevices = {
    ZX16D: require('./bluetooth/ZX16D.js'),
    FMBMS: require('./bluetooth/FMBMS.js'),
    LFBMS: require('./bluetooth/LFBMS.js'),
    JYBMS: require('./bluetooth/LFBMS.js'),
    BLFM: require('./bluetooth/BLFM.js'),
    ZXBT: require('./bluetooth/ZXBT.js'),
    LSBMS: require('./bluetooth/LSBMS.js'),
    LSCabinet: require('./bluetooth/LSCabinet.js'),
    ZXBTS: require('./bluetooth/ZXBTS.js'),
    AD3BTS: require('./bluetooth/AD3BTS.js'),
    BWJT: require('./bluetooth/ZXBT_JL.js'),
    JTBMS: require('./bluetooth/ZXBT_JL.js'),
	ZXZK: require('./bluetooth/ZXCar.js') //flk中控
	// ZXCAR: require('./bluetooth/ZXCar.js') //flk中控
};
//初始化蓝牙
function initBluetooth() {
	console.log('initBluetooth');
	const app = getApp();
    //监听蓝牙适配器状态变化事件
    uni.onBluetoothAdapterStateChange((res) => {
        console.log(app,res,'onBluetoothAdapterStateChange');
        Object.keys(app.globalData.adapterStateChangeFunc).forEach((n) => app.globalData.adapterStateChangeFunc[n](res));
    });
    //监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接，设备丢失，连接异常断开等等
    uni.onBLEConnectionStateChange((res) => {
		console.log('蓝牙状态变化/可能是断开连接',res);
		// console.log(app.globalData.connectionState,'app.globalData.connectionState');
        if (app.globalData.connectionState[res.deviceId]) {
            app.globalData.connectionState[res.deviceId].connected = res.connected;
            const device = app.globalData.connectionState[res.deviceId].device;
            if (app.globalData.connectionStateChangeFunc[device.mac_id]) {
                Object.keys(app.globalData.connectionStateChangeFunc[device.mac_id]).forEach((p) => app.globalData.connectionStateChangeFunc[device.mac_id][p](res));
            }
			// console.log(app.globalData.connectionStateChangeFunc[device.mac_id],'app.globalData.connectionStateChangeFunc');
        }
    });
	
	// uni.onBLEMTUChange((res) => {
	//   console.log("MTU 变更:", res.mtu); // 实际生效的 MTU 大小
	// });
	console.log(app,"监听值")
    //监听低功耗蓝牙设备的特征值变化事件。必须先启用 notifyBLECharacteristicValueChange 接口才能接收到设备推送的 notification
    uni.onBLECharacteristicValueChange((res) => {
		console.log(res,'restest1111');
		const car_sn=uni.getStorageSync('car_info').car_sn;
        if (app.globalData.connectionState[car_sn]) {
            const device = app.globalData.connectionState[car_sn].device;
			console.log(res.serviceId.toUpperCase() == bluetoothDeviceConfig(device).readServiceID.toUpperCase(),'00000');
			if (
                res.serviceId.toUpperCase() == bluetoothDeviceConfig(device).readServiceID.toUpperCase() &&
                res.characteristicId.toUpperCase() == bluetoothDeviceConfig(device).readID.toUpperCase()
            ) {
				console.log(app.globalData.connectionState[car_sn],bluetoothDeviceConfig(device),'data--------');
                var data = bluetoothDeviceConfig(device).readData(device, res.value, app.globalData.connectionState[car_sn].data);
				
				if (data) {
					const app = getApp();
                    app.globalData.connectionState[car_sn].data = data;
                    if (app.globalData.characteristicStateChangeFunc[device.mac_id]) {
                        Object.keys(app.globalData.characteristicStateChangeFunc[device.mac_id]).forEach((p) =>
                            app.globalData.characteristicStateChangeFunc[device.mac_id][p](data)
                        );
						// common.simpleToast(app.globalData.connectionState[car_sn].data)
                        console.log(app.globalData.connectionState[car_sn].data);
                    }
                }
            }
        }
    });
}
// 监听蓝牙适配器状态变化事件
function onAdapterStateChange(name, callback) {
	const app = getApp();
    app.globalData.adapterStateChangeFunc[name] = callback;
}
// 移除蓝牙适配器状态变化事件的监听
function offAdapterStateChange(name) {
	const app = getApp();
    delete app.globalData.adapterStateChangeFunc[name];
}
// 监听蓝牙设备连接状态变化事件
function onConnectionStateChange(macid, name, callback) {
	const app = getApp();
    if (!app.globalData.connectionStateChangeFunc[macid]) {
        app.globalData.connectionStateChangeFunc[macid] = {};
    }
    app.globalData.connectionStateChangeFunc[macid][name] = callback;
}
// 移除蓝牙设备连接状态变化事件的监听
function offConnectionStateChange(macid, name) {
	const app = getApp();
    if (app.globalData.connectionStateChangeFunc[macid]) {
        delete app.globalData.connectionStateChangeFunc[macid][name];
    }
}
// 监听蓝牙特征值状态变化事件
function onCharacteristicStateChange(macid, name, callback) {
	const app = getApp();
    if (!app.globalData.characteristicStateChangeFunc[macid]) {
        app.globalData.characteristicStateChangeFunc[macid] = {};
    }
    app.globalData.characteristicStateChangeFunc[macid][name] = callback;
}
// 移除蓝牙特征值状态变化事件的监听
function offCharacteristicStateChange(macid, name) {
	const app = getApp();
    if (app.globalData.characteristicStateChangeFunc[macid]) {
        delete app.globalData.characteristicStateChangeFunc[macid][name];
    }
}
// 获取蓝牙适配器的状态
function getAdapterState(callback = () => {}, fail = () => {}) {
    uni.getBluetoothAdapterState({
        success: (res) => {
            callback(res);
        },
        fail: (res) => {
            console.log(res);
            fail(res);
        }
    });
}
// 打开蓝牙适配器
function openBluetoothAdapter(callback = () => {}, fail = () => {}) {
    uni.openBluetoothAdapter({
        success: (res) => {
            console.log('初始化蓝牙模块成功');
            callback(res);
        },
        fail: (res) => {
            console.log(res);
            //permisson.permission_request(blePermissionName, blePermissionZhName);
            fail(res);
        }
    });
}
// 关闭蓝牙适配器
function closeBluetoothAdapter(callback = () => {}, fail = () => {}) {
    uni.closeBluetoothAdapter({
        success: (res) => {
			const app = getApp();
            app.globalData.adapterStateChangeFunc = {};
            app.globalData.connectionStateChangeFunc = {};
            app.globalData.characteristicStateChangeFunc = {};
            app.globalData.connectionState = {};
            callback(res);
        },
        fail: (res) => {
            console.log(res);
            fail(res);
        }
    });
}
// 函数acceptDevice用于接受设备
// 参数device为设备对象
function acceptDevice(device) {
    // 如果设备类型在bluetoothDevices中存在，则返回true，否则返回false
    return bluetoothDevices[device.bt_type] || (bluetoothDevices[device.device_type] && bluetoothDevices[device.device_type].acceptDevice(device)) ? true : false;
}
// 判断设备是否为单蓝牙设备
function isSingleBT(device) {
    // if (bluetoothDevices[device_type] && bluetoothDevices[device_type].isSingleBt) {
    //   return bluetoothDevices[device_type].isSingleBt()
    // }
    // return false
    // 判断设备配置是否存在且包含isSingleBt属性
    if (bluetoothDeviceConfig(device) && bluetoothDeviceConfig(device).isSingleBt) {
        // 返回设备配置中的isSingleBt属性值
        return bluetoothDeviceConfig(device).isSingleBt();
    }
    // 如果设备配置不存在或没有isSingleBt属性，则返回false
    return false;
}
// 判断设备是否为蜂鸣器
function isBuzzer(device) {
    // 如果设备是蓝牙设备且设备配置中包含isBuzzer属性
    if (bluetoothDeviceConfig(device) && bluetoothDeviceConfig(device).isBuzzer) {
        // 返回设备配置中的isBuzzer属性值
        return bluetoothDeviceConfig(device).isBuzzer();
    }
    // 否则返回false
    return false;
}
// 判断设备是否为电压到电设备
function isVoltageToEle(device) {
    // 如果设备配置中存在电压到电配置，则返回true
    if (bluetoothDeviceConfig(device) && bluetoothDeviceConfig(device).voltageToEle) {
        return true;
    }
    // 否则返回false
    return false;
}
// 根据macid判断是否是单蓝牙设备
function isSginleBtByMacid(macid) {
	const app = getApp();
    // 根据macid查找设备id
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    // 打印全局连接状态
    console.log(app.globalData.connectionState);
    // 如果设备id为undefined，则返回false
    if (deviceId == undefined) {
        return false;
    }
    // 根据设备id判断是否是单蓝牙设备
    return isSingleBT(app.globalData.connectionState[deviceId].device);
}
function haveBMSForBT(device) {
    if (bluetoothDeviceConfig(device) && bluetoothDeviceConfig(device).haveBms) {
        return bluetoothDeviceConfig(device).haveBms();
    }
    return false;
}
// 定义一个函数，用于查找蓝牙设备
function findDevice(device, callback = () => {}, fail = () => {}) {
	console.log('走到了findDevice fun');
    // 定义一个变量，用于存储设备ID
    var deviceId = '';
    // 判断设备是否为蓝牙设备
    if (!bluetoothDeviceConfig(device)) {
        // 如果不是蓝牙设备，则返回
        return;
    }
    // 打印查找到为蓝牙设备
    console.log('查找到为蓝牙设备');
    // 开始搜索蓝牙设备
        setTimeout(()=> {       
    uni.startBluetoothDevicesDiscovery({
        // 搜索成功
        success(res) {
            console.log(res,'startBluetoothDevicesDiscovery');
			
				// 获取搜索到的蓝牙设备
				uni.getBluetoothDevices({
					success: (res) => {
						console.log(res,'getBluetoothDevices');
						// 遍历搜索到的蓝牙设备
						res.devices.forEach((data) => {
							// console.log(data,'data***************');
							// 判断设备是否为指定设备
							console.log('------',bluetoothDeviceConfig(device).isDevice(device, data));
							if (bluetoothDeviceConfig(device).isDevice(device, data)) {
								const app = getApp();
								// uni.offBluetoothDeviceFound();
								uni.stopBluetoothDevicesDiscovery(); //查找到蓝牙设备停止搜索
								const car_info= uni.getStorageSync('car_info')
								const deviceIds = data.deviceId;
								console.log(deviceIds,'deviceIds123');
								const deviceId = car_info.car_sn;
								if (app.globalData.connectionState[deviceId]) {
									app.globalData.connectionState[deviceId].device = device;
								} else {
									app.globalData.connectionState[deviceId] = {
										device: device,
										deviceName:data.name,
										deviceId: deviceIds,
										connected: false,
										data: {}
									};
								}
								callback(deviceId);
							}
						});
						
						setTimeout(function () {
							if (!deviceId) {
								// uni.offBluetoothDeviceFound();
								uni.stopBluetoothDevicesDiscovery();
								var res = {
									errCode: 9000001,
									errMsg: 'openBluetoothAdapter:find not device',
									errno: 9000002
								};
								fail(res);
							}
						}, 5000);
					},
					fail(res) {
						uni.stopBluetoothDevicesDiscovery();
						console.log(res);
						fail(res);
					}
				});
				// 监听蓝牙设备发现事件
			 
            uni.onBluetoothDeviceFound((res) => {
				console.log(res,"foundDevice")
                // console.log(res);
                // 遍历搜索到的蓝牙设备列表
                res.devices.forEach((data) => {
                    // 检查当前设备是否为目标设备
                    if (bluetoothDeviceConfig(device).isDevice(device, data)) {
                        // uni.offBluetoothDeviceFound();
                        // 停止蓝牙设备搜索
                        uni.stopBluetoothDevicesDiscovery();
						const car_info= uni.getStorageSync('car_info')
                        const deviceIds = data.deviceId;
						console.log(deviceIds,'deviceIds456');
						const deviceId = car_info.car_sn;
						const app = getApp();
                         // 检查全局状态中是否已经存在该设备
                        if (app.globalData.connectionState[deviceId]) {
                            app.globalData.connectionState[deviceId].device = device;
                        } else {
							
                            // 如果不存在，创建新的设备状态对象
                            app.globalData.connectionState[deviceId] = {
                                device: device,
								deviceName:data.name,
                                deviceId: deviceIds,
                                connected: false,
                                data: {}
                            };
							console.log(app.globalData.connectionState[deviceId],'datatest--------');
							
                        }
                        callback(deviceId);
                    }
                });
            });
        },
        fail(res) {
            console.log(res);
            fail(res);
        }
    });
	   }, 500);
	 
}
// 连接设备函数
function connectDevice(device, callback = () => {}, fail = () => {}) {
    // 打印设备信息
    console.log(device);
    // 判断设备是否符合蓝牙设备配置
    if (!bluetoothDeviceConfig(device) || !bluetoothDeviceConfig(device).acceptDevice(device)) {
        return;
    }
	const app = getApp();
	console.log(app,'连接函数connectDevice deviceId111111');
    // 获取设备ID
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == device.mac_id);
	console.log(deviceId,'连接函数connectDevice deviceId');
	// 判断设备是否已经连接
    if (deviceId == undefined) {
        // 如果设备未连接，则查找设备
        findDevice(
            device,
            (deviceId) => {
                // 递归调用连接设备函数
                connectDevice(device, callback, fail);
            },
            (res) => {
                // 失败回调
                fail(res);
            }
        );
        return;
    } else {
        // 如果设备已经连接，则直接回调
        if (app.globalData.connectionState[deviceId].connected) {
            callback();
            return;
        }
    }
	const car_sn=uni.getStorageSync('car_info').car_sn
	const deviceIds = app.globalData.connectionState[car_sn].deviceId
	console.log(deviceIds,'deviceIds');
	const device_name=app.globalData.connectionState[car_sn].deviceName
    // 创建蓝牙连接
    uni.createBLEConnection({
        deviceId: deviceIds,
        success: (res) => {
			console.log(res,'蓝牙连接成功');
			const app = getApp();
            // 更新连接状态
            app.globalData.connectionState[deviceId] = {
                device: device,
				deviceName: device_name,
                deviceId: deviceIds,
                connected: true,
                data: {}
            };
            // 调用连接成功回调
            alterConnect(
                device,
                deviceIds,
                (res) => {
                    console.log('uni.createBLEConnection');
                    callback(res);
                },
                (res) => {
                    console.log(' uni.createBLEConnection');
                    // 关闭设备连接
                    closeDevice(deviceId);
                    // 失败回调
                    fail(res);
                }
            );
        },
        fail(res) {
            console.log(res);
            // 如果连接失败，则关闭设备连接，并重新连接
            if (res.errCode == -1) {
                closeDevice(
                    deviceId,
                    (res) => {
                        connectDevice(device, callback, fail);
                    },
                    (res) => {
                        fail(res);
                    }
                );
            } else {
                // 失败回调
                fail(res);
            }
        }
    });
}
// 函数alterConnect用于连接蓝牙设备
function alterConnect(device, deviceId, callback = () => {}, fail = () => {}) {
    // 判断设备是否支持蓝牙连接
	console.log("xxxx1")
    if (!bluetoothDeviceConfig(device) || !bluetoothDeviceConfig(device).acceptDevice(device)) {
        return;
    }
	console.log("xxxx2")
	console.log(deviceId)
	// var data = bluetoothDeviceConfig(device).alterConnect(device, deviceId);
	//蓝牙不使用登录指令
	// var data = bluetoothDeviceConfig(device).nearUnlock(device, deviceId);
	// setTimeout(()=>{
	// 	writeData(device, deviceId, data, callback, fail);
	// },1000)
    // 获取蓝牙设备的服务列表
	setTimeout(()=>{
    uni.getBLEDeviceServices({
        deviceId: deviceId,
        success(res) {
            console.log(res,'res1111');
			console.log(bluetoothDeviceConfig(device).writeServiceID)
			// 获取蓝牙设备的写特征值
			setTimeout(()=>{
            uni.getBLEDeviceCharacteristics({
                deviceId: deviceId,
                serviceId: bluetoothDeviceConfig(device).writeServiceID,
                success(res) {
                    console.log(res,'res22222');
                    // 获取蓝牙设备的读特征值
                    uni.getBLEDeviceCharacteristics({
                        deviceId: deviceId,
                        serviceId: bluetoothDeviceConfig(device).readServiceID,
                        success(res) {
                            console.log(res,'res3333');
                            // 监听蓝牙设备的读特征值变化
                            uni.notifyBLECharacteristicValueChange({
                                state: true,
                                deviceId: deviceId,
                                serviceId: bluetoothDeviceConfig(device).readServiceID,
                                characteristicId: bluetoothDeviceConfig(device).readID,
                                success(res) {
                                    console.log(res);
                                    // 判断设备是否支持  ，并且当前平台是否为安卓
                                    if (bluetoothDeviceConfig(device).MTU && SystemInfoUtil.platform == SystemInfoUtil.ANDROID) {
                                        // 设置蓝牙设备的MTU
                                        uni.setBLEMTU({
                                            deviceId: deviceId,
                                            mtu: bluetoothDeviceConfig(device).MTU,
                                            success: (res) => {
                                                console.log('setBLEMTU success>>', res);
                                                // 判断设备是否有alterConnect方法
                                                if (bluetoothDeviceConfig(device).getNearUnlockSet) {
                                                    var data = bluetoothDeviceConfig(device).getNearUnlockSet(device, deviceId);
													console.log(data[0],'data111111');
                                                    // 判断alterConnect方法是否返回数据
                                                    if (data) {
                                                        // 写入数据
														setTimeout(()=>{
															writeData(device, deviceId, data, callback, fail);
														},3000)
                                                        
                                                    } else {
                                                        // 调用回调函数
                                                        callback(res);
                                                    }
                                                } else {
                                                    // 调用回调函数
                                                    callback(res);
                                                }
                                            },
                                            fail: (res) => {
                                                console.log('setBLEMTU fail>>', res);
                                                // 判断设备是否有alterConnect方法
                                                if (bluetoothDeviceConfig(device).getNearUnlockSet) {
                                                    var data = bluetoothDeviceConfig(device).getNearUnlockSet(device, deviceId);
                                                    // 判断alterConnect方法是否返回数据
                                                    if (data) {
                                                        // 写入数据
                                                        writeData(device, deviceId, data, callback, fail);
                                                    } else {
                                                        // 调用回调函数
                                                        callback(res);
                                                    }
                                                } else {
                                                    // 调用回调函数
                                                    callback(res);
                                                }
                                            }
                                        });
                                    } else {
                                        // 判断设备是否有alterConnect方法
                                        if (bluetoothDeviceConfig(device).getNearUnlockSet) {
                                            var data = bluetoothDeviceConfig(device).getNearUnlockSet(device, deviceId);
                                            // 判断alterConnect方法是否返回数据
                                            if (data) {
                                                // 写入数据
                                                writeData(device, deviceId, data, callback, fail);
                                            } else {
                                                // 调用回调函数
                                                callback(res);
                                            }
                                        } else {
                                            // 调用回调函数
                                            callback(res);
                                        }
                                    }
                                },
                                fail(res) {
                                    // 调用失败回调函数
                                    fail(res);
                                }
                            });
                        },
                        fail(res) {
                            // 调用失败回调函数
                            fail(res);
                        }
                    });
				},
                fail(res) {
					console.log('getBLEDeviceServices fail',res);
                    // 调用失败回调函数
                    fail(res);
                }
            });	
			},500)
            
        },
        fail(res) {
			
            // 调用失败回调函数
            fail(res);
        }
    });
	},500)
}
// 关闭设备连接
function closeDevice(macid, callback = () => {}, fail = () => {}) {
    const app=getApp()
	// 获取设备ID
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    // 如果设备ID不存在，则调用fail函数
    if (deviceId == undefined) {
        fail();
        return;
    } else {
        // 如果设备未连接，则调用callback函数
        if (!app.globalData.connectionState[deviceId].connected) {
            callback();
            return;
        }
    }
    // 获取设备信息
    const device = app.globalData.connectionState[deviceId].device;
    // 关闭设备连接
    uni.closeBLEConnection({
        deviceId: deviceId,
        success: (res) => {
            console.log(res);
			const app = getApp();
            // 如果设备连接状态存在，则将连接状态设置为false
            if (app.globalData.connectionState[deviceId]) {
                app.globalData.connectionState[deviceId].connected = false;
            }
            // 调用callback函数
            callback(res);
        },
        fail(res) {
            console.log(res);
            // 调用fail函数
            fail(res);
        }
    });
}
function bmsInfo(macid) {
    console.log(macid);
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).bmsInfo) {
        return false;
    }
    return bluetoothDeviceConfig(device).bmsInfo(device, deviceId, app.globalData.connectionState[deviceId].data);
}
function bmsSet(macid, name, vars, callback = () => {}, fail = () => {}) {
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).bmsSet) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).bmsSet(device, deviceId, name, vars);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
// 定义一个函数，用于向蓝牙设备写入数据
function writeData(device, deviceId, data, callback = () => {}, fail = () => {}) {
    // 如果数据长度为0，则直接返回
    console.log(data,'data写入---------------------');
	if (data.length == 0) {
        return;
    }
	console.log(data,data[0].length);
    // 将数据转换为ArrayBuffer类型
   // let buffer;
    // buffer = common.toArrayBuffer(data.shift());
	
    //buffer = common.toArrayBuffer(data.shift());
	var byteArray = data.shift()
	const buffer = new ArrayBuffer(byteArray.length);
	const dataView = new DataView(buffer);
	// 2. 逐个写入字节
	for (let i = 0; i < byteArray.length; i++) {
	  dataView.setUint8(i, byteArray[i]);
	}
	
	console.log(data[0],buffer,'buffer写入---------------------');
	// console.log(buffer,'buffer111');
    // 调用uni.writeBLECharacteristicValue方法，向蓝牙设备写入数据
	// setTimeout(() => {
		plus.bluetooth.writeBLECharacteristicValue({
    // uni.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: bluetoothDeviceConfig(device).writeServiceID,
        characteristicId: bluetoothDeviceConfig(device).writeID,
        writeType:'write',// 写入方式
        value: buffer,
        // 成功回调函数
        success(res) {
			uni.hideLoading();
			console.log('写入成功');
            // 如果数据长度为0，则调用回调函数
            if (data.length == 0) {
                callback(res);
            } else {
				// writeData(device, deviceId, data, callback, fail);
                // // 否则，延时500毫秒后再次调用writeData函数
                setTimeout(() => {
                    writeData(device, deviceId, data, callback, fail);
                }, 150);
            }
        },
        // 失败回调函数
        fail(res) {
            console.log(res);
            // 调用失败回调函数
            fail(res);
        }
    });
	// }, 200);
}
function stateUpdate(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).stateUpdate) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).stateUpdate(device, deviceId);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function voltageToEle(macid, value, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).voltageToEle) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).voltageToEle(device, value);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function turnOn(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).turnOn) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).turnOn(device, deviceId);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function turnOnBuzzer(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).turnOnBuzzer) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).turnOnBuzzer(device, deviceId);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function turnOffBuzzer(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).turnOffBuzzer) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).turnOffBuzzer(device, deviceId);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function turnOff(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).turnOff) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).turnOff(device, deviceId);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function bmsChargingMOS(macid, value, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).bmsChargingMOS) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).bmsChargingMOS(value - 0, device);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function bmsDischargeMOS(macid, value, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDeviceConfig(device).bmsDischargeMOS) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device).bmsDischargeMOS(value - 0, device);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function isConnected(macid) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        return false;
    }
    return app.globalData.connectionState[deviceId].connected;
}
function getData(macid) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        return false;
    }
    return app.globalData.connectionState[deviceId].data;
}
function getConnectionState(macid) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        return false;
    }
    return app.globalData.connectionState[deviceId];
}
function bluetoothDeviceConfig(device) {
    if (bluetoothDevices[device.bt_type]) {
        return bluetoothDevices[device.bt_type];
    } else if (bluetoothDevices[device.device_type]) {
        return bluetoothDevices[device.device_type];
    } else {
        return false;
    }
}
function isUniversalBluetoothPlugin(device) {
    if (bluetoothDevices[device.bt_type]) {
        return bluetoothDevices[device.bt_type];
    } else {
        return false;
    }
}
function sendHireCommand(macid, info, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDevices[device.device_type].sendHireCommand) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].sendHireCommand(info);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function sendBackCommand(macid, info, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDevices[device.device_type].sendBackCommand) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].sendBackCommand(info);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function sendExchangeCommand(macid, info, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDevices[device.device_type].sendExchangeCommand) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].sendExchangeCommand(info);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
// 定义一个函数，用于发送获取柜子信息的命令
function sendGetCabinetInfoCommand(macid, info, callback = () => {}, fail = () => {}) {
	const app = getApp();
    // 获取设备ID
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    console.log(deviceId,'deviceId0000');
	// 如果设备ID为空，则调用fail函数并返回false
	if (deviceId == undefined) {
        fail();
        return false;
    }
	console.log(app.globalData.connectionState[deviceId].device,'device333333');
	console.log(bluetoothDevices,'deviceId11111');
	console.log(bluetoothDevices['ZXCAR'].sendGetCabinetInfoCommand,'test333');
    // 获取设备信息
    const device = app.globalData.connectionState[deviceId].device;
    // 如果设备类型没有sendGetCabinetInfoCommand方法，则调用fail函数并返回false
    if (!bluetoothDevices[device.device_type].sendGetCabinetInfoCommand) {
        fail();
        return false;
    }
	 console.log(bluetoothDevices[device.device_type].sendGetCabinetInfoCommand(info),'deviceId2222');
    // 调用sendGetCabinetInfoCommand方法，获取数据
    var data = bluetoothDevices[device.device_type].sendGetCabinetInfoCommand(info);
    // 如果数据存在，则调用writeData函数，并返回true
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function sendConfirmCommand(macid, value, serialNum, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDevices[device.device_type].sendConfirmCommand) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].sendConfirmCommand(value, serialNum);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}
function sendCancelCommand(macid, serialNum, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDevices[device.device_type].sendCancelCommand) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].sendCancelCommand(serialNum);
    if (data) {
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}

//切换正常工厂模式
function sendSwitchNormalCommand(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
    if (!bluetoothDevices[device.device_type].switchFactory) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].switchFactory(device,deviceId);
    if (data) {
		console.log(data,'写入data');
        writeData(device, deviceId, data, callback, fail);
        return true;
    }
    fail();
    return false;
}

function sendOTACommand(macid, callback = () => {}, fail = () => {}) {
	const app = getApp();
    const deviceId = Object.keys(app.globalData.connectionState).find((i) => app.globalData.connectionState[i].device.mac_id == macid);
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[deviceId].device;
	
    if ( !bluetoothDevices[device.device_type].otaUpgrade) {
        fail();
        return false;
    }
    var data = bluetoothDevices[device.device_type].otaUpgrade(device,deviceId);
    if (data) {
		
		data.then(result => {
			console.log(result[0],'result');
			    writeData(device, deviceId, [result[0]], callback, fail);
				// const testData=result.slice(0,3)
				// const testData=result
				// for(let i = 0; i < testData.length; i++){
				// 	if(i==(testData.length-1)){
				// 		console.log('发送升级文件结束');
				// 	}
				// 	console.log(testData[i],'[testData[i]]');
				// 	writeData(device, deviceId, [testData[i]], callback, fail);
				// }
			}).catch(error => {
				console.error(error); // 如果Promise被拒绝，这将打印出错误信息
			});
       return true;
    }
    fail();
    return false;
}
function executeDeviceCommand(macid, commandName, callback = () => {}, fail = () => {}) {
    console.log('test');
	const app = getApp();
	const deviceId =  app.globalData.connectionState[macid].deviceId
    if (deviceId == undefined) {
        fail();
        return false;
    }
    const device = app.globalData.connectionState[macid].device;
    if (!bluetoothDeviceConfig(device)[commandName]) {
        fail();
        return false;
    }
    var data = bluetoothDeviceConfig(device)[commandName](device, deviceId);
    if (data) {
		setTimeout(()=>{
			writeData(device, deviceId, data, callback, fail);
		},200)
        return true;
    }
    fail();
    return false;
}
//开机
function turnOnCar(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'turnOnCar', callback, fail);
}
//关机
function turnOffCar(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'turnOffCar', callback, fail);
}
//寻车
function findCarCmd(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'findCarCmd', callback, fail);
}
//打开车座
function openCarSeat(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'openCarSeat', callback, fail);
}
//打开车后备箱
function openCarTrunk(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'openCarTrunk', callback, fail);
}
//获取胎压
function getCarPressure(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'getCarPressure', callback, fail);
}
//打开接近解锁
function nearUnlock(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'nearUnlock', callback, fail);
}
//关闭接近解锁
function nearCloseUnlock(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'nearCloseUnlock', callback, fail);
}
//获取灵敏度设置
function getSensitivity(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'getSensitivity', callback, fail);
}
//设置灵敏度
function setSensitivity(macid,type, callback = () => {}, fail = () => {}) {
	const app = getApp();
	const deviceId = app.globalData.connectionState[macid].deviceId
	if (deviceId == undefined) {
	    fail();
	    return false;
	}
	const device = app.globalData.connectionState[macid].device;
	if (!bluetoothDeviceConfig(device)[setSensitivity]) {
	    fail();
	    return false;
	}
	var data = bluetoothDeviceConfig(device)[setSensitivity](device, deviceId,type);
	if (data) {
	    writeData(device, deviceId, data, callback, fail);
	    return true;
	}
	fail();
	return false;
}
//
function setNearUnlock(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'setNearUnlock', callback, fail);
}
//获取靠近解锁设置
function getNearUnlockSet(macid, callback = () => {}, fail = () => {}) {
    return executeDeviceCommand(macid, 'getNearUnlockSet', callback, fail);
}


module.exports = {
    initBluetooth: initBluetooth,
    onAdapterStateChange: onAdapterStateChange,
    offAdapterStateChange: offAdapterStateChange,
    onConnectionStateChange: onConnectionStateChange,
    offConnectionStateChange: offConnectionStateChange,
    onCharacteristicStateChange: onCharacteristicStateChange,
    offCharacteristicStateChange: offCharacteristicStateChange,
    getAdapterState: getAdapterState,
    openBluetoothAdapter: openBluetoothAdapter,
    closeBluetoothAdapter: closeBluetoothAdapter,
    acceptDevice: acceptDevice,
    findDevice: findDevice,
    connectDevice: connectDevice,
    closeDevice: closeDevice,
    stateUpdate: stateUpdate,
    turnOn: turnOn,
    turnOff: turnOff,
    turnOnBuzzer: turnOnBuzzer,
    turnOffBuzzer: turnOffBuzzer,
    bmsInfo: bmsInfo,
    bmsSet: bmsSet,
    isConnected: isConnected,
    getData: getData,
    isSingleBT: isSingleBT,
    isBuzzer: isBuzzer,
    haveBMSForBT: haveBMSForBT,
    isSginleBtByMacid: isSginleBtByMacid,
    getConnectionState: getConnectionState,
    bmsChargingMOS: bmsChargingMOS,
    bmsDischargeMOS: bmsDischargeMOS,
    bluetoothDeviceConfig: bluetoothDeviceConfig,
    voltageToEle: voltageToEle,
    isVoltageToEle: isVoltageToEle,
    isUniversalBluetoothPlugin: isUniversalBluetoothPlugin,
    //机柜协议增加
    sendHireCommand: sendHireCommand,
    sendBackCommand: sendBackCommand,
    sendExchangeCommand: sendExchangeCommand,
    sendGetCabinetInfoCommand: sendGetCabinetInfoCommand,
    sendConfirmCommand: sendConfirmCommand,
    sendCancelCommand: sendCancelCommand,
	//切换正常工厂模式写入
	sendSwitchNormalCommand,
	
	//蓝牙中控
	sendOTACommand,
    // 执行设备命令
    executeDeviceCommand,
    turnOnCar,
    turnOffCar,
	findCarCmd,
	openCarSeat,
	openCarTrunk,
	getCarPressure,
	nearUnlock,
	nearCloseUnlock,
	getSensitivity,
	setSensitivity,
	getNearUnlockSet,
	setNearUnlock,
	
	
};
