import ICINLocker from "./ICINPakage/ICINLocker"
const WXAPI = require('./request')
import moment from "./moment"
var bleall = require('./bleall');
import {
  BLE
} from "./btls/ble";

const app = getApp();
const emitter = app.globalData.emitter
// 锁端连接蓝牙
function bluetoothConnectivity(deviceNum,manufactureId){
    var that=this
    return new Promise((resolve, reject)=>{
        if(manufactureId==201||manufactureId==221){
            let data={
                status:'',
                msg:''
            }
            wx.showLoading({
              title: '连接蓝牙中',
              mask: true
            })        
            ICINLocker.scanDevices(deviceNum)
            .then((res) => {
                if (res.status === 0) {
                    app.globalData.blueDeviceId = res.deviceId
                    ICINLocker.connect(res.deviceId,false) // 此处 deviceId 存起来，当断开连接时使用
                    .then((res1) => {
                        if (res1.status === 0) {
                            data.status='00'
                            data.msg='连接成功'
                            wx.hideLoading()
                            wx.showToast({
                              title: '连接成功',
                              icon: "none",
                              duration: 2000
                            })
                            app.globalData.zgBlueStatus = true   
                            resolve(data)  
                        }else{
                            data.status='01'
                            data.msg='连接失败'
                            wx.hideLoading()
                            var msg = ''
                            switch (res.errCode) {
                              case 10001:
                                msg = '调用失败，请打开蓝牙！';
                                break;
                            }
                            wx.showToast({
                              title: msg,
                              duration: 2000,
                              icon: 'none'
                            })
                            reject(data)
                        }
                    })
                }else{
                    data.status='01'
                    data.msg='搜索失败'
                    wx.hideLoading()
                    wx.showToast({
                      title: '搜索失败',
                      duration: 2000,
                      icon: 'none'
                    })
                    reject(data)
                }
            }).catch((res) => {
                if (res.status == 1) {
                  if (res.statusReason.errCode == 10001) {
                    data.status='01'
                    data.msg='请检查手机蓝牙和定位功能是否打开？'
                    wx.hideLoading()
                    wx.showToast({
                      title: '请检查手机蓝牙和定位功能是否打开？',
                      duration: 2000,
                      icon: 'none'
                    })                
                    reject(data)
                  }else if(res.statusReason.errCode == 1000){
                    data.status='01'
                    data.msg='未找到该设备'
                    wx.hideLoading()
                    wx.showToast({
                      title: '未找到该设备',
                      duration: 2000,
                      icon: 'none'
                    })                
                    reject(data)
                  }else {
                    if (!app.globalData.zgBlueStatus && app.globalData.blueStatus) {
                      that.bluetoothConnectivity()
                    } else {
                        data.status='01'
                        data.msg=res.statusReason
                        wx.hideLoading()
                        wx.showToast({
                            title: res.statusReason,
                            duration: 2000,
                            icon: 'none'
                        })                
                        reject(data)
                    }
                  }
                }else{
                    data.status='01'
                    data.msg='连接失败'
                    wx.hideLoading()                    
                    reject(data)
                }
            })
        }else if(manufactureId==101){            
            let data={
                status:'',
                msg:''
            }
            wx.showLoading({
              title: '连接蓝牙中',
              mask: true
            })        
            const ble = new BLE(deviceNum, emitter)
            app.globalData.ble = ble
            app.globalData.ble.init()
            if (app.globalData.ble && app.globalData.bleStatus) {
              app.globalData.ble.listen(res => {
                if (res.type == 'connect') {
                  if (res.data == "未打开适配器") {
                    wx.hideLoading()
                    wx.showToast({
                      title: '请检查手机蓝牙和定位功能是否打开？',
                      duration: 2000,
                      icon: 'none'
                    })
                    data.status='01'
                    data.msg='请检查手机蓝牙和定位功能是否打开？'
                    reject(data)
                  } else {
                    if (res.data == '蓝牙已连接') {
                      app.globalData.bleStatus = res.data
                      data.status='00'
                      data.msg='连接成功'
                      resolve(data)
                    }
                  }
                }
              })
            }
        }
    })
}
// ZH，GX1000蓝牙开锁
function bluetoothUnlocking(data,manufactureId){
    wx.showLoading({
      title: '开锁中',
      mask:true,
    })
    if(manufactureId==201||manufactureId==221){
        ICINLocker.getSignKey(data.lockerId, data.superId,data.superId, (callback) => {
            console.log(callback,'管理员获取密钥')
            if (callback.status == '00') {
              var userSignKey = callback.signKey?callback.signKey:callback.commonKey||''
              ICINLocker.getCommonKey(data.lockerId, data.superId, data.superId, userSignKey, (callback1) => {
                if(callback1.status=='00'){
                  var commonKey = callback1.commonKey      
                  ICINLocker.openTheDoor(data.lockerId, data.superId, userSignKey, data.superId, '', '00', commonKey, (callback2) => {
                    if(callback2.status=='00'){
                      var rqTime=moment().format("X")
                      var username=wx.getStorageSync('username'),password=wx.getStorageSync('password')
                      var str=`${username}+${password}+${rqTime}`
                      var signature=md5(str)
                      var data = {
                        code: "zg/bleUnlockRecord",
                        data: {
                          lockerId:data.lockerId,
                          lockerUserId: data.superId,
                          roomId:data.roomId,
                          roomName:data.roomName,
                          cardName:username,
                          signature:signature
                        }
                      }
                      console.log(data,'蓝牙开锁')
                      wx.hideLoading()
                      wx.showToast({
                        title: '开锁成功',
                        duration:2000,
                        icon:'none'
                      })         
                      WXAPI.sendCommand(data).then(res => {
                        console.log(res)
                      })
                    }else{
                      wx.hideLoading()
                      wx.showToast({
                        title: '开锁失败',
                        duration:2000,
                        icon:'none'
                      })                
                    }
                  })
                }else{
                  wx.hideLoading()
                  wx.showToast({
                    title: '连接失败',
                    duration:2000,
                    icon:'none'
                  })
                }
              })
            }else{
              wx.hideLoading()
            }
          });
    }else if(manufactureId==101){
        let userTelephone = "18270949468" //JSON.parse(this.data.deviceinfo.info).userTelephone
        let userPassword = "202108" //JSON.parse(this.data.deviceinfo.info).userPassword
        let pwd = "2021110309" //JSON.parse(this.data.deviceinfo.info).userPassword
        let openLockType = 2
        var userInfo=wx.getStorageSync('userInfo')
        var timestamp = moment().format("x")
        bleall.openLock(userTelephone, userPassword, pwd, openLockType, timestamp, function (res) {
            if (res.success) {
                var rqTime=moment().format("X")
                var username=wx.getStorageSync('username'),password=wx.getStorageSync('password')
                var str=`${username}+${password}+${rqTime}`
                var signature=md5(str)
                var data = {
                code: "ld/bleUnlockRecord",
                data: {
                    deviceNum: data.deviceNum,
                    userTelephone: userTelephone,
                    password: userPassword,
                    roomId:data.roomId,
                    roomName:data.roomName,
                    cardName:userInfo.username,
                    signature:signature
                }
                }
                WXAPI.sendCommand(data).then(res => {

                })
            }
        })
    }
}

//  ZH锁蓝牙操作
/*
1--添加用户
2--删除用户
3--添加密码
4--删除密码
5--添加指纹
6--删除指纹
7--添加卡
8--删除卡
*/
function bluetoothOperation_ZH(data,info,type){
    return new Promise((resolve, reject)=>{
        wx.showLoading({
          title: '下发中',
          mask:true,
        })
        if(type==1){
            ICINLocker.getSignKey(data.lockerId, data.superId, data.superId, (callback) => {
                if(callback.status=='00'){
                    var signKey = callback.signKey
                    ICINLocker.getCommonKey(data.lockerId, data.superId, data.superId, signKey, (callback1) => {
                        if(callback1.status=='00'){
                            var commonKey = callback1.commonKey
                            ICINLocker.addUserToLock(data.lockerId, data.superId, info.usrID, data.superId, '00', signKey, '', commonKey, info.startTime, info.endTime, (callback2) => {
                                if(callback2.status=='00'){
                                    resolve(callback2)
                                }else{
                                    reject(callback2)
                                }
                            })
                        }else{
                            reject(callback1)
                        }
                    })
                }else{
                    reject(callback)
                }
            })
        }else{
            ICINLocker.getUserSignKey(data.lockerId, data.superId, info.userPassword, data.superId, data.authKey, '01', (callback) => {
                if(callback.status=='00'){
                    var userSignKey = callback.userSignKey
                    ICINLocker.getCommonKey(data.lockerId, info.userPassword, info.userPassword, userSignKey, (callback1) => {
                        if(callback1.status=='00'){
                            var commonKey = callback1.commonKey
                             if(type==3){
                               console.log(data,info,commonKey)
                                ICINLocker.handlePwd(data.lockerId, data.superId, info.userPassword, info.password, info.pwdNo, data.superId, data.authKey, '', info.startTime, info.endTime, 255, commonKey, (callback2) => {
                                    if(callback2.status=='00'){
                                        resolve(callback2)
                                    }else{
                                        reject(callback2)
                                    }
                                })
                            }else if(type==5){
                                wx.showLoading({
                                  title: '请在锁上按压手指',
                                  mask:true,
                                })
                                ICINLocker.addFingerPrints(data.lockerId, data.superId, info.userPassword, data.superId, '', data.authKey, info.startTime, info.endTime, '00', commonKey, (callback2) => {
                                    if(callback2.status=='00' && callback2.completeFlag=='01'){
                                        resolve(callback2)
                                    }else if(callback2.status=='ff' && callback2.completeFlag=='00'){
                                      wx.showToast({
                                        title: '录入失败',
                                        icon:'none'
                                      })
                                      reject(callback2)
                                    }
                                })
                            }else if(type==7){
                                wx.showLoading({
                                  title: '请在锁上按键区刷卡',
                                  mask:true,
                                })
                                ICINLocker.RfCardRegister(data.lockerId, data.superId, info.userPassword, data.superId, info.pwdNo, '',data.authKey, info.startTime, info.endTime, commonKey, (callback2) => {
                                    if(callback2.status=='00'){
                                        resolve(callback2)
                                    }else{
                                        reject(callback2)
                                    }
                                })
                            }
                        }else{
                            reject(callback1)
                        }
                    })
                }else{
                    reject(callback)
                }
            })    
        }       
    })
}

module.exports = {
  bluetoothUnlocking,
  bluetoothConnectivity,
  bluetoothOperation_ZH,
}