const app = getApp();

Page({
  data: {
    userInfo: wx.getStorageSync('userInfo'),
    deviceId:0,
    devInfo:{},
    _deviceId:"",
    _mac:"",
    deviceId:"",
    serviceId:"F000AA50-0451-4000-B000-000000000000",
    writeCharacteristic:"F000AA51-0451-4000-B000-000000000000",
    readCharacteristic:"F000AA52-0451-4000-B000-000000000000",
    countCharacteristic:"F000AA53-0451-4000-B000-000000000000",
    mac:"",
    count:"",
    power:"",
    code:"",
    move:"",
    D600:null
  },
  onLoad: function (options) {
    var id = options.id;
    var PageThis = this;
    PageThis.setData({
      userInfo:wx.getStorageSync('userInfo')
    })
    this.setData({
      deviceId: id
    })
    this.getDeviceDetail();
  },
  onUnload(){
    this.closeBluetoothAdapter();
    this.closeBLEConnection();
    var D600 = that.data.D600;
    if(D600 != null){
      D600.closeBluetoothAdapter();
      D600.closeBLEConnection();
    }
  },
  /**获取设备 */
  getDeviceDetail: function () {
    var PageThis = this;
    var id = PageThis.data.deviceId;
    wx.request({
      url: app.globalData.serverInfo.gateWayUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {
        api_name: "device_detail",
        device_id: id,
        login_manager_id: PageThis.data.userInfo.manager_id
      },
      success: function (res) {
        PageThis.setData({
          "devInfo": res.data.data,
          "_mac": res.data.data.dev_mac
        })
        PageThis.openBluetoothAdapter();
      }
    })
  },
  /**
   * 打开格子
   */
  openLat(e){
    var that = this;
    var dev_info = that.data.devInfo;
    var name = e.currentTarget.dataset.name;
    if(Number(dev_info['dev_version']) === 4){
      var D600 = that.data.D600;
      if(D600 != null){
        D600.openLat(name);
      }
    }
  },
  /**
   * 打开所有格子
   */
  openAllLat(){
    var that = this;
    var dev_info = that.data.devInfo;
    if(Number(dev_info['dev_version']) === 4){
      var D600 = that.data.D600;
      if(D600 != null){
        D600.openNoStockLat();
      }
    }
  },
  // 初始化蓝牙适配器
  openBluetoothAdapter() {
    var that = this;
    that.closeBluetoothAdapter();
    that.closeBLEConnection();
    wx.openBluetoothAdapter({
      success: function (res) {
        console.log("初始化蓝牙适配器成功");
        that.startBluetoothDevicesDiscovery();
      },
      fail: function (err) {
        wx.showModal({
          title: '温馨提示',
          content: '请先打开手机蓝牙，然后点击确认连接设备',
          success (res) {
            if (res.confirm) {
              that.openBluetoothAdapter();
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        console.log(err, "初始化蓝牙适配器失败");
      }
    })
  },
  // 开始搜索蓝牙设备
  startBluetoothDevicesDiscovery() {
    var that = this;
    wx.startBluetoothDevicesDiscovery({
      powerLevel:"low",
      success: function (res) {
        console.log("蓝牙搜索中...");
        wx.showLoading({
          title: '设备搜索中',
        })
        var times = 0;
        var timer = setInterval(() => {
          that.getBluetoothDevices();
          times++;
          if(times >= 5){
            wx.hideLoading();
            clearInterval(timer);
            that.stopBluetoothDevicesDiscovery();
            wx.showModal({
              title: "温馨提示",
              content: "请按设备任意按钮激活蓝牙，再点击确定重新连接",
              success (res) {
                if (res.confirm) {
                  that.startBluetoothDevicesDiscovery();
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          }
        },2000);
        that.setData({
          timer:timer
        })
      }
    })
  },
  //获取已发现的蓝牙设备列表
  getBluetoothDevices() {
    var that = this;
    wx.getBluetoothDevices({
      success: function (res) {
        var devInfo = that.data.devInfo;
        res.devices.forEach(item => {
          if(Number(devInfo['dev_version']) === 4 && item.localName == devInfo['dev_no'] && item.advertisServiceUUIDs[0] == "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"){
            var file = require("../../utils/D600.js");
            clearInterval(that.data.timer);
            that.stopBluetoothDevicesDiscovery();
            var D600 = new file(devInfo['dev_no'],item.deviceId);
            D600.createBLEConnection().then(function(ret){
              console.log(ret);
              var isConnect = ret;
              if(isConnect){
                D600.readPower();
                setTimeout(() => {
                  var power = D600.getPower();
                  power = (Number(power)/4)*100;
                  if(power > 100){
                    power = 100;
                  }else{
                    power = power.toFixed(2);
                  }
                  that.reportElectric(power);
                }, 2000);
              }
            });
            that.setData({
              D600:D600
            })
          }else if (item.localName == "OrgboxMini" || item.name == "TI BLE Sensor Tag") {
            var mac = that.buf2hex(item.advertisData);
            mac = mac.toUpperCase();
            var new_mac = "";
            for(var i in mac){
              new_mac += mac[i];
              if(i%2 != 0 && i != 11){
                new_mac += ":";
              }
            }
            if(new_mac == that.data._mac){
              clearInterval(that.data.timer);
              that.stopBluetoothDevicesDiscovery();
              that.createBLEConnection(item.deviceId);
              that.setData({
                deviceId:item.deviceId,
                mac:new_mac
              })
            }
          }
        });
      }
    })
  },
  //停止搜索设备
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("停止搜索设备" + JSON.stringify(res.errMsg))
      }
    })
  },
  //创建蓝牙连接
  createBLEConnection(deviceId) {
    var that = this;
    wx.showLoading({
      title: '设备连接中',
      duration: 99999,
      mask: true
    })
    wx.createBLEConnection({
      deviceId: deviceId,
      success: function (res) {
          wx.getBLEDeviceServices({
            deviceId: deviceId,
            success: function (res) {
              that.getBLEDeviceCharacteristics()
            },
            fail: function (err) {
              console.log(err, "蓝牙连接失败getBLEDeviceServices")
            }
          })
      },
      fail: function (err) {
        console.log(err, "蓝牙连接失败createBLEConnection")
      }
    })
  },
  // 获取该服务的特征值
  getBLEDeviceCharacteristics() {
    var that = this;
    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success: function (res) {
        that.notifyBLECharacteristicValueChange(that.data.deviceId, that.data.serviceId, that.data.readCharacteristic);
      },
      fail: function (err) {
        console.log(err, "获取该服务失败getBLEDeviceCharacteristics")
      }
    })
  },
  // 监听蓝牙返回值
  notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      state: true,
      success: function (res) {
        console.log('使能成功', res);
        wx.showToast({
          title: '连接成功',
          duration: 3000,
          icon: 'success'
        })
        that.onBLECharacteristicValueChange();
        wx.readBLECharacteristicValue({
          characteristicId: that.data.countCharacteristic,
          deviceId: that.data.deviceId,
          serviceId: that.data.serviceId,
          success:function(ret){
            console.log(ret);
          },fail:function(err){
            console.log(err);
            console.log(that.data.deviceId);
            console.log(that.data.serviceId);
            console.log(that.data.countCharacteristic);
          }
        })
      },
      fail: function (err) {
        wx.hideLoading({
          complete: (res) => {
          },
        })
        wx.showToast({
          title: '蓝牙连接失败，errCode：'+err.errCode,
          icon:"none"
        })
        console.log("监听失败", err, deviceId, serviceId, characteristicId)
      }
    })
  },
  // 获取返回值
  onBLECharacteristicValueChange() {
    var that = this;
    wx.onBLECharacteristicValueChange(function (res) {
      var turn_back = that.hex2str(that.buf2hex(res.value));
      turn_back = turn_back.replace(/\ +/g,"");
      turn_back = turn_back.replace(/[ ]/g,"");
      turn_back = turn_back.replace(/[\r\n]/g,"");
      console.log("最终转回来的值",turn_back);
    }, function (err) {
      console.log(err)
    })
  },
  // 发送指令API
  writeBLECharacteristicValue(hex,characteristic){
    var that = this;
    var buffer = new ArrayBuffer(hex.length);
    console.log(hex);
    if(hex){
      console.log(hex);
      for(var i in hex){
        new DataView(buffer).setInt8(i,Number(hex.charCodeAt(i)));
      }
    }else{
      console.log("未输入指令");
      return;
    }
    console.log(buffer);
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: characteristic,
      value: buffer,
      success: function (res) {
        console.log("发送指令成功")
      },
      fail: function (err) {
        console.log("指令发送失败", err)
      }
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter({
      success(res) {
        console.log("断开蓝牙模块", res);
      }
    })
  },
  closeBLEConnection() {
    var that = this;
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success(res) {
        console.log("断开蓝牙连接", res);
        that.setData({
          mac:"",
          count:"",
          power:"",
        })
        wx.showToast({
          title: '已断开连接',
          icon:"none"
        })
      }
    })
  },
  buf2hex: function (buffer) { // buffer is an ArrayBuffer
    return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
  },
  // 16进制转字符串
  hex2str(hex) {
    var rawStr = hex.substr(0, 2).toLowerCase() === "0x" ? hex.substr(2) : hex;
    var len = rawStr.length;
    if (len % 2 !== 0) {
      alert("Illegal Format ASCII Code!");
      return "";
    }
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
      curCharCode = parseInt(rawStr.substr(i, 2), 16);
      resultStr.push(String.fromCharCode(curCharCode));
    }
    return resultStr.join("");
  },
  // 字符串转16进制
  str2hex(str) {
    if (str === "") {
      return "";
    }
    var arr = [];
    // arr.push("0x");
    for (var i = 0; i < str.length; i++) {
      arr.push(str.charCodeAt(i).toString(16));
    }
    return arr.join('');
  },
  /**
   * 确认补货完成
   */
  sureRep:function(){
    var PageThis = this;
    wx.showModal({
      title: '提示',
      content: '确认已完成补货?',
      success(res) {
        if (res.confirm) {
          PageThis.uploadData();
        } else if (res.cancel) {

        }
      }
    })
  },
  /**
   * 上报信息
   */
  uploadData:function(){
    var PageThis = this;
    var latList = PageThis.data.devInfo.lat_list;
    var uploadList = [];
    for(var i in latList){
      if (latList[i].lat_op_state > 0 && latList[i].noStockState != 1){
        uploadList.push({
          lat_id:latList[i].lat_id,
          rep_goods_id:latList[i].lat_goods_id
        });
      }
    }
    wx.request({
      url: app.globalData.serverInfo.gateWayUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {
        api_name: "rep_lat_goods",
        device_id: PageThis.data.devInfo.dev_id,
        login_manager_id: PageThis.data.userInfo.manager_id,
        rep_list: uploadList,
        count:PageThis.data.count
      },
      success:function(res){
        var data = res.data;
        console.log(res);
        if (Number(data.state) == 1){
          wx.showToast({
            title: '补货成功',
            icon: 'success',
            duration: 2000,
          });
          PageThis.closeBluetoothAdapter();
          PageThis.closeBLEConnection();
          setTimeout(function(){
            wx.navigateBack();
          },1500)
        }else{
          wx.showToast({
            title: data.msg,
            icon: 'none',
            duration: 2000,
          });
        }
      }
    })
  },
  /**
   * 上报缺货
   */
  reportNoStock:function(e){
    var PageThis = this;
    var devInfo = PageThis.data.devInfo;
    var id = e.currentTarget.dataset.id;
    for (var i in devInfo.lat_list){
      if (devInfo.lat_list[i].lat_id == id){
        devInfo.lat_list[i].noStockState = 1;
      }
    }
    PageThis.setData({
      devInfo: devInfo
    });
    wx.showToast({
      title: '设置成功',
      icon: 'success',
      duration: 1000,
    });
  },
  /**
   * 上报电量
   */
  reportElectric:function(num){
    var PageThis = this;
    var devInfo = PageThis.data.devInfo;
    devInfo['dev_electric_quantity'] = num;
    PageThis.setData({
      devInfo:devInfo,
    })
    wx.request({
      url: app.globalData.serverInfo.gateWayUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {
        api_name: "report_device_electric",
        dev_id:  PageThis.data.devInfo.dev_id,
        device_electric: num,
        login_manager_id: PageThis.data.userInfo.manager_id
      },
      success:function(res){
        console.log(res)
      }
    })
  }
})