module.exports = {
  compareList: compareList,
}

function compareList(changeCallback, addBlueCallback) {
  var pages = getCurrentPages();
  var deviceList = pages[0].getDeviceList()
  if (deviceList.length > 0) {
    const {
      BtHelper
    } = require('../../devices/bt_helper.js');
    if (BtHelper.getInstance().getCallBackConnect() == null) {
      var compareList = BtHelper.getInstance().getCompareList();
      var dissmissDevice = BtHelper.getInstance().getDissmissDevice();

      ///去掉未连接的离线的
      for (var i = 0; i < dissmissDevice.length; i++) {
        for (var j = 0; j < compareList.length; j++) {
          if (compareList[j].deviceId == dissmissDevice[i].deviceId) {
            compareList.splice(j, 1);
            break;
          }
        }
      }

      if (compareList.length > 0) {
        ///对比在线的蓝牙设备
        var isChanged = false;
        for (var i = 0; i < deviceList.length; i++) {
          var tempItem = deviceList[i];
          if (tempItem.connectType != 3) {
            var has = false;
            for (var j = 0; j < compareList.length; j++) {
              // "state":"online" "offline" MW-SR1(4G_WIFI)
              if (tempItem.deviceId === compareList[j].deviceId) {
                has = true;
                break;
              }
            }

            if (has) {
              if (tempItem.state != "online") {
                isChanged = true;
                tempItem.state = "online";
              }
            } else {
              if (tempItem.state != "offline") {
                isChanged = true;
                tempItem.state = "offline";
              }
            }
          }
        }

        if (isChanged) {
          changeCallback(deviceList);
        }

        ///没有连接则连接第一个在线的蓝牙
        var autoConnected = pages[0].getAutoConnected();
        var deviceListSelect = pages[0].getDeviceListSelect();
        if (!autoConnected && deviceListSelect == null) {
          var list = pages[0].getDeviceList();
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if (item.connectType == 1 && item.state == "online") {
              item.name = item.devName;
              BtHelper.getInstance().connect(item, function (isConnected, device) {
                if (isConnected) {
                  addBlueCallback(device);
                }
              });
              break;
            }
          }
        }
      }
      BtHelper.getInstance().startScan(null, null, null);
    }
  }
};