// pagesA/facepeople/facepeople.js
import moment from '../../utils/moment'

function CurentTime() {
    var now = new Date();
    var year = now.getFullYear(); //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    // if (hh < 10)
    //   clock += "0";
    // clock += '00' + ":";
    // // if (mm < 10) clock += '0';
    clock += '00:00:00';
    return (clock);
}

function CurentTime1() {
    var now = new Date();
    var year = now.getFullYear() + 3; //年
    var month = now.getMonth() + 1; //月
    var day = now.getDate(); //日
    var hh = now.getHours(); //时
    var mm = now.getMinutes(); //分
    var clock = year + "-";
    if (month < 10)
        clock += "0";
    clock += month + "-";
    if (day < 10)
        clock += "0";
    clock += day + " ";
    // if (hh < 10)
    //   clock += "0";
    // clock += hh + ":";
    // if (mm < 10) clock += '0';
    // clock += mm;
    clock += '23:59:59';
    return (clock);
}
const app = getApp()
const WXAPI = require("../../utils/request")
const util = require("../../utils/util")
const plugin = requirePlugin("myPlugin")
var methods = require('../../utils/methods');
var md5 = require('../../utils/md5.js');
var bleall = require('../../utils/bleall');
var util1 = require('../../utils/util1');
const config = require('../../config')
const ADD_NFC_MODE = 10
var date = new Date()
var isConnected = false
var connectedDeviceId = ''
var basecode = 29283991
var lockId = 1
var lockManagerId = 1
var lockMac = ''
var isInitReady = false
var lockModel
var lockDevice
var taskId = 0

var pincode = -1
var pincodeIndex = -1

var rfCardId = -1
var rfCardIndex = -1

var fingerprintIndex = -1
var passwordLiAll = {
    id: ''
}
var faceaddIndex = -1
var isLockLogin = false
var serialNumber = ''
Page({

    /**
     * 页面的初始数据
     */
    data: {
        date: moment().format('YYYY-MM-DD HH:mm:ss'),
        show: false,
        value: '',
        show2: false,
        facename: '',
        minDate: '',
        minDate1: '',
        endtime: '',
        starttime: '',
        datetimerange: [CurentTime(), CurentTime1()],
        chooseface: false,
        avatarPath: "", // 上传的图片数据
        facepic: "", // 上传的图片的base64格式
        isSearch: app.globalData.isSearch,
        cgInfo: {},
        deviceinfo: {},
        personLi: {},
        faceList: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var cgInfo = wx.getStorageSync('cgInfo')
        var deviceinfo = wx.getStorageSync('deviceinfo')
        var personLi = wx.getStorageSync('personLi')
        let minDate = wx.getStorageSync('minDate')
        let minDate1 = wx.getStorageSync('minDate1')
        console.log(cgInfo, deviceinfo, personLi, minDate, minDate1);
        this.setData({
            isSearch: false,
            cgInfo: cgInfo,
            minDate,
            minDate1,
            starttime: minDate,
            endtime: minDate1,
            deviceinfo: deviceinfo,
            personLi: personLi,
        })
        if (this.data.avatarPath) {
            this.setData({
                show2: true
            })
        }
    },
    CurentTime() {
        var now = new Date();
        var year = now.getFullYear(); //年
        var month = now.getMonth() + 1; //月
        var day = now.getDate(); //日
        var hh = now.getHours(); //时
        var mm = now.getMinutes(); //分
        var clock = year + "-";
        if (month < 10)
            clock += "0";
        clock += month + "-";
        if (day < 10)
            clock += "0";
        clock += day + " ";
        // if (hh < 10)
        //   clock += "0";
        // clock += '00' + ":";
        // // if (mm < 10) clock += '0';
        clock += '00:00:00';
        return (clock);
    },
    changeshow2() {
        this.setData({
            show2: true
        })
    },
    onChange2(e) {
        this.setData({
            facename: e.detail
        })
    },
    bindDateChange: function (e) {
        var str = e.detail.value + " 00:00:00"
        this.data.datetimerange[0] = str
        this.setData({
            starttime: str,
        })
    },
    bindDateChange1: function (e) {
        var str = e.detail.value + " 23:59:59"
        this.data.datetimerange[1] = str
        this.setData({
            endtime: str
        })
    },
    onSearch() {

    },
    onCancel() {

    },
    // 新增人脸
    addFace() {

        // wx.chooseImage({
        //   count: 1,
        //   sizeType: ['original', 'compressed'],
        //   success: function (res) {
        //     console.log(res)
        //     wx.getImageInfo({
        //       src: res.tempFilePaths[0],
        //       success(res) {
        //         wx.navigateTo({
        //           url: '/pagesA/selectFace/selectFace?data=' + JSON.stringify(res)
        //         })
        //       }
        //     })
        //   }
        // });

        wx.navigateTo({
            url: '/pagesA/selectFace/selectFace',
        })
    },
    // 弹出框
    changeshow() {
        this.setData({
            show: true
        })
    },
    onClose() {
        this.setData({
            show: false,
            show2: false
        })
    },
    // 跳转详情页
    gotoinfo() {
        wx.navigateTo({
            url: '/pagesA/faceinfo/faceinfo',
        })
    },
    // 增加人脸
    sendface() {
        var time3 = new Date(this.data.datetimerange[0].replace(/-/g, '/'))
        var time4 = new Date(this.data.datetimerange[1].replace(/-/g, '/'))
        var passwordStartTimecontrast = time3.getTime() / 1000
        var passwordEndTimecontrast = time4.getTime() / 1000
        if (passwordStartTimecontrast > passwordEndTimecontrast) {
            wx.showToast({
                title: '开始时间不能大于结束时间',
                duration: 2000,
                mask: true,
                icon: 'none'
            })
            return
        }
        wx.showLoading({
            title: '正在添加人脸',
            mask: true
        })
        var _this = this
        var deviceinfo = this.data.deviceinfo
        var info = JSON.parse(this.data.personLi.info)
        if (deviceinfo.manufactureId == 1241) {
            var time1 = new Date(_this.data.datetimerange[0].replace(/-/g, '/'))
            var time2 = new Date(_this.data.datetimerange[1].replace(/-/g, '/'))
            var passwordStartTime = time1.getTime() / 1000
            var passwordEndTime = time2.getTime() / 1000
            // let facepicture = wx.getFileSystemManager().readFileSync(_this.data.avatarPath, "base64")
            // facepic = `data:image/jpg;base64, ${facepicture}`
            var dataface = {
                code: "lwj/faceOperate",
                data: {
                    action: 1,
                    endTime: passwordEndTime,
                    faceData: _this.data.facepic,
                    lockerId: deviceinfo.deviceNum,
                    lockerUserId: info.userPassword,
                    startTime: passwordStartTime,
                }
            }
            console.log(_this.data.avatarPath, dataface);
            WXAPI.sendCommand(dataface).then(res => {
                console.log(res);
                if (res.success) {
                    faceaddIndex = res.data.index
                    serialNumber = res.data.serialNumber
                    this.setData({
                        show2: false
                    })
                    wx.showToast({
                      title: '添加人脸凭证成功',
                      icon: 'none',
                      duration: 2000
                    })
                }else{
                    wx.showToast({
                      title: res.msg,
                      icon: 'none',
                      duration: 2000
                    })
                }
            })
        }
    },
    sendBytes(bytes) {
        setTimeout(() => {
            wx.writeBLECharacteristicValue({
                deviceId: lockDevice.deviceId,
                serviceId: config.uuid.serviceUuid.toUpperCase(),
                characteristicId: config.uuid.writeUuid.toUpperCase(),
                value: bytes,
                success: function (res) {

                },
            })
        }, 50)
    },
    searchDevicesMethods() {
        var that = this;
        wx.showLoading({
            title: '正在搜索',
            // mask: true
        })
        this.setData({
            searchClick: false
        })
        wx.openBluetoothAdapter({
            success: function (res) {
                wx.startBluetoothDevicesDiscovery({
                    success: function (res) {
                        wx.getBluetoothDevices({
                            success: function (res) {
                                res.devices.map(it => {
                                    var status = it.name.indexOf('WSL_')
                                    if (status != -1) {
                                        if (it.RSSI != 127) {
                                            if (it.advertisData != null) {
                                                it.adData = util1.ab2hex(it.advertisData)
                                                if (it.adData.length > 10) {
                                                    var macStr = it.adData.substring(4, 16).toUpperCase()
                                                    //console.log('macStr', macStr)
                                                    it.mac = macStr.substr(10, 2) + ':' + macStr.substr(8, 2) + ':' + macStr.substr(6, 2) + ':' + macStr.substr(4, 2) + ':' + macStr.substr(2, 2) + ':' + macStr.substr(0, 2)
                                                    if (it.adData.substring(1, 2) == '1') {
                                                        it.isLightOn = true
                                                        it.textColor = 'green'
                                                    } else {
                                                        it.isLightOn = false
                                                        it.textColor = 'black'
                                                    }
                                                    if (it.adData.substring(3, 4) == '1') {
                                                        it.textColor = 'pink'
                                                        it.isBind = true
                                                    } else {
                                                        it.isBind = false
                                                    }
                                                }
                                            } else {
                                                it.textColor = 'black'
                                            }
                                            lockModel = util1.getLockModel(it.name)
                                            it.lockType = util1.getLockType(lockModel)
                                            if (it.name == that.data.deviceinfo.deviceNum) {
                                                app.addDeviceWithDevName(it.name, it)
                                                lockDevice = it
                                                connectedDeviceId = it.deviceId
                                                that.setData({
                                                    isSearch: true
                                                })
                                                that.initBluetooth()
                                            }
                                        }
                                    }
                                })
                                if (!that.data.isSearch) {
                                    that.searchDevicesMethods()
                                }
                            }
                        })
                    },
                    fail: function (res) {
                        wx.hideLoading({
                            success: (res) => {
                                wx.showToast({
                                    title: res.errMsg,
                                    duration: 2000,
                                    icon: 'none'
                                })
                            },
                        })
                    }
                })
            },
            fail: function (res) {
                console.log('请打开蓝牙和定位功能')
                wx.hideLoading({
                    success: (res) => {
                        wx.showToast({
                            title: '请打开蓝牙和定位功能',
                            duration: 2000,
                            icon: 'none'
                        })
                    },
                })
            }
        })
    },
    initBluetooth: function () {
        var that = this
        wx.getConnectedBluetoothDevices({
            services: [config.uuid.serviceUuid],
            success: function (res) {
                res.devices.map(function (it) {
                    if (it.deviceId == connectedDeviceId || it.name == that.data.deviceinfo.deviceNum) {
                        isConnected = true
                    }
                })
                that.setData({
                    isConnected: isConnected
                })
                console.log(isInitReady, 'isConnected', isConnected)
                if (isConnected) {
                    console.log("2144");
                    if (isInitReady) {
                        console.log("2146");
                        that.doWork()
                    } else {
                        that.setupConnection()
                    }
                } else {
                    that.connectTo()
                }
            },
        })
    },
    connectTo: function () {
        var that = this
        wx.showLoading({
            title: '连接中',
        })
        wx.createBLEConnection({
            deviceId: lockDevice.deviceId,
            timeout: config.ble.connectTimeOut,
            success: function (res) {
                console.log('connectTo', res)
                isConnected = true
                // app.globalData.isConnected = true
                wx.hideLoading()
                setTimeout(function () {
                    that.setupConnection()
                }, 500)
            },
            fail: function (e) {
                console.debug('connectTo', e)
                wx.hideLoading()
                switch (e.errCode) {
                    case 10003: {
                        wx.showModal({
                            title: '连接失败',
                            content: '是否重新连接？',
                            success: function (res) {
                                if (res.confirm) {
                                    that.connectTo()
                                }
                            }
                        })
                        break
                    }
                    case 10012: {
                        wx.showModal({
                            title: '连接失败',
                            content: '蓝牙连接超时',
                            showCancel: false
                        })
                        break
                    }
                    case 10002: {
                        wx.showModal({
                            title: '连接失败',
                            content: '没有找到指定设备',
                            showCancel: false
                        })
                        break
                    }
                }
            }
        })
    },
    setupConnection: function () {
        var that = this
        wx.showLoading({
            title: '初始化连接中',
        })
        wx.getBLEDeviceServices({
            deviceId: lockDevice.deviceId,
            success: function (res) {
                console.log('Services', res)
                wx.getBLEDeviceCharacteristics({
                    deviceId: lockDevice.deviceId,
                    serviceId: config.uuid.serviceUuid.toUpperCase(),
                    success: function (res) {
                        console.log('Characteristics', res)
                        wx.showToast({
                            title: '连接成功',
                            duration: 1000,
                            icon: 'none'
                        })
                        wx.onBLECharacteristicValueChange(function (res) {
                            console.log(res, 'reslllllll')
                            var bytes = new Uint8Array(res.value)
                            console.log('bytes', bytes)
                            var data = plugin.parseBytes(lockDevice.name, basecode, bytes)
                            console.log('data', data)
                            switch (data.cmd) {
                                case 'reportLockBattery': {
                                    if (data.data.battery < 10) {
                                        wx.showModal({
                                            title: '电量报警',
                                            content: `门锁当前电量${data.data.battery}%！\n电量严重不足，请立即更换电池！`,
                                            showCancel: false
                                        })
                                    } else if (data.data.battery < 30) {
                                        wx.showModal({
                                            title: '电量预警',
                                            content: `门锁当前电量${data.data.battery}%！\n请及时更换电池！`,
                                            showCancel: false
                                        })
                                    }
                                    break
                                }
                                case 'reportRfCardResult': {
                                    if (taskId == 61) {
                                        wx.showModal({
                                            title: '检测到新卡',
                                            content: `是否添加此房卡，卡号：${data.data.cardId}？`,
                                            success: function (res) {
                                                if (res.confirm) {
                                                    console.log(data.data, 'rfCardIdrfCardId')
                                                    // rfCardId = randomMethods()//data.data.cardId
                                                    that.onAddRfCard()
                                                }
                                            }
                                        })
                                    } else {
                                        if (lockModel > 70) {
                                            if (data.data.isValid) {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: `房卡开锁成功，序号：${data.data.index}！`,
                                                    showCancel: false
                                                })
                                            } else {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: `多次刷房卡开锁失败！`,
                                                    showCancel: false
                                                })
                                            }
                                        } else {
                                            if (data.data.isValid) {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: `房卡开锁成功，卡号：${data.data.cardId}！`,
                                                    showCancel: false
                                                })
                                            } else {
                                                wx.showModal({
                                                    title: '提示',
                                                    content: `房卡未授权，卡号：${data.data.cardId}！`,
                                                    showCancel: false
                                                })
                                            }
                                        }
                                    }
                                    break
                                }
                                case 'reportPincodeResult': {
                                    if (lockModel > 70) {
                                        if (data.data.isValid) {
                                            wx.showModal({
                                                title: '提示',
                                                content: `密码开锁成功，序号：${data.data.index}！`,
                                                showCancel: false
                                            })
                                        } else {
                                            wx.showModal({
                                                title: '提示',
                                                content: `多次密码开锁失败！`,
                                                showCancel: false
                                            })
                                        }
                                    } else {
                                        if (data.data.isValid) {
                                            wx.showModal({
                                                title: '提示',
                                                content: `密码：${data.data.pincode}开锁成功！`,
                                                showCancel: false
                                            })
                                        } else {
                                            wx.showModal({
                                                title: '提示',
                                                content: `密码：${data.data.pincode}未授权！`,
                                                showCancel: false
                                            })
                                        }
                                    }
                                    break
                                }
                                case 'reportFingerprintResult': {
                                    if (data.data.isValid) {
                                        wx.showModal({
                                            title: '提示',
                                            content: `指纹开锁成功，序号：${data.data.index}！`,
                                            showCancel: false
                                        })
                                    } else {
                                        wx.showModal({
                                            title: '提示',
                                            content: `多次指纹开锁失败！`,
                                            showCancel: false
                                        })
                                    }
                                    break
                                }
                                case 'queryLockState': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '查询失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    that.setData({
                                        lock: {
                                            mac: data.data.mac,
                                            lockType: util1.getLockType(lockModel),
                                        },
                                        isBindLock: data.data.isBind
                                    })
                                    lockMac = data.data.mac

                                    if (taskId > 0) {
                                        if (data.data.isBind) {
                                            // wx.showModal({
                                            //   title: data.data.mac,
                                            //   content: '此设备已经硬件绑定！',
                                            //   showCancel: false,
                                            //   success: function (res) {}
                                            // })
                                        } else {
                                            wx.showModal({
                                                title: data.data.mac,
                                                content: '此设备硬件未绑定！',
                                                showCancel: false,
                                                success: function (res) {}
                                            })
                                        }
                                    }
                                    taskId = 0
                                    break
                                }
                                case 'queryLockBattery': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '查询失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: `此门锁电量为${data.data.battery}%`,
                                        showCancel: false,
                                        success: function (res) {}
                                    })
                                    break
                                }
                                case 'queryNbImei': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '查询失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: `此NB设备IMEI为${data.data.imei}`,
                                        showCancel: false,
                                        success: function (res) {}
                                    })
                                    break
                                }
                                case 'setNbFun': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '设置Nb功能失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: that.data.isNbEnable ? 'NB功能已禁用' : 'NB功能已打开',
                                        showCancel: false,
                                    })
                                    that.setData({
                                        isNbEnable: !that.data.isNbEnable
                                    })
                                    break
                                }
                                case 'sendBindLock': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '绑定失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    that.setData({
                                        isBindLock: data.data.isBind
                                    })
                                    if (data.data.isBind) {
                                        wx.showToast({
                                            title: '绑定成功！',
                                        })
                                    } else {
                                        wx.showToast({
                                            title: '绑定失败！',
                                        })
                                    }
                                    break
                                }

                                case 'sendUnbindLock': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '解绑失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    that.setData({
                                        isBindLock: data.data.isBind
                                    })
                                    if (data.data.isBind) {
                                        wx.showToast({
                                            title: '解绑失败！',
                                        })
                                    } else {
                                        wx.showToast({
                                            title: '解绑成功！',
                                        })
                                    }
                                    break
                                }
                                case 'login1':
                                case 'sendOpenLockP1': {
                                    if (data.code != 200) {
                                        wx.hideLoading()
                                        if (taskId == 41) {
                                            wx.showModal({
                                                title: '提示',
                                                content: that.data.isJack ? '上电失败！' : '解锁失败！',
                                                showCancel: false,
                                                success: function (res) {}
                                            })
                                        } else if (taskId == 32) {
                                            wx.showModal({
                                                title: '提示',
                                                content: '登录失败！',
                                                showCancel: false,
                                                success: function (res) {}
                                            })
                                        }

                                        break
                                    }
                                    if (taskId == 41) {
                                        var bytes = plugin.sendOpenLockP2(lockDevice.name, basecode, data.data.randomN)
                                        console.debug('bytes', bytes)
                                        that.sendBytes(bytes)
                                    } else if (taskId == 32) {
                                        var bytes = plugin.login2(lockDevice.name, basecode, data.data.randomN)
                                        console.debug('bytes', bytes)
                                        that.sendBytes(bytes)
                                    }
                                    break;
                                }
                                case 'login':
                                case 'sendOpenLockP2': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        if (taskId == 41) {
                                            wx.showModal({
                                                title: '提示',
                                                content: that.data.isJack ? '上电失败！' : '解锁失败！',
                                                showCancel: false,
                                                success: function (res) {}
                                            })
                                        } else if (taskId == 32) {
                                            wx.showModal({
                                                title: '提示',
                                                content: '登录失败！',
                                                showCancel: false,
                                                success: function (res) {}
                                            })
                                        }
                                        break
                                    }

                                    isLockLogin = true
                                    if (taskId == 41) {
                                        // var data = {
                                        //   code: "zg/bleUnlockRecord",
                                        //   data: {
                                        //     lockerId: that.data.deviceinfo.deviceNum,
                                        //     roomId:that.data.deviceinfo.roomId,
                                        //     roomName:that.data.deviceinfo.roomName,
                                        //     cardName:that.data.userInfo.username
                                        //   }
                                        // }
                                        var data = {
                                            code: "ble/bleUnlockRecord",
                                            data: {
                                                deviceNum: that.data.deviceinfo.deviceNum,
                                                roomId: that.data.deviceinfo.roomId,
                                                roomName: that.data.deviceinfo.roomName,
                                                cardName: that.data.userInfo.username,
                                                productId: that.data.deviceinfo.manufactureId,
                                                userId: '29283991'
                                            }
                                        }
                                        WXAPI.sendCommand(data).then(res => {
                                            console.log(res)
                                        })
                                        wx.showToast({
                                            title: that.data.isJack ? '上电成功！' : '解锁成功！',
                                        })
                                    } else if (taskId == 32) {
                                        wx.showToast({
                                            title: '登录成功！',
                                        })
                                    }
                                    taskId = 0
                                    break;
                                }

                                case 'syncClock': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '同步时间失败！' + data.data.msg,
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: '时间更新成功！',
                                        showCancel: false
                                    })
                                    break;
                                }
                                case 'addPincode': {
                                    // console.log(data.data,'data.data')
                                    // wx.hideLoading()
                                    let data2 = {
                                        "code": "ble/bleSendVoucherReply",
                                        "data": {
                                            "deviceNum": that.data.deviceinfo.deviceNum,
                                            "serialNumber": serialNumber,
                                            "index": pincodeIndex,
                                            "type": 7,
                                            "result": 1,
                                            "productId": that.data.deviceinfo.manufactureId
                                        }
                                    }
                                    if (data.code != 200) {
                                        data2 = {
                                            "code": "ble/bleSendVoucherReply",
                                            "data": {
                                                "deviceNum": that.data.deviceinfo.deviceNum,
                                                "serialNumber": serialNumber,
                                                "index": pincodeIndex,
                                                "type": 7,
                                                "result": 0,
                                                "productId": that.data.deviceinfo.manufactureId
                                            }
                                        }
                                        WXAPI.sendCommand(data2).then(res => {

                                        })
                                        wx.showModal({
                                            title: '提示',
                                            content: '添加密码失败！' + data.data.msg,
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
                                    var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
                                    var passwordStartTime = time1.getTime() / 1000
                                    var passwordEndTime = time2.getTime() / 1000
                                    var pzname = '',
                                        cardName = '';
                                    pzname = '蓝牙-密码' + (that.data.passwordList.length + 1)
                                    cardName = that.data.personLi.name + '-蓝牙-密码' + (that.data.passwordList.length + 1)
                                    var str = {
                                        // cardId: this.personInfo.cardId,
                                        imei: that.data.deviceinfo.imei,
                                        pzname: pzname,
                                        password: that.data.password.toString(),
                                        userTelephone: JSON.parse(that.data.personLi.info).userTelephone,
                                        operateMode: 7,
                                        userPassword: JSON.parse(that.data.personLi.info).userPassword,
                                        passwordStartTime: passwordStartTime,
                                        passwordEndTime: passwordEndTime,
                                        index: pincodeIndex,
                                        is: false,
                                        pass: true
                                    }
                                    var data1 = {
                                        cardId: that.data.personLi.cardId,
                                        content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                                        deviceNum: that.data.deviceinfo.deviceNum,
                                        type: 4,
                                        imei: that.data.deviceinfo.imei,
                                        serial: serialNumber,
                                        startTime: passwordStartTime,
                                        endTime: passwordEndTime,
                                    };
                                    var datalist = {
                                        cardId: that.data.personLi.cardId,
                                        content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                                        type: 14,
                                        startTime: passwordStartTime,
                                        endTime: passwordEndTime,
                                    };
                                    WXAPI.addCertificates(datalist).then(res6 => {
                                        console.log(datalist, '密码22', res6)
                                    })
                                    WXAPI.addCertificates(data1).then(res3 => {
                                        if (res3.success) {
                                            var updatedata = {
                                                id: res3.data,
                                                status: 1
                                            };
                                            WXAPI.updateCertificates(updatedata).then((res2) => {});
                                            WXAPI.sendCommand(data2).then(res => {

                                            })
                                            that.getPassword()
                                            that.setData({
                                                show: false
                                            })
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: '添加成功',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        } else {
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: '添加失败',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    })
                                    taskId = 0
                                    that.setData({
                                        isPincodeAdd: true,
                                        show: false
                                    })
                                    wx.showModal({
                                        title: '提示',
                                        content: `添加密码${pincode}成功！`,
                                        showCancel: false
                                    })
                                    break
                                }

                                case 'delPincode': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        var datacom = {
                                            code: "lwj/passwordOperate",
                                            data: {
                                                lockerId: that.data.deviceinfo.deviceNum,
                                                serialNumber: serialNumber,
                                                index: pincodeIndex,
                                                action: 2,
                                                type: 9,
                                                result: 0
                                            }
                                        }
                                        WXAPI.sendCommand(datacom).then(res2 => {
                                            console.log(res2, '失败')
                                        })

                                        wx.showModal({
                                            title: '提示',
                                            content: '删除密码失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: `删除密码成功！`,
                                        showCancel: false,
                                    })
                                    var datacom = {
                                        code: "lwj/passwordOperate",
                                        data: {
                                            lockerId: that.data.deviceinfo.deviceNum,
                                            serialNumber: serialNumber,
                                            index: pincodeIndex,
                                            action: 2,
                                            type: 9,
                                            result: 1
                                        }
                                    }
                                    WXAPI.sendCommand(datacom).then(res2 => {
                                        if (res2.success) {}
                                    })
                                    var data = {
                                        ids: [passwordLiAll.id]
                                    }
                                    WXAPI.deleteCertificates(data).then(res1 => {
                                        if (res1.success) {
                                            that.getPassword()
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: '删除成功',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        } else {
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: '删除失败',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    })
                                    that.setData({
                                        isPincodeAdd: false
                                    })
                                    pincode = -1
                                    pincodeIndex = -1
                                    break
                                }

                                case 'addRfCard': {
                                    wx.hideLoading()
                                    if (data.code == 100) {
                                        wx.showLoading({
                                            title: data.data.msg,
                                        })
                                        break
                                    } else if (data.code != 200) {
                                        var datacom = {
                                            code: "ble/bleSendVoucherReply",
                                            data: {
                                                deviceNum: that.data.deviceinfo.deviceNum,
                                                serialNumber: serialNumber,
                                                index: rfCardIndex,
                                                type: ADD_NFC_MODE,
                                                cardNo: '',
                                                result: 0,
                                                productId: that.data.deviceinfo.manufactureId
                                            }
                                        }
                                        WXAPI.sendCommand(datacom).then(res2 => {})
                                        wx.showModal({
                                            title: '提示',
                                            content: '添加房卡失败！' + data.data.msg,
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    that.setData({
                                        isRfCardAdd: true
                                    })

                                    if (lockModel > 70) {
                                        console.log(data.data, 'rfCardIndexrfCardIndex')
                                        // rfCardId = randomMethods()
                                        wx.showModal({
                                            title: '提示',
                                            content: `添加房卡成功，序号${rfCardIndex}！`,
                                            showCancel: false
                                        })
                                        that.addRfcardCertificates()
                                    } else {
                                        console.log(data.data, 'rfCardIndexrfCardIndex1')
                                        // rfCardId = randomMethods()
                                        wx.showModal({
                                            title: '提示',
                                            content: `添加房卡成功，卡号${rfCardId}！`,
                                            showCancel: false
                                        })
                                        that.addRfcardCertificates()
                                    }
                                    break
                                }

                                case 'delRfCard': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        var datacom = {
                                            code: "lwj/c",
                                            data: {
                                                lockerId: that.data.deviceinfo.deviceNum,
                                                serialNumber: serialNumber,
                                                index: rfCardIndex,
                                                action: 2,
                                                type: 12,
                                                result: 0
                                            }
                                        }
                                        WXAPI.sendCommand(datacom).then(res2 => {
                                            console.log(res2, '失败')
                                        })
                                        wx.showModal({
                                            title: '提示',
                                            content: '删除房卡失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    that.setData({
                                        isRfCardAdd: false
                                    })
                                    if (lockModel > 70) {
                                        wx.showModal({
                                            title: '提示',
                                            content: `删除房卡成功，序号${rfCardIndex}！`,
                                            showCancel: false,
                                        })
                                    } else {
                                        wx.showModal({
                                            title: '提示',
                                            content: `删除房卡成功，卡号${rfCardId}！`,
                                            showCancel: false,
                                        })
                                    }
                                    var datacom = {
                                        code: "lwj/c",
                                        data: {
                                            lockerId: that.data.deviceinfo.deviceNum,
                                            serialNumber: serialNumber,
                                            index: rfCardIndex,
                                            action: 2,
                                            type: 12,
                                            result: 1
                                        }
                                    }
                                    WXAPI.sendCommand(datacom).then(res2 => {
                                        console.log(res2, '失败')
                                    })
                                    var data = {
                                        ids: [passwordLiAll.id]
                                    }
                                    WXAPI.deleteCertificates(data).then(res1 => {
                                        console.log(res1, '2936');
                                        if (res1.success) {
                                            that.getNfc()
                                            wx.showToast({
                                                title: '删除成功',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        } else {
                                            wx.showToast({
                                                title: '删除失败',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    })
                                    rfCardId = -1
                                    rfCardIndex = -1
                                    break
                                }

                                case 'addFingerprint': {
                                    wx.hideLoading()
                                    if (data.code == 100) {
                                        wx.showLoading({
                                            title: data.data.msg,
                                        })
                                        break
                                    } else if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '添加指纹失败！' + data.data.msg,
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        var datacom = {
                                            code: "ble/bleSendVoucherReply",
                                            data: {
                                                deviceNum: that.data.deviceinfo.deviceNum,
                                                serialNumber: serialNumber,
                                                index: 0,
                                                type: 16,
                                                result: 0,
                                                productId: that.data.deviceinfo.manufactureId
                                            }
                                        }
                                        WXAPI.sendCommand(datacom).then(res2 => {
                                            if (res2.success) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    that.setData({
                                        isFingerprintAdd: true
                                    })
                                    wx.showModal({
                                        title: '提示',
                                        content: `添加指纹成功，序号${fingerprintIndex}！`,
                                        showCancel: false
                                    })

                                    var time1 = new Date(that.data.starttime.replace(/-/g, '/'))
                                    var time2 = new Date(that.data.endtime.replace(/-/g, '/'))
                                    var passwordStartTime = time1.getTime() / 1000
                                    var passwordEndTime = time2.getTime() / 1000
                                    var cardName = '',
                                        pzname = ''
                                    if (that.data.pzname) {
                                        cardName = that.data.personLi.name + '-蓝牙-' + that.data.pzname
                                        pzname = '蓝牙-' + that.data.pzname
                                    } else {
                                        cardName = that.data.personLi.name + '-蓝牙-指纹' + (that.data.FpList.length + 1)
                                        pzname = '蓝牙-指纹' + (that.data.FpList.length + 1)
                                    }

                                    var str = {
                                        // cardId: this.personInfo.cardId,
                                        imei: that.data.deviceinfo.imei,
                                        pzname: pzname,
                                        password: '',
                                        fingerprintAlias: that.data.radioDetil,
                                        userTelephone: JSON.parse(that.data.personLi.info).userTelephone,
                                        operateMode: 16,
                                        userPassword: JSON.parse(that.data.personLi.info).userPassword,
                                        passwordStartTime: passwordStartTime,
                                        passwordEndTime: passwordEndTime,
                                        index: fingerprintIndex,
                                        is: false,
                                        pass: true
                                    }
                                    var data2 = {
                                        cardId: that.data.personLi.cardId,
                                        content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                                        deviceNum: that.data.deviceinfo.deviceNum,
                                        type: 1,
                                        imei: that.data.deviceinfo.imei,
                                        serial: serialNumber,
                                        startTime: passwordStartTime,
                                        endTime: passwordEndTime,
                                        status: 1
                                    };
                                    var datalist = {
                                        cardId: that.data.personLi.cardId,
                                        content: JSON.stringify(str), //operateMode:NFC-10、把人员添加到凭证-1
                                        type: 11,
                                        startTime: passwordStartTime,
                                        endTime: passwordEndTime
                                    };
                                    var datacom = {
                                        code: "ble/bleSendVoucherReply",
                                        data: {
                                            deviceNum: that.data.deviceinfo.deviceNum,
                                            serialNumber: serialNumber,
                                            index: fingerprintIndex,
                                            type: 16,
                                            result: 1,
                                            productId: that.data.deviceinfo.manufactureId
                                        }
                                    }
                                    WXAPI.addCertificates(datalist).then(res6 => {})
                                    console.log(data, '添加凭证')
                                    WXAPI.addCertificates(data2).then(res3 => {
                                        if (res3.success) {
                                            var updatedata = {
                                                id: res3.data,
                                                status: 1
                                            };
                                            WXAPI.updateCertificates(updatedata).then((res2) => {});
                                            WXAPI.sendCommand(datacom).then(res2 => {
                                                if (res2.success) {}
                                            })
                                            console.log(res3, '添加凭证成功')
                                            that.getFp()
                                            that.setData({
                                                show: false
                                            })
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: '添加成功',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        } else {
                                            wx.hideLoading()
                                            wx.showToast({
                                                title: '添加失败',
                                                mask: true,
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    })
                                    break
                                }

                                case 'delFingerprint': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '删除指纹失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: `删除指纹成功，序号${fingerprintIndex}！`,
                                        showCancel: false,
                                    })
                                    that.setData({
                                        isFingerprintAdd: false
                                    })
                                    fingerprintIndex = -1
                                    break
                                }

                                case 'changeAdminPincode': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '修改管理密码失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showToast({
                                        title: '修改管理密码成功！',
                                    })
                                }

                                case 'queryLockSlotState': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '查询失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: data.data.state == 0 ? '此门锁方舌关闭' : '此门锁方舌打开',
                                        showCancel: false,
                                        success: function (res) {}
                                    })
                                    break
                                }

                                case 'queryLockUnlockState': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '查询失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: data.data.state == 0 ? '此门锁已关闭' : '此门锁已打开',
                                        showCancel: false,
                                        success: function (res) {}
                                    })
                                    break
                                }

                                case 'setLockUnlockState': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '设置常开指令失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: data.data.state == 0 ? '常开模式已退出' : '常开模式已开启',
                                        showCancel: false,
                                    })
                                    that.setData({
                                        isUnloked: data.data.state == 1
                                    })
                                    break
                                }

                                case 'setLockMuteState': {
                                    wx.hideLoading()
                                    if (data.code != 200) {
                                        wx.showModal({
                                            title: '提示',
                                            content: '设置静音指令失败！',
                                            showCancel: false,
                                            success: function (res) {}
                                        })
                                        break
                                    }
                                    taskId = 0
                                    wx.showModal({
                                        title: '提示',
                                        content: data.data.state == 1 ? '静音模式已退出' : '静音模式已开启',
                                        showCancel: false,
                                    })
                                    that.setData({
                                        isMuted: data.data.state == 0
                                    })
                                    break
                                }
                            }
                        })

                        wx.notifyBLECharacteristicValueChange({
                            deviceId: lockDevice.deviceId,
                            serviceId: config.uuid.serviceUuid.toUpperCase(),
                            characteristicId: config.uuid.notifyUuid.toUpperCase(),
                            state: true,
                            success: function (res) {
                                console.log('setupNotify', res)
                                isInitReady = true
                                setTimeout(function () {
                                    wx.hideLoading()
                                    // that.onQueryBindState()
                                    that.login()
                                }, 500)
                            },
                        })
                    },
                })
            },
        })
    },
    doWork: function () {
        var that = this
        console.log(taskId);
        switch (taskId) {
            case 11: {
                that.onBindLock()
                break
            }
            case 12: {
                that.onUnbindLock()
                break
            }
            case 21: {
                that.onQueryBindState()
                break
            }
            case 22: {
                that.onQueryBattery()
                break
            }

            case 31: {
                that.onQueryNbImei()
                break
            }
            case 32: {
                that.onLogin()
                break
            }
            case 41: {
                that.LwjonOpenLock()
                break
            }
            case 42: {
                that.onSyncClock()
                break
            }
            case 51: {
                that.onAddPincode()
                break
            }
            case 52: {
                that.onDelPincode()
                break
            }
            case 61: {
                // that.onAddRfCard()
                // if (lockModel > 70) {
                that.sendAddRfcard()
                // } else {
                //   wx.showModal({
                //     title: '提示',
                //     content: '请刷卡！',
                //     showCancel: false
                //   })
                // }
                break
            }
            case 62: {
                that.onDelRfCard()
                break
            }
            case 71: {
                that.onAddFingerprint()
                break
            }
            case 72: {
                that.onDelFingerprint()
                break
            }
            case 81: {
                that.onChangeAdminPincode()
                break
            }

            case 91: {
                that.onQueryLockSlotState()
                break
            }

            case 92: {
                that.onQueryLockUnlockState()
                break
            }

            case 101: {
                that.onChangeLockUnlockState()
                break
            }

            case 102: {
                that.onChangeLockMutedState()
                break
            }
            case 111: {
                this.onChangeLockNbState()
            }
            default: {

            }
        }
    },
    login: function () {
        var that = this
        taskId = 32
        that.initBluetooth()
    },
    onLogin: function () {
        var that = this
        wx.showLoading({
            title: '登录中',
        })

        var bytes = plugin.login1(lockDevice.name, basecode)
        console.debug('bytes', bytes)
        that.sendBytes(bytes)
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})