'use strict';
import React, { Component } from 'react';
import { NativeModules, DeviceEventEmitter, Platform } from 'react-native';



let MethodModule;
if (Platform.OS === 'ios') {
    MethodModule = NativeModules.RNSanModule;
} else {
    MethodModule = NativeModules.RNMethodModule;
}




const OVER_TIME = 5 * 1000;
const CONNECT_OVER_TIME = 35 * 1000;
const COMMAND_TIME_INTERVAL = 200;
const PROGRESS_TIME_INTERVAL = 8 * 1000;
const TAG = 'MY_RNDY';

if (__DEV__) {
    const version = 201704011315;
    console.log(TAG, 'dyg driver version:', version);
}

/** 监控的消息参数 */
const DYG_CREATED_CHANNEL = 'DYG_CREATED_CHANNEL';
const DYG_ON_GET_ALL_DATA_COUNT = 'DYG_ON_GET_ALL_DATA_COUNT';
const DYG_ON_DO_AUTHORIZATION = 'DYG_ON_DO_AUTHORIZATION';
const DYG_ON_GET_MONITOR_STATUS = 'DYG_ON_GET_MONITOR_STATUS';
const UPDATE_DEVICE_LIST = 'UPDATE_DEVICE_LIST';
const DYG_ON_GET_ALL_DATA = 'DYG_ON_GET_ALL_DATA';
const DYG_ON_START_MONITOR = 'DYG_ON_START_MONITOR';
const DYG_ON_STOP_MONITOR = 'DYG_ON_STOP_MONITOR';
const DYG_ON_UPDATE_NEW_DATA = 'DYG_ON_UPDATE_NEW_DATA';
const DYG_ON_GET_BATTERY = 'DYG_ON_GET_BATTERY';

/* =============================== 常量 ======================== */
const START_MONITOR = 1;
const STOP_MONITOR = 2;
const GET_NUMBER_DATA_FROM_INDEX = 3;
const GET_ALL_DATA_FROM_INDEX = 4;
const GET_ALL_DATA_COUNT = 5;
const GET_ALL_DATA = 6;
const GET_NAME = 7;
const getMaxNumber = 8;
const disConnection = 9;
const GET_SN = 10;
const GET_VERSION = 11;
const doAuthorization = 12;
const getRecord = 13;
const GET_AUTH = 14;
const GET_MONITOR_STATUS = 15;
const GET_BATTERY = 16;

let driver = null;

export default class RNDYGlucoseDriver {
    subscriptionMap = {};

    constructor() {
        this._eventMap = {

        };
        this._onUpdateDeviceList = null;
        this._onUpdateNewData = null;

        this.startMonitorDriverEvent = this.startMonitorDriverEvent.bind(this);
        this.endMonitorDriverEvent = this.endMonitorDriverEvent.bind(this);
        this.startScan = this.startScan.bind(this);
        this.stopScan = this.stopScan.bind(this);
        this._timeoutPromise = this._timeoutPromise.bind(this);
        this.connectDevice = this.connectDevice.bind(this);
        this._mixTimeoutPromise = this._mixTimeoutPromise.bind(this);
        this._executeEvent = this._executeEvent.bind(this);
        this._registerEvent = this._registerEvent.bind(this);
        this._commadTimeInterval = this._commadTimeInterval.bind(this);
        this.createAuthChannel = this.createAuthChannel.bind(this);
        this.disconnecAllDevicestWithout = this.disconnecAllDevicestWithout.bind(this);
        this.getAllDataFromIndex = this.getAllDataFromIndex.bind(this);
        this.disconnectDevice = this.disconnectDevice.bind(this);
    }

    /** 创建 */
    static shareDriver() {
        if (driver === null) {
            driver = new RNDYGlucoseDriver();
        }

        return driver;
    }

    /** 开始扫描 */
    startScan() {
        console.log(TAG, '开始扫描!!!!!!');
        if (Platform.OS === 'ios') {
            NativeModules.RNMethodModule.startScanDynamicGlucose();
            NativeModules.RNMethodModule.forceUpdateDeviceList();
        } else {
            MethodModule.startScanDynamicGlucose();
            MethodModule.forceUpdateDeviceList();
        }
    }

    /** 停止扫描 */
    stopScan() {
        console.log(TAG, '停止扫描');
        if (Platform.OS === 'ios') {
            NativeModules.RNMethodModule.stopScanDynamicGlucose();
        } else if (Platform.OS === 'android') {
            MethodModule.stopScanDynamicGlucose();
        }
    }

    set onUpdateDeviceList(delegate) {
        if (typeof delegate !== 'function') {
            throw new Error('update device list must be a function');
        }

        this._onUpdateDeviceList = delegate;
    }

    set onUpdateNewData(delegate) {
        if (typeof delegate !== 'function') {
            throw new Error('update device list must be a function');
        }

        this._onUpdateNewData = delegate;
    }

    /** 开始监控 */
    startMonitor(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject(new Error('paras type error'));
                return;
            }
            console.log(TAG, 'start monitor');
            MethodModule.startMonitorDYG(deviceMac, START_MONITOR);
            this._eventMap[DYG_ON_START_MONITOR] = (deviceInfo) => {
                console.log(TAG, 'resolve connect');
                resolve(deviceInfo.isSuc);
            }
        });
        const timer = this._timeoutPromise(OVER_TIME);
        const mixPromise = Promise.race([devicePromise, timer]);
        return mixPromise;
    }

    /** 停止监控 */
    stopMonitor(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject(new Error('paras type error'));
                return;
            }
            console.log(TAG, 'stop monitor');
            MethodModule.stopMonitorDYG(deviceMac, STOP_MONITOR);
            this._eventMap[DYG_ON_STOP_MONITOR] = (deviceInfo) => {
                console.log(TAG, 'resolve stop monitor');
                resolve(deviceInfo.isSuc);
            }
        });
        const timer = this._timeoutPromise(OVER_TIME);
        const mixPromise = Promise.race([devicePromise, timer]);
        return mixPromise;
    }

    /** 创建通道 */
    async createAuthChannel(deviceMac) {
        return new Promise(async (resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }

            try {
                if (Platform.OS === 'android') {
                    MethodModule.stopScanDynamicGlucose();
                } else if (Platform.OS === 'ios') {
                    NativeModules.RNMethodModule.stopScanDynamicGlucose();
                }

                await this.connectDevice(deviceMac);
                await this._commadTimeInterval(COMMAND_TIME_INTERVAL);

                if (Platform.OS === 'android') {
                    MethodModule.forceUpdateDeviceList();
                } else if (Platform.OS === 'ios') {
                    NativeModules.RNMethodModule.forceUpdateDeviceList();
                }

                const info = await this.doAuthorization(deviceMac);
                console.log(TAG, 'auth info:', info);
                this.disconnecAllDevicestWithout(deviceMac);
                if (Platform.OS === 'android') {
                    MethodModule.forceUpdateDeviceList();
                    MethodModule.startScanDynamicGlucose();

                } else if (Platform.OS === 'ios') {
                    NativeModules.RNMethodModule.forceUpdateDeviceList();
                    NativeModules.RNMethodModule.startScanDynamicGlucose();

                }

                resolve(info);
            } catch (e) {
                console.log(TAG, e);
                if (Platform.OS === 'android') {
                    MethodModule.startScanDynamicGlucose();
                } else if (Platform.OS === 'ios') {
                    NativeModules.RNMethodModule.startScanDynamicGlucose();
                }
                reject(e);
            }
        });

    }

    /** 断开除指定设备 */
    disconnecAllDevicestWithout(deviceMac) {
        MethodModule.disconnecAllDYGDevicetWithout(deviceMac);
    }

    /** 开始连接单独设备 */
    connectDevice(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'driver auth');
            MethodModule.connectDynamicGlucose(deviceMac);
            if (Platform.OS === 'android') {
                MethodModule.forceUpdateDeviceList();
            } else if (Platform.OS === 'ios') {
                NativeModules.RNMethodModule.forceUpdateDeviceList();
            }

            this._eventMap[DYG_CREATED_CHANNEL] = (deviceInfo) => {
                console.log(TAG, 'resolve connect');
                resolve(deviceInfo);
            }
        });
        const timer = this._timeoutPromise(CONNECT_OVER_TIME);
        const mixPromise = Promise.race([devicePromise, timer]);
        return mixPromise;
    }

    /** 认证设备 */
    doAuthorization(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'driver start');
            MethodModule.doAuthorizationDYG(deviceMac, START_MONITOR);
            this._eventMap[DYG_ON_DO_AUTHORIZATION] = (deviceInfo) => {
                console.log(TAG, 'resolve auth');
                resolve(deviceInfo);
            }
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    /** 获得状态 */
    getMonitorStatus(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'get monitor status');
            MethodModule.getMonitorStatusDYG(deviceMac, GET_MONITOR_STATUS);
            this._eventMap[DYG_ON_GET_MONITOR_STATUS] = (deviceInfo) => {
                console.log(TAG, 'resolve get monitor status');
                resolve(deviceInfo.isStartMonitor);
            }
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    /** 获得名字 */
    getName(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'get monitor status');
            MethodModule.getNameDYG(deviceMac, GET_NAME);
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    /** 获得版本号 */
    getVersion(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'get monitor status');
            MethodModule.getVersionDYG(deviceMac, getVersion);
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    /** 获得序列号 */
    getSN(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'get monitor status');
            MethodModule.getSnDYG(deviceMac, getSN);
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    /** 获得电池电量 */
    getBattery(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'get battery status');

            MethodModule.getBatteryDYG(deviceMac, GET_BATTERY);
            this._eventMap[DYG_ON_GET_BATTERY] = (deviceInfo) => {
                console.log(TAG, 'resolve ' + DYG_ON_GET_BATTERY);
                const { value } = deviceInfo;
                const percent = (value - 2.85) / (2.95 - 2.85); // 改成2.95貌似比较合适
                resolve(percent);
            }
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    calculateDyRoc(index, refValue, values) {
        return new Promise(async (resolve, reject) => {
            const info = {
                index: index,
                refValue: refValue,
                values: values
            }

            try {
                const values = await MethodModule.caculateDyRoc(info);
                resolve(values);
            } catch (e) {

            }
        })
    }


    /**得到所有的数据 
     * 
     * finish(error,[]);
     * progress(currentCount,amountCount,[],[])
    */
    async getAllData(deviceMac, progress, finish) {
        if (typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function') {
            throw new Error('paras type error');
        }

        console.log(TAG, 'get all data');

        let receiveData = null;
        let dataList = [];
        let timer = null;
        try {
            const count = await this.getAllDataCount(deviceMac);
            if (count === 0) {
                finish(null, []);
                return;
            }

            receiveData = (deviceInfo) => {
                if (deviceInfo.deviceMac !== deviceMac) {
                    return;
                }

                clearTimeout(timer);
                dataList = dataList.concat(deviceInfo.dataList);


                if (dataList.length >= count) {
                    // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData); 
                    if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                        this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                        delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                    }
                    finish(null, dataList);
                    return;
                } else {
                    progress(dataList.length, count, deviceInfo.dataList, dataList);
                }

                timer = setTimeout(() => {
                    // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                    if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                        this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                        delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                    }
                    finish(new Error('receive data time out'))
                }, PROGRESS_TIME_INTERVAL);
            };



            this.subscriptionMap[DYG_ON_GET_ALL_DATA] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA, receiveData);
            await this._commadTimeInterval(COMMAND_TIME_INTERVAL);
            MethodModule.getAllDataDYG(deviceMac, GET_ALL_DATA);

            timer = setTimeout(() => {
                // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                    this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                    delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                }
                finish(new Error('receive data time out'))
            }, PROGRESS_TIME_INTERVAL);

        } catch (e) {
            console.log(TAG, e);
            finish(e);
        }
    }

    async getAllDataFromIndex(deviceMac, index, progress, finish) {
        if (typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function') {
            throw new Error('paras type error');
        }
        // index = 45

        console.log(TAG, 'get  data from index');

        let receiveData = null;
        let dataList = [];
        let timer = null;
        try {
            let count = await this.getAllDataCount(deviceMac);
            if (count === 0 || index >= count) {
                finish(null, []);
                return;
            }

            count = count - index;
            console.log(TAG, 'count:', count);
            receiveData = (deviceInfo) => {
                if (deviceInfo.deviceMac !== deviceMac) {
                    return;
                }

                clearTimeout(timer);
                dataList = dataList.concat(deviceInfo.dataList);
                console.log(TAG, 'rcv data count', dataList.length);

                if (dataList.length >= count) {
                    // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                    if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                        this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                        delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                    }
                    finish(null, dataList);
                    return;
                } else {
                    progress(dataList.length, count, deviceInfo.dataList, dataList);
                }

                timer = setTimeout(() => {
                    // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                    if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                        this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                        delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                    }

                    finish(new Error('receive data time out'))
                }, PROGRESS_TIME_INTERVAL);
            };



            this.subscriptionMap[DYG_ON_GET_ALL_DATA] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA, receiveData);
            await this._commadTimeInterval(COMMAND_TIME_INTERVAL);
            MethodModule.getAllDataFromIndexDYG(deviceMac, GET_ALL_DATA_FROM_INDEX, index);

            timer = setTimeout(() => {
                // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                    this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                    delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                }
                finish(new Error('receive data time out'))
            }, PROGRESS_TIME_INTERVAL);

        } catch (e) {
            console.log(TAG, e);
            finish(e);
        }
    }

    async getNumberDataFromIndex(deviceMac, index, number, progress, finish) {
        if (typeof deviceMac !== 'string' || typeof progress !== 'function' || typeof finish !== 'function') {
            throw new Error('paras type error');
        }

        console.log(TAG, 'get  data from index');

        let receiveData = null;
        let dataList = [];
        let timer = null;
        try {
            let count = await this.getAllDataCount(deviceMac);
            if (count === 0 || index >= count) {
                finish(null, []);
                return;
            }

            count = (count - index) > number ? number : (count - index);
            console.log(TAG, 'count:', count);
            receiveData = (deviceInfo) => {
                if (deviceInfo.deviceMac !== deviceMac) {
                    return;
                }

                clearTimeout(timer);
                dataList = dataList.concat(deviceInfo.dataList);
                console.log(TAG, 'rcv device data length:', dataList.length);
                if (dataList.length >= count) {
                    // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                    if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                        this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                        delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                    }
                    finish(null, dataList);
                    return;
                } else {
                    progress(dataList.length, count, deviceInfo.dataList, dataList);
                }

                timer = setTimeout(() => {
                    // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                    if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                        this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                        delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                    }
                    finish(new Error('receive data time out'));
                }, PROGRESS_TIME_INTERVAL);
            };



            this.subscriptionMap[DYG_ON_GET_ALL_DATA] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA, receiveData);
            await this._commadTimeInterval(COMMAND_TIME_INTERVAL);
            MethodModule.getNumberDataFromIndexDYG(deviceMac, GET_NUMBER_DATA_FROM_INDEX, index, count);

            timer = setTimeout(() => {
                // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA, receiveData);
                if (this.subscriptionMap['DYG_ON_GET_ALL_DATA']) {
                    this.subscriptionMap['DYG_ON_GET_ALL_DATA'].remove();
                    delete this.subscriptionMap['DYG_ON_GET_ALL_DATA']; // 可选，从映射中删除键，避免内存泄漏
                }
                finish(new Error('receive data time out'));
            }, PROGRESS_TIME_INTERVAL);

        } catch (e) {
            console.log(TAG, e);
            finish(e);
        }
    }



    /** 得到所有数据数量 */
    getAllDataCount(deviceMac) {
        const devicePromise = new Promise((resolve, reject) => {
            if (typeof deviceMac !== 'string') {
                reject('paras type error');
                return;
            }
            console.log(TAG, 'get all data count');
            MethodModule.getAllDataCountDYG(deviceMac, GET_ALL_DATA_COUNT);
            this._eventMap[DYG_ON_GET_ALL_DATA_COUNT] = (deviceInfo) => {
                console.log(TAG, 'resolve ' + DYG_ON_GET_ALL_DATA_COUNT);
                resolve(deviceInfo.count);
            }
        });
        return this._mixTimeoutPromise(devicePromise);
    }

    /** 断开连接 */
    disconnectDevice(deviceMac) {
        if (Platform.OS === 'android') {
            MethodModule.disconnectDevice(deviceMac);
        } else if (Platform.OS === 'ios') {
            NativeModules.RNMethodModule.disconnectDevice(deviceMac)
        }
    }


    calculateBloodGlucose(index, refValue, values) {
        return new Promise(async (resolve, reject) => {
            const info = {
                index: index,
                refValue: refValue,
                values: values
            }

            try {
                const values = await MethodModule.caculateBloodGlucose(info);
                resolve(values);
            } catch (e) {

            }
        })

    }

    _mixTimeoutPromise(devicePromise) {
        const timer = this._timeoutPromise(OVER_TIME);
        const mixPromise = Promise.race([devicePromise, timer]);
        return mixPromise;
    }

    _timeoutPromise(delay) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                reject(new Error('timeout'));
            }, delay);
        });
    }

    _commadTimeInterval(interval) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve('command await time out');
            }, interval);
        });
    }


    _registerEvent(eventName) {
        this._eventMap[eventName] = (deviceInfo) => {
            console.log(TAG, 'resolve ' + eventName);
            resolve(deviceInfo);
        }
    }

    _isFunctionEmpty(event) {
        if (event === undefined || event === null) {
            return true;
        }
        return false;
    }

    _executeEvent(eventName, deviceInfo) {
        const event = this._eventMap[eventName];
        if (this._isFunctionEmpty(event)) {
            return;
        }

        event(deviceInfo);
        this._eventMap[eventName] = null;
    }

    /** 监控底层驱动发送的消息 */
    startMonitorDriverEvent() {
        this._createChannel = (deviceInfo) => {
            console.log(TAG, 'created channel');
            this._executeEvent(DYG_CREATED_CHANNEL, deviceInfo);
        };
        this.subscriptionMap['DYG_CREATED_CHANNEL'] = DeviceEventEmitter.addListener(DYG_CREATED_CHANNEL, this._createChannel);


        this._onDoAuthorization = (deviceInfo) => {
            console.log(TAG, 'received ' + DYG_ON_DO_AUTHORIZATION);
            this._executeEvent(DYG_ON_DO_AUTHORIZATION, deviceInfo);
        };
        this.subscriptionMap[DYG_ON_DO_AUTHORIZATION] = DeviceEventEmitter.addListener(DYG_ON_DO_AUTHORIZATION, this._onDoAuthorization);

        this._onGetBattery = (deviceInfo) => {
            console.log(TAG, 'received ' + DYG_ON_GET_BATTERY);
            this._executeEvent(DYG_ON_GET_BATTERY, deviceInfo);
        };
        this.subscriptionMap[DYG_ON_GET_BATTERY] = DeviceEventEmitter.addListener(DYG_ON_GET_BATTERY, this._onGetBattery);

        this._onGetAllDataCount = (deviceInfo) => {
            console.log(TAG, 'received ' + DYG_ON_GET_ALL_DATA_COUNT);
            this._executeEvent(DYG_ON_GET_ALL_DATA_COUNT, deviceInfo);
        };
        this.subscriptionMap[DYG_ON_GET_ALL_DATA_COUNT] = DeviceEventEmitter.addListener(DYG_ON_GET_ALL_DATA_COUNT, this._onGetAllDataCount);

        this._updateDeviceList = (deviceInfos) => {
            // console.log(TAG,deviceInfos);
            if (this._onUpdateDeviceList === null) {
                return;
            }
            const deviceList = deviceInfos.filter((device) => {
                return device.deviceName.indexOf('TH-') >= 0
            });

            this._onUpdateDeviceList(deviceList);
        };
        this.subscriptionMap[UPDATE_DEVICE_LIST] = DeviceEventEmitter.addListener(UPDATE_DEVICE_LIST, this._updateDeviceList);

        /** 获得当前监控的状态 */
        this._onGetMonitorStatus = (deviceInfo) => {
            this._executeEvent(DYG_ON_GET_MONITOR_STATUS, deviceInfo);
        }
        this.subscriptionMap[DYG_ON_GET_MONITOR_STATUS] = DeviceEventEmitter.addListener(DYG_ON_GET_MONITOR_STATUS, this._onGetMonitorStatus);

        /** 获得是否已经开始监控 */
        this._onStartMonitor = (deviceInfo) => {
            this._executeEvent(DYG_ON_START_MONITOR, deviceInfo);
        }
        this.subscriptionMap[DYG_ON_START_MONITOR] = DeviceEventEmitter.addListener(DYG_ON_START_MONITOR, this._onStartMonitor);

        this._onStopMonitor = (deviceInfo) => {
            this._executeEvent(DYG_ON_STOP_MONITOR, deviceInfo);
        }
        this.subscriptionMap[DYG_ON_STOP_MONITOR] = DeviceEventEmitter.addListener(DYG_ON_STOP_MONITOR, this._onStopMonitor);



        /** 监听接收到的单条新消息 */
        this._updateNewData = (deviceInfo) => {
            if (this._onUpdateNewData === null) {
                return;
            }

            this._onUpdateNewData(deviceInfo.index, deviceInfo.value);
        }
        this.subscriptionMap[DYG_ON_UPDATE_NEW_DATA] = DeviceEventEmitter.addListener(DYG_ON_UPDATE_NEW_DATA, this._updateNewData);

    }

    endMonitorDriverEvent() {
        // DeviceEventEmitter.removeListener(DYG_CREATED_CHANNEL,this._createChannel);
        // DeviceEventEmitter.removeListener(DYG_ON_DO_AUTHORIZATION,this._onDoAuthorization);
        // DeviceEventEmitter.removeListener(DYG_ON_GET_ALL_DATA_COUNT,this._onGetAllDataCount);
        // DeviceEventEmitter.removeListener(DYG_ON_GET_MONITOR_STATUS,this._onGetMonitorStatus);
        // DeviceEventEmitter.removeListener(UPDATE_DEVICE_LIST,this._updateDeviceList);
        // DeviceEventEmitter.removeListener(DYG_ON_START_MONITOR,this._onStartMonitor);
        // DeviceEventEmitter.removeListener(DYG_ON_STOP_MONITOR,this._onStopMonitor);
        // DeviceEventEmitter.removeListener(DYG_ON_UPDATE_NEW_DATA,this._updateNewData);
        // DeviceEventEmitter.removeListener(DYG_ON_GET_BATTERY,this._onGetBattery);

        // 移除监听器
        Object.keys(this.subscriptionMap).forEach(key => {
            this.subscriptionMap[key].remove();
        });

        // 清除订阅对象记录，避免内存泄漏
        this.subscriptionMap = {};
    }
}

