// 引入必要的模块
// const DeviceUtil = require('./DeviceUtil');
// const BtAndroidHelper = require('./BtAndroidHelper');
// const BtIOSHelper = require('./BtIOSHelper');
// const QueueManager = require('./QueueManager');
// const DeviceManager = require('./DeviceManager');
const { CmdBase, BtCmd, } = require('./../devices/bluetooth/bt_cmd');
const BtParse = require('./../devices/bluetooth/bt_parse');
const ble = require('./ble_manager');
// const VolumeUtil = require('./VolumeUtil');
// const EventManager = require('./EventManager');
// const CmdBase = require('./../devices/bluetooth/bt_cmd');
const bleManager = require('./ble_manager');
// const EnumConnectStatus = require('./EnumConnectStatus');
// const EnumOpen = require('./EnumOpen');
// const EnumSupplier = require('./EnumSupplier');
// const EnumLowDelayModeOpen = require('./EnumLowDelayModeOpen');
// const EnumLowDelayMode = require('./EnumLowDelayMode');
// const EnumPlayStatus = require('./EnumPlayStatus');




class BtHelper {
    // static get instance() {
    //     return this._instance;
    // }

    // static _instance = new BtHelper();

    static _isConnecting = false;
    static isDisConnectByOTA = false;

    // _helper;

    constructor() {
        this.timer = null;
        // if (DeviceUtil.isAndroid) {
        //     this._helper = BtAndroidHelper.instance;
        // } else {
        //     this._helper = BtIOSHelper.instance;
        // }

        // QueueManager.instance.listenTask((task) => {
        //     if (!DeviceManager.instance.isWatch) {
        //         this._helper.send({ cmd: task });
        //     }
        // });
    }


    resetConnectState(connect) {
        // BtHelper._isConnecting = connect;
    }

    async search(mqttFilterList) {
        let res = await bleManager.startScan()
        this.timer = null;
        this.timer = setTimeout(() => {
            bleManager.stopScan();
        }, 10000);
        // console.log(res);
        // return await this._helper.search();
    }

    async findDevices(callback) {
        bleManager.onBluetoothDeviceFound(callback)
        // return await this._helper.search();
    }

    async stopSearch() {
        bleManager.stopScan();
    }

    async _connectSuccess() {
        btHelper.checkDevice()
        btHelper.getDeviceInfo()
    }

    async connect(data, onChanged) {
        // await this._helper.connect({ data, onChanged, isClick });
        try {
            clearTimeout(this.timer);
            this.timer = null;
            bleManager.stopScan()
            var res = await bleManager.connectToDevice(data);
            console.log('连接成功');
            // this.setData({ connectedDeviceId: deviceId });
            if (res === false) {
                console.log("连接失败")
                this.disconnect(data)
                if (onChanged) {
                    onChanged(false)
                }
                return
            }
            const serviceId = await bleManager.discoverServices(data.deviceId);
            if (serviceId == "") {
                console.log("连接失败")
                this.disconnect(data)
                if (onChanged) {
                    onChanged(false)
                }
                return
            }
            // this.setData({ services });
            console.log("服务ID:" + serviceId)

            var characteristics = await bleManager.discoverCharacteristics(data.deviceId, serviceId)
            if (characteristics == "") {
                console.log("连接失败")
                this.disconnect(data)
                if (onChanged) {
                    onChanged(false)
                }
                return
            }
            console.log('device特征值:', characteristics)
            for (let i = 0; i < characteristics.length; i++) {
                let charc = characteristics[i];
                if (charc.properties.notify) {
                    // 订阅的
                    bleManager.notifyCharacteristicValueChange(charc.uuid, (res) => {
                        // console.log('收到数据：', BtParse.parseTLV);
                        BtParse.parseTLV(res);
                    })
                }
                if (charc.properties.write || charc.properties.writeWithoutResponse) {
                    // 写入的
                    bleManager.setWrite(charc, charc.uuid)

                    setTimeout(() => {
                        this._connectSuccess()
                    }, 1000);

                    if (onChanged) {
                        onChanged(true)
                    }
                }
                if (charc.properties.read) {
                    var chara = await bleManager.readCharacteristicValue(charc.uuid,)
                }
            }


            // this.setData({ characteristics: { ...this.data.characteristics, [service.uuid]: characteristics } });

        } catch (error) {
            console.error(error);
        }
    }

    async disconnect(data) {
        bleManager.disconnect(data.deviceId)
    }

    async dispose() {
        // await this._helper.dispose();
    }

    send(cmd, type) {
        console.log('开始发送数据:', cmd)
        if (cmd) {
            bleManager.sendData(cmd)
        }

        // QueueManager.instance.addTask({ task: cmd });
    }
    // onLoad: function () {
    //     bleManager = new bleManager();
    //     this.initBluetooth();
    //   }

    async initBluetooth(callback) {
        try {
            let adpter = await bleManager.initBluetoothAdapter((res) => { });
            // console.log(res)

            bleManager.checkBluetoothPermission(function (per) {
                if (callback) {
                    callback(adpter, per)
                }
            });
            // console.log(per)
        } catch (error) {
            console.error(error);
        }
    }

    closeBle() {
        bleManager.closeBle()
    }

    async getConnectedDevices() {
        try {
            const connectedDevices = await bleManager.getConnectedDevices();
            console.log("全部设备1：", connectedDevices)
            if (connectedDevices.length) {
                // todo 已经连接上的设备
            }
            const allDevices = await bleManager.getAllConnectedDevices()
            console.log("全部设备2：", allDevices)
            let newDevices = connectedDevices.concat(allDevices);
            return newDevices
        } catch (error) {
            console.error(error);
            return []
        }
    }

    async checkDevice() {
        // console.log("校验设备：", BtCmd); // 输出: EarPhone Info
        await this.send(BtCmd.checkDevice());
        //2.0有发这个，不知道是啥
        await this.send([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x26, 0x01, 0x01]);
    }

    async getVersion() {
        await this.send(BtCmd.queryVersion());
    }

    _time() {
        return 400;
    }

    getDeviceInfo() {
        // if (DeviceManager.instance.isEarphone) {
        //     this.send(BtCmd.queryKwhEarPhone);
        //     this.send(BtCmd.queryLowDelayMode);
        //     this.send(BtCmd.queryEQ);
        //     this.send(BtCmd.queryLowPower);
        //     this.send(BtCmd.queryCtrlStatus);
        // } else {
        this.send(BtCmd.setDevTime());
        this.send(BtCmd.queryKwh());
        this.getSleep();
        this.getAlert();
        this.send(BtCmd.queryRGB());
        this.getVolume();
        this.getPauseSleep();
        // }
    }

    async getAlert() {
        await this.send(BtCmd.queryAlarm());
    }

    async getSleep() {
        await this.send(BtCmd.querySleep());
    }

    async setAlert(open, weekCycle, hour, minutes, channel = 1) {
        await this.send(BtCmd.setAlarm({ switchStatus: open, weekCycle, hour, minutes }));
    }

    async setAutoPlay(open) {
        await this.send(BtCmd.setAutoPlay({ switchStatus: open }));
    }

    async getAutoPlay() {
        await this.send(BtCmd.getAutoPlay);
    }

    async setLowKwhWarningTone(notify) {
        await this.send(BtCmd.setLowKwhWarningTone({ notify }));
    }

    async setPauseSleep(time) {
        await this.send(BtCmd.setSleepAfterPlayPause({ time }));
    }

    async getPauseSleep() {
        await this.send(BtCmd.querySleepAfterPlayPause());
    }

    async setRGB(r, g, b) {
        await this.send(BtCmd.setRGB({ r, g, b }));
    }

    async setSleep(open, hour, minutes) {
        await this.send(BtCmd.setSleep({ switchStatus: open, hour, minutes }));
    }

    async setTime() {
        console.log("setTime========111")
        // await this.send(BtCmd.setTime());
    }

    async setVolume(volume) {
        VolumeUtil.setVolume(volume, { hideVolumeView: true });

        const phoneMax = await VolumeUtil.getMaxVolume();
        const result = Math.floor(CmdBase.volumeMax * volume / phoneMax);

        console.log(`phoneMax=${phoneMax}, deviceMax=${CmdBase.volumeMax}, setVolume=${volume}, result=${result}`);

        await this.send(BtCmd.setVolume({ volume: result }));
    }

    async getVolume() {
        await this.send(BtCmd.queryVolume());
    }

    stop() {
        // EventManager.fire({ event: 'playStatus', playStatus: EnumPlayStatus.stop.index });
    }

    next() {
        // TODO: implement next
    }

    pause() {
        // EventManager.fire({ event: 'playStatus', playStatus: EnumPlayStatus.pause.index });
    }

    play() {
        // TODO: implement play
    }

    previous() {
        // TODO: implement previous
    }

    startVoiceRecordResponse(supplier) {
        console.log(`回调开始录音：${supplier}`);
        // switch (supplier) {
        //     case EnumSupplier.jieLi:
        //         this.send(BtCmd.jlStartVoiceResponse);
        //         break;
        //     case EnumSupplier.lingXin:
        //         this.send(BtCmd.lxStartVoiceResponse);
        //         break;
        //     case EnumSupplier.qiXinWei:
        //         this.send(BtCmd.b1StartVoiceResponse);
        //         break;
        // }
    }

    stopVoiceRecordResponse(supplier) {
        console.log(`回调结束录音：${supplier}`);
        // switch (supplier) {
        //     case EnumSupplier.jieLi:
        //         this.send(BtCmd.jlStopVoiceResponse());
        //         break;
        //     case EnumSupplier.lingXin:
        //         this.send(BtCmd.lxStopVoiceResponse());
        //         break;
        //     case EnumSupplier.qiXinWei:
        //         this.send(BtCmd.b1StopVoiceResponse());
        //         break;
        // }
    }

    async getLowDelayMode() {
        await this.send(BtCmd.queryLowDelayMode());
    }

    async setLowDelayMode(open, mode) {
        await this.send(BtCmd.setLowDelayMode({ open, mode }));
    }

    async setLowPowerMode(isOpen) {
        await this.send(BtCmd.setLowPowerMode({ isOpen: isOpen ? EnumOpen.open : EnumOpen.close }));
    }

    async queryLowPower() {
        await this.send(BtCmd.queryLowPower());
    }

    async setCtrlStatus(singleClick, doubleClick, longClick) {
        await this.send(BtCmd.setCtrlStatus({ singleClick, doubleClick, longClick }));
    }

    async getEQ() {
        await this.send(BtCmd.queryEQ());
    }

    async setEQ(list) {
        await this.send(BtCmd.setEQ({ list }));
    }

    async queryLowKwhWarningTone() {
        await this.send(BtCmd.queryLowKwhWarningTone());
    }

    async changeChannelCallBack() {
        await this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x0a, 0x29, 0x02, 0x00, 0x01]));
        await this.send(Uint8Array.from([0x54, 0x44, 0x44, 0x48, 0x01, 0x09, 0x39, 0x01, 0x00]));
    }
}

// 导出 BtHelper 类
const btHelper = new BtHelper();

module.exports = btHelper;