// 引入必要的模块
// 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 {
  EnumCmdEvent,
  CmdEvent
} = require('./../devices/cmd_key_event');
const {
  addNotification
} = require('./../utils/event_bus');
const BtParse = require('./../devices/bluetooth/bt_parse');
// const VolumeUtil = require('./VolumeUtil');
// const EventManager = require('./EventManager');
// const CmdBase = require('./../devices/bluetooth/bt_cmd');
const bleManager = require('./ble_manager');
const QueueManager = require('./QueueManager');

// 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 getInstance() {
    // if (!BtHelper._instance) {
    //     BtHelper._instance = new BtHelper();
    // }
    return BtHelper._instance;
  }

  static _instance = new BtHelper();
  static _isConnecting = false;
  static isDisConnectByOTA = false;
  // _helper;

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

    // QueueManager.instance.listenTask((task) => {
    //     if (!DeviceManager.instance.isWatch) {
    //         that._helper.send({ cmd: task });
    //     }
    // });
    that.queueManager = new QueueManager();
    that.queueManager.clear();
    that.queueManager.listenTask((task) => {
      that.bleManager.sendData(task);
    });
    addNotification(CmdEvent.eventName, function (event) {
      // console.log("蓝牙helper：", event)
      let device = getApp().globalData.mDeviceList[0] ?? {};
      if (device.connectType != 1 && device.state != "online") {
        return;
      }
      that.handleCommand(event, device);
    }, this)
  }

  ///获取比较的数据
  getCompareList() {
    return this.bleManager.getCompareList();
  }

  getDissmissDevice() {
    return this.bleManager.getDissmissDevice();
  }

  getCallBackConnect() {
    return this.bleManager.getCallBackConnect();
  }

  ///初始化蓝牙适配器
  initBluetoothAdapter() {
    var that = this;
    that.bleManager.initBluetoothAdapter();
  }

  ///获取蓝牙设备 connect:true，去连接，false,去对比
  getBluetoothDevices() {
    var that = this;
    that.bleManager.getBluetoothDevices();
  }

  ///搜索蓝牙设备
  startScan(connectWillDevice, boolean, callBackConnect) {
    var that = this;
    that.bleManager.startScan(
      connectWillDevice,
      boolean,
      callBackConnect,
    );
  }

  ///停止搜索蓝牙设备
  async stopSearch() {
    var that = this;
    await that.bleManager.stopSearch();
  }

  ///获取蓝牙权限
  async getBluetoothPermission() {
    var that = this;
    await that.bleManager.getBluetoothPermission();
  }

  ///断开设备连接
  async disconnect(device) {
    await this.bleManager.disconnect(device)
  }

  handleCommand(event, mDevice) {
    let name = event.cmdEvent;
    switch (name) {
      ///音量  设备控制手机
      case EnumCmdEvent.volume:
        var volume = event.volume;
        // if (ProviderUtil.play.isSimulate) {
        //   _isPhoneVolume = false;
        //   await VolumeUtil.setVolume(volume);
        //   Future.delayed(const Duration(milliseconds: 100), () {
        //     _isPhoneVolume = true;
        //   });
        // }
        mDevice.volume = volume;
        break;

        ///电量
      case EnumCmdEvent.battery:
        mDevice.kwh = event.kwh;
        break;

        ///低时延模式  低时延模式开启 1:音乐 , 2: 游戏 , 3: movie
      case EnumCmdEvent.lowDelayMode:
        mDevice.lowDelayMode = event.lowDelayMode;
        mDevice.lowDelayModeOpen = event.lowDelayModeOpen;
        break;

        ///电量 耳机电量
      case EnumCmdEvent.batteryEarphone:
        mDevice.kwh = event.kwh;
        mDevice.kwhLeft = event.kwhLeft;
        mDevice.kwhRight = event.kwhRight;
        mDevice.kwhBox = event.kwhBox;
        break;

        ///是否支持TTS
      case EnumCmdEvent.enableTTS:
        mDevice.enableTTS = event.enableTTS;
        break;

        ///切换设备连接模式 0:未知 1：低功耗蓝牙 2：wifi类型 3：经典蓝牙(不做任何操作) 4：4G类型
      case EnumCmdEvent.switchDeviceMode:
        var deviceMode = event.deviceMode.index;
        if (deviceMode != null) {
          L.d("switchDeviceMode======$deviceMode");
          mDevice.deviceMode = deviceMode;
        }
        break;

        ///4G外插卡  4G虚拟卡 当前使用的sim卡
      case EnumCmdEvent.sim:
        mDevice.sim = event.sim;
        mDevice.eSim = event.eSim;
        mDevice.simIndex = event.simIndex;
        break;

        ///闹钟是否开启  闹钟周期 闹钟唤醒时间
      case EnumCmdEvent.wake:
        mDevice.wakeSwitch = event.wakeSwitch;
        mDevice.wakeCycle = event.wakeCycle;
        mDevice.wakeHour = event.wakeHour;
        mDevice.wakeMinutes = event.wakeMinutes;
        break;

        ///休眠是否开启 休眠时间
      case EnumCmdEvent.sleep:
        mDevice.sleepSwitch = event.sleepSwitch;
        mDevice.sleepHour = event.sleepHour;
        mDevice.sleepMinutes = event.sleepMinutes;
        break;

        ///版本和型号
      case EnumCmdEvent.version:
        mDevice.version = event.version;
        var clientType = mDevice.clientType ?? "";

        ///验证设备首页固件升级图标
        // getCheckOTAIndexProvider.refresh();

        // // TODO 校验版本是否升级
        // if (clientType.isNotEmpty) {
        //     var response = await DeviceService.getDeviceDetail(
        //         clientType: clientType,
        //         version: event.version,
        //         type: mDevice.deviceMode ?? EnumDeviceMode.ble.index,
        //     );

        //     if (response.isSuccess) {
        //         DeviceDetailEntity ? updateData = response.data;
        //         if (updateData != null) {
        //             // mDevice.typeList = updateData.typeList;
        //             // 是否强制升级0-无更新 1-是,2-否
        //             var force = updateData.isEnforcement;
        //             var hasNewVersion = force == 1 || force == 2;


        //             // if (force == 1) {
        //             //     EventManager.fire(OtaUpdateEvent(updateData: updateData));
        //             // }
        //         }
        //     }
        // }
        break;

        ///云小微授权
      case EnumCmdEvent.auth:
        var authInfo = event.authInfo;
        mDevice.authInfo = authInfo;
        // QQMusicManager.auth(authInfo: authInfo);
        // CacheUtil.saveDSN(dsn: authInfo.dsn ?? "");
        break;
      case EnumCmdEvent.btMac:
        var btMac = event.btMac;
        mDevice.btMac = btMac;
        // // 更新一下 imei
        // getDeviceImei().then((e) {
        //     mDevice.imei = e;
        // });
        break;

        ///EQ音效
      case EnumCmdEvent.eq:
        mDevice.eqs = event.eqs;
        break;

        ///payId 充流量使用
      case EnumCmdEvent.payId:
        mDevice.payId = event.payId;
        break;

        ///QQ音乐使用dsn授权
      case EnumCmdEvent.dsn:
        var dsn = event.dsn;
        mDevice.dsn = dsn;
        // //存储设备的DSN
        // await CacheUtil.saveDSN(dsn: dsn ?? "");
        // ProviderUtil.twelvePublic.wifiDeviceConnected();
        break;

        ///自动切换 0，1不能
        ///
      case EnumCmdEvent.netModeAuto:
        mDevice.netModeAuto = event.netModeAuto;
        break;

        ///解绑设备
      case EnumCmdEvent.unbind:
        //   let unbindAddress = event.item.address ?? "";
        //     if (unbindAddress != mDevice.address) {
        //         _resetList();
        //         return;
        //     }
        //     _lastConnectAddress = null;
        //     bondedDeviceData.remove(mDevice);
        //     if (mDevice.address == event.item.address) {
        //         mDevice = null;
        //     }
        //     _resetList();

        break;

        ///解绑设备
      case EnumCmdEvent.ctrlStatus:
        // List < int > ctrlList = event.ctrlStatus;
        // if (ctrlList.length == 3) {
        //     mDevice.singleClick = ctrlList[0];
        //     mDevice.doubleClick = ctrlList[1];
        //     mDevice.longPressClick = ctrlList[2];
        // }
        break;

      case EnumCmdEvent.lowPowerOpen:
        let lowPower = event.lowPowerOpen ?? 0;
        mDevice.lowPowerOpen = lowPower;
        break;

      case EnumCmdEvent.authSleepStatus:
        let pauseSleep = event.pauseSleep;
        mDevice.pauseSleep = pauseSleep;

        // notifyListeners();
        break;

        ///设备信息
      case EnumCmdEvent.getDeviceInfo:
        //   List list = [];
        //   String userId = ProviderUtil.user.userModel.uid ?? "";
        //     for (var element in bondedDeviceData) {
        //         list.add({
        //             "clientType": element.clientType ?? "",
        //             "userId": userId,
        //             "deviceName": element.name ?? "",
        //             "mac": element.address,
        //             "deviceId": element.deviceId ?? 0,
        //         });
        //     }

        //     MobClickEvent.mobClickEvent(EnumMobEvent.eventDevicesConnect, params: { "devices": list });
        //     if (mDevice != null) {
        //         mDevice.imei ??= await CacheUtil.getImei(address: mDevice.address ?? "");

        //         /// 用户绑定设备
        //         await CacheUtil.addDevice(item: mDevice!);

        //         // String dsn = await CacheUtil.getDSN();
        //         // if (dsn.isEmpty) {
        //         // 获取设备dsn
        //         DeviceManager.instance.auth();
        //         // }
        //         //延迟
        //         var address = mDevice.address ?? "";
        //     bool isSuccess = await ProviderUtil.twelve.questDeviceTwelveData(address);
        //         if (isSuccess) {
        //       bool showDevice = await DeviceChannelAllPage.presentPage();
        //             if (!showDevice) {
        //                 VipOpenAiTingDialogWidget.presentPage();
        //             }
        //         }
        //     }
        //     await CacheUtil.saveConnectedDevice(list: bondedDeviceData);

        break;
      default:
        break;
    }
  }

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

  async stopSearch() {
    clearTimeout(this.timer);
    this.timer = null;
    await this.bleManager.stopSearch();
  }

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

  async connect(device, onChanged) {
    var that = this;
    await that.disconnect(device);
    clearTimeout(that.timer);
    that.timer = null;
    that.bleManager.stopSearch()
    var res = await that.bleManager.connectToDevice(device);
    if (res === false) {
      console.log("连接失败")
      that.disconnect(device)
      if (onChanged) {
        onChanged(false, device)
      }
      return
    }

    const serviceId = await that.bleManager.discoverServices(device.deviceId);
    if (serviceId == "") {
      console.log("连接失败")
      that.disconnect(device)
      if (onChanged) {
        onChanged(false, device)
      }
      return
    }
    // that.setData({ services });
    console.log("服务ID:" + serviceId)
    var characteristics = await that.bleManager.discoverCharacteristics(device.deviceId, serviceId)
    if (characteristics == "") {
      console.log("连接失败")
      that.disconnect(device)
      if (onChanged) {
        onChanged(false, device)
      }
      return
    }
    console.log('device特征值:', characteristics)
    let uuids = ["AB01", "FFC1"];
    for (let i = 0; i < characteristics.length; i++) {
      let charc = characteristics[i];
      if (uuids.includes(charc.uuid.toUpperCase())) {
        console.log('有特征值：', charc.uuid);
      }

      if (charc.properties.notify) {
        console.log('订阅数据：', charc.uuid);
        // 订阅的
        that.bleManager.notifyCharacteristicValueChange(charc.uuid, (res) => {
          BtParse.parseTLV(res);
        })
      }
      if (charc.properties.write || charc.properties.writeWithoutResponse) {
        // 写入的
        that.bleManager.setWrite(charc, charc.uuid)
        setTimeout(() => {
          that._connectSuccess()
        }, 100);

        ///解决连接之后会有一段时间显示离线，先添加进去就不会了
        var has = false;
        var compareList = that.bleManager.getCompareList();
        for (var j = 0; j < compareList.length; j++) {
          if (compareList[j].deviceId == device.deviceId) {
            has = true;
          }
        }
        if (!has) {
          compareList.unshift(device);
          that.bleManager.setCompareList(compareList);
        }

        if (onChanged) {
          onChanged(true, device);
        }
      }

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


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

  }

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

  async sendNow(cmd) {
    if (cmd) {
      this.bleManager.sendData(cmd)
    }
  }
  async send(cmd) {
    if (cmd) {
      this.queueManager.addTask(cmd)
    }
    // QueueManager.instance.addTask({ task: cmd });
  }

  static sendCallBack(cmd, callback) {
    BtHelper.getInstance().bleManager.sendData(cmd, callback)
  }

  // onLoad: function () {
  //     bleManager = new bleManager();
  //     this.initBluetooth();
  //   }

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

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

  async getVersion() {
    var that = this;
    that.send(BtCmd.queryVersion());
  }

  _time() {
    return 400;
  }

  getDeviceInfo() {
    var that = this;
    // if (DeviceManager.instance.isEarphone) {
    //     that.send(BtCmd.queryKwhEarPhone);
    //     that.send(BtCmd.queryLowDelayMode);
    //     that.send(BtCmd.queryEQ);
    //     that.send(BtCmd.queryLowPower);
    //     that.send(BtCmd.queryCtrlStatus);
    // } else {
    // that.send(BtCmd.setDevTime());

    // that.send(BtCmd.queryKwh());
    that.getSleep();
    // that.getAlert();
    // that.send(BtCmd.queryRGB());
    // that.getVolume();
    // that.setVolume(8)
    that.getPauseSleep();

    // that.send(BtCmd.getClientType());
    that.send(BtCmd.getIsConnect());
    // that.send(BtCmd.getMac());

    // }
  }

  async getAlert() {
    var that = this;
    that.send(BtCmd.queryAlarm());
  }

  async getSleep() {
    var that = this;
    that.send(BtCmd.querySleep());
  }

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

  async setAutoPlay(open) {
    var that = this;
    that.send(BtCmd.setAutoPlay(open));
  }

  async getAutoPlay() {
    var that = this;
    that.send(BtCmd.getAutoPlay);
  }

  async setLowKwhWarningTone(notify) {
    var that = this;
    that.send(BtCmd.setLowKwhWarningTone(notify));
  }

  async setPauseSleep(time) {
    var that = this;
    that.send(BtCmd.setSleepAfterPlayPause(time));
  }

  async getPauseSleep() {
    var that = this;
    that.send(BtCmd.querySleepAfterPlayPause());
  }

  async setRGB(r, g, b) {
    var that = this;
    that.send(BtCmd.setRGB({
      r,
      g,
      b
    }));
  }

  async setSleep(open, hour, minutes) {
    var that = this;
    let defaultMin = minutes ?? 10;
    let defaultHour = hour ?? 0;
    that.send(BtCmd.setSleep({
      switchStatus: open,
      defaultHour,
      defaultMin
    }));
  }

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

  async setVolume(volume) {
    var that = this;
    // VolumeUtil.setVolume(volume, { hideVolumeView: true });

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

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

    that.send(BtCmd.setVolume(8));
  }

  async getVolume() {
    var that = this;
    that.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() {
    var that = this;
    that.send(BtCmd.queryLowDelayMode());
  }

  async setLowDelayMode(open, mode) {
    // 0 open,
    // 1 close,
    // mode 1:音乐 , 2: 游戏 , 3: movie
    var that = this;
    that.send(BtCmd.setLowDelayMode({
      open,
      mode
    }));
  }

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

  async queryLowPower() {
    var that = this;
    that.send(BtCmd.queryLowPower());
  }

  async setCtrlStatus(singleClick, doubleClick, longClick) {
    var that = this;
    that.send(BtCmd.setCtrlStatus({
      singleClick,
      doubleClick,
      longClick
    }));
  }

  async getEQ() {
    var that = this;
    that.send(BtCmd.queryEQ());
  }

  async setEQ(list) {
    var that = this;
    that.send(BtCmd.setEQ({
      list
    }));
  }

  async queryLowKwhWarningTone() {
    var that = this;
    that.send(BtCmd.queryLowKwhWarningTone());
  }

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

  /* 黑胶音箱的指令 */
  // 壁纸指令 1开始， 0结束
  wallPaper(value) {
    var that = this;
    that.send(BtCmd.wallPaper(value));
  }
  // 壁纸指令 
  wallPaperData(value, callback) {
    BtHelper.sendCallBack(BtCmd.wallPaperData(value), callback);
  }
  // 背景图指令
  backgroudImg(value) {
    var that = this;
    that.send(BtCmd.backgroudImg(value));
  } // 背景图指令
  backgroudImgData(value) {
    var that = this;
    that.send(BtCmd.backgroudImgData(value));
  }
  // OTA指令
  otaCmd(value) {
    this.send(BtCmd.otaCmd(value));
  }
  otaData(value, callback) {
    BtHelper.sendCallBack(BtCmd.wallPaperData(value), callback);
  }

  async closeBle() {
    var that = this;
    that.bleManager.closeBle();
    await that.bleManager.stopSearch();
  }

}


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

module.exports = {
  BtHelper
}