// app.js
const app=getApp()
const EventEmitter2 = require("./components/eventemitter2/index.js").EventEmitter2;
const emitter = new EventEmitter2();
const WXAPI = require('./utils/request') 

const plugin = requirePlugin("myPlugin")

App({
  onLaunch() {
    this.globalData.sysinfo = wx.getSystemInfoSync()
    plugin.init('wx20de9fe5943934a1', '458f9df0-3405-66a9-1cdb-49d5f4197e6a')
    .then(function(res){
      console.log('res', res)
      if(res.code != 200){
        wx.showToast({
          title: res.data.msg,
        })
      }
    })
    wx.login({
      success (res) {
        if (res.code) {
          let data={
            code:res.code
          }
          WXAPI.getOpenId(data).then(res=>{
            console.log(res)
            wx.setStorageSync('openid', res.openid)
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
    // 展示本地存储能力
    var logs = wx.getStorageSync('token') || ''
    var userRole = wx.getStorageSync('userRole') || ''
    var signature= wx.getStorageSync('signature') || ''
    // 登录
    if(logs!=''&&userRole==0){
      this.globalData.token=logs.access_token
      setTimeout(()=>{
        wx.switchTab({
          url: '/pages/index/index',
        })     
    },100)
    }
    if(signature&&userRole==1){
      wx.navigateTo({
        url: '/pages/indexUser/indexUser',
      })
    }
  },
  getDeviceByDevName(devName) {
    return this.globalData.foundBleDevs[devName]
  },
  addDeviceWithDevName(devName, dev) {
    this.globalData.foundBleDevs[devName] = dev
  },
  connectTo: function(options) {
    console.debug('connectTo', options)
    if (typeof options !== 'object') {
      var message = '请求传参应为 object 类型，但实际传了 ' + (typeof options) + ' 类型';
      throw new RequestError('invalid params', message);
    }

    var success = options.success || noop;
    var fail = options.fail || noop;
    var complete = options.complete || noop;

    // 成功回调
    var callSuccess = function() {
      success.apply(null, arguments);
      complete.apply(null, arguments);
    };

    // 失败回调
    var callFail = function(error) {
      fail.call(null, error);
      complete.call(null, error);
    };
    var that = this
    if (options.devName == undefined) {
      throw new RequestError('invalid params', 'options.devName');
    }

    var bleDev = that.globalData.foundBleDevs[options.devName]
    console.log('bleDev', bleDev)
    if(bleDev == undefined){
      throw new RequestError('dev not found', options.devName);
    }

    wx.showLoading({
      mask: true,
      title: '连接中...',
    })
    wx.createBLEConnection({
      deviceId: bleDev.deviceId,
      timeout: 8000,
      success: function(res) {
        console.log('createBLEConnection success', res)
        wx.getBLEDeviceServices({
          deviceId: bleDev.deviceId,
          success: function(res) {
            wx.getBLEDeviceCharacteristics({
              deviceId: bleDev.deviceId,
              serviceId: config.uuid.serviceUuid.toUpperCase(),
              success: function(res) {
                wx.notifyBLECharacteristicValueChange({
                  deviceId: bleDev.deviceId,
                  serviceId: config.uuid.serviceUuid.toUpperCase(),
                  characteristicId: config.uuid.notifyUuid.toUpperCase(),
                  state: true,
                  success: function(res) {
                    callSuccess()
                  },
                  fail: function(res) {
                    callFail(res)
                  }
                })
              },
              fail: function(res) {
                callFail(res)
              }
            })
          },
          fail: function(res) {
            callFail(res)
          }
        })
      },
      fail: function(res) {
        console.log('createBLEConnection fail', res)
        wx.hideLoading()
        if (res.errMsg.indexOf('already connect') > 0) {
          callSuccess()
        } else {
          callFail(res)
        }
      }
    })
  },
  globalData: {
    userInfo: null,
    token:'',
    baseurl:'https://schoolsafety.zhiweisz.cn/',
    emitter:emitter,//全局订阅函数
    ble: "", //全局蓝牙实例
    blueStatus: false,
    userInfo: null,
    fingerprintId: -1,//指纹ID
    backdata: -1,//返回状态
    openlock:-1,//蓝牙开锁返回状态
    stop29:false,
    zgBlueStatus:false,
    blueDeviceId:'',
    deviceNum:'',
    tenantIdEnter:wx.getStorageSync('tenantId') || '100',
    sysinfo: null,
    foundBleDevs: {},
    isSearch:false,
    isConnected:false,
    isInitReady:false
  }
})
