// subpages/addMattresses/addMattresses.js

const app = getApp();
const util = require('../../utils/util.js');
const timeOut = 40; //超时时间
var timeId = "";
var sequenceControl = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    showBluetoothList: false,
    showBluetoothConnected: false,//连接中
    isBluetoothConnected: false,//连接成功
    bluetoothConnectedStep: 0,
    placeOfUse: "",
    usingHuman: "",
    pid: "",
    sn: "",
    ssid: "",
    password: "",
    bluetoothSelectIndex: -1,
    activeIcon: "/subpages/images/ic_blue_radio_check.png",
    normalIcon: "/subpages/images/ic_blue_radio_uncheck.png",
    deviceList: [],
    deviceId: "",
    deviceIds: [],
    wifiInfo: null,
    deviceId: "",
    password: "",
    notice: "",
    value: 90,
    gradientColor: {
      '0%': '#00CEB2',
      '50%': '#00C7FF',
      '100%': '#53DAFF',
    },
    statusDefault: ['蓝牙连接...', '蓝牙连接成功', '成功获取设备信息', '获取属性信息成功', '发送配置信息...', '配置信息发送成功', '连接成功'],
    descFailList: ["蓝牙连接失败", "获取设备信息失败", "获取属性信息失败", "发送配置信息失败", "分配网络失败"],
    failure: false,
    value: 0,
    desc: "设备连接...",
    blueConnectNum: 0,
    isChecksum: true,
    isEncrypt: false,
    flagEnd: false,
    defaultData: 1,
    ssidType: 2,
    passwordType: 3,
    meshIdType: 3,
    deviceNo: 0,
    uuid: "",
    serviceId: "",
    meshId: "",
    processList: [],
    result: [],
  },
  onClose() {
    wx.offBluetoothDeviceFound();
    this.setData({ showBluetoothList: false, showBluetoothConnected: false });
  },
  closeEndDialog() {
    this.onClose()
    wx.navigateBack()
  },
  checkBluetoothSelectIndex(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ bluetoothSelectIndex: index });

  },
  commitData() {
    console.log(this.data.placeOfUse);
    console.log(this.data.usingHuman);
    console.log(this.data.sn);
    console.log(this.data.ssid);
    console.log(this.data.password);
    this.checkSn(this.data.sn);


  },
  commitUserData() {
    const that = this;
    if (that.data.isEdit) {
      wx.request({
        url: 'https://aipush.aidsleep.cn/customeredit',
        method: 'POST',
        data: {
          token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
          pid: this.data.pid,
          sntram: this.data.sn,
          per: this.data.usingHuman,
          loc: this.data.placeOfUse,
        },
        success: (res) => {
          var codes = res.data.codes;
          if (codes && codes == 'success') {
            wx.showToast({
              icon: 'none',
              title: "编辑成功"
            });
            wx.setStorageSync("successId", this.data.pid);
            setTimeout(() => {
              wx.navigateBack();
            }, 800);
          } else {
            wx.showToast({
              icon: 'none',
              title: "编辑失败"
            });
          }
        },
        fail: () => {
          wx.showToast({
            icon: 'none',
            title: "编辑失败"
          });
        }
      });
      return
    }
    wx.request({
      url: 'https://aipush.aidsleep.cn/wxsaveunionsn',
      method: 'POST',
      data: {
        token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
        unionid: wx.getStorageSync("unionid"),
        sntram: this.data.sn,
        per: this.data.usingHuman,
        loc: this.data.placeOfUse,
      },
      success: (res) => {
        var codes = res.data.codes;
        var backPid = res.data.back.pid || "";
        if (codes && codes == 'success') {
          wx.showToast({
            icon: 'none',
            title: "添加成功"
          });
          wx.setStorageSync("successId", backPid);
          setTimeout(() => {
            wx.navigateBack();
          }, 800);
        } else {
          wx.showToast({
            icon: 'none',
            title: "添加失败"
          });
        }
      },
      fail: () => {
        wx.showToast({
          icon: 'none',
          title: "添加失败"
        });
      }
    });
  },
  // 开启蓝牙
  bindViewBlue: function ()  {
    const that = this;
    wx.offBluetoothDeviceFound();
    wx.closeBluetoothAdapter();
    wx.openBluetoothAdapter({
      success(res) {
        //console.log(res);
        that.getBluDevice()
      },
      fail(res) {
        console.log(res);
        wx.showToast({
          icon: 'none',
          title: `${JSON.stringify(res)}`
        });
      }
    })
  },
  // 获取蓝牙设备列表
  getBluDevice() {
    var self = this;
    //第一步检查蓝牙适配器是否可用
    wx.onBluetoothAdapterStateChange(function (res) {
      if (!res.available) {
        util.showToast('蓝牙不可用');
        return false;
      }
    });

    var oldDeviceList = wx.getStorageSync('deviceList');
    if (oldDeviceList && oldDeviceList.length) {
      self.setData({
        deviceList: oldDeviceList,
        showBluetoothList: true
      });
    }
    //第二步关闭适配器，重新来搜索
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.getBluetoothAdapterState({
          success: function (res) {
            wx.stopBluetoothDevicesDiscovery({
              success: function (res) {
                wx.startBluetoothDevicesDiscovery({
                  services: ['0000FFF0-0000-1000-8000-00805F9B34FB'],
                  success: function (res) {
                    wx.onBluetoothDeviceFound(function (res) {
                      console.log(res);

                      var list = util.filterDevice(res.devices, "name");
                      if (list.length > 0) {
                        console.log('==========onBluetoothDeviceFound===========');
                        console.log(list);
                        var deviceList = self.data.deviceList;
                        var doDevices = wx.getStorageSync('doDevices');
                        if (doDevices) {
                        } else {
                          doDevices = [];
                        }
                        console.log(deviceList);
                        console.log(doDevices);
                        wx.setStorageSync('doDevices', doDevices);
                        wx.hideLoading();
                        list.forEach(function (item) {
                          var flag = true;
                          for (var i = 0; i < deviceList.length; i++) {
                            var itemSub = deviceList[i];
                            if (itemSub.deviceId === item.deviceId) {
                              flag = false;
                              break;
                            }
                          }
                          if (flag) {
                            var arrD = item['name'].split(' ');
                            item['sn'] = arrD[1];
                            // wx.request({
                            //   url: 'https://aipush.aidsleep.cn/checkbeds',
                            //   method: 'POST',
                            //   header: {
                            //     'content-type': 'application/json' // 设置请求的 header
                            //   },
                            //   data: {
                            //     "snlists": arrD[1], // 需要发送的数据
                            //     "token": "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3"
                            //   },
                            //   success: function (res) {
                            //     //console.log(res);
                            //     if (res.data.data[arrD[1]].trim() == 'yes') {
                            //       item['beOnline'] = 'icon-deng-ok';
                            //     } else {
                            //       item['beOnline'] = '';
                            //       // if (doDevices.indexOf(item['deviceId']) >= 0) {
                            //       //   item['beOnline'] = 'icon-deng-ok';
                            //       // }
                            //     }
                                deviceList.push(item);
                            //   },
                            //   fail: function (error) {
                            //     console.error(error);
                            //   }
                            // });
                          }
                        })

                        self.setData({
                          deviceList: deviceList,
                          showBluetoothList: true
                        });
                        wx.setStorageSync('deviceList', deviceList);
                      }
                    })
                  }
                })
              },
              fail: function (res) {
                console.log(res);
              }
            });
          },
          fail: function (res) {
            console.log(res);
          }
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });

  },
  commitBluetooth() {
    this.onClose();
    if (this.data.bluetoothSelectIndex < 0) {
      util.showToast("请选择一个床垫");
      wx.offBluetoothDeviceFound()
      return false;
    }
    var deviceId = this.data.deviceList[this.data.bluetoothSelectIndex].deviceId;
    var name = this.data.deviceList[this.data.bluetoothSelectIndex].name;
    var nameList = this.data.deviceList[this.data.bluetoothSelectIndex].name.split(' ');
    this.setData({
      deviceId: deviceId,
      sn: nameList[1]
    })
      wx.offBluetoothDeviceFound()
  },
  // 开始配网
  bindViewConnect() {
    const that = this;
    if (that.data.bluetoothSelectIndex < 0) {
      util.showToast("没有指定要配网的设备");
      return false;
    }
    var deviceIds = this.data.deviceList[this.data.bluetoothSelectIndex];
    if (this.data.deviceList.length == 0 || deviceIds.length === 0) {
      util.showToast("没有指定要配网的设备");
      return false;
    }


    that.gotoProvision()
  },
  // 获取Wifi
  getWifiInfo: function () {
    wx.startWifi({
      success(res) {
        //console.log(' ================== startWifi ================== ');
        //console.log(res);
        wx.getConnectedWifi({
          success(res) {
          },
          fail: function (err) {
            console.log(' ================== startWifi fail ================== ');
            console.log(err);
            if (app.data.sytem == 'ios') {
              util.showToast("获取Wi-Fi信息失败,请更新微信到最新版");
            } else {
              util.showToast("获取Wi-Fi信息失败");
            }
          }
        });
      }
    });
    const self = this;
    wx.startWifi({
      success(res) {
        //console.log(res)
        // 先取一次，防止IOS获取不到
        wx.getConnectedWifi({
          success(res) {
            self.setData({
              wifiInfo: res.wifi,
              ssid: res.wifi.SSID
            });
            //console.log('== getConnectedWifi ==');
            //console.log(res);
            if (res.frequency >= 2412 && res.frequency <= 2472) { } else {
              self.setData({
                notice: "温馨提示：当前您连接的Wi-Fi网络是5G频段，建议连接2.4G频段配网"
              })
            }
          },
          fail: function (err) {
            util.showToast("获取Wi-Fi信息失败");

          }
        })
        wx.onWifiConnected(function (res) {
          // console.log('== onWifiConnected ==');
          // console.log(res);
          self.setData({
            wifiInfo: res.wifi
          })
        })
      },
      fail(res) {
        console.log('WIFI初始化失败', res)
        util.showToast("WIFI初始化失败");
      }
    })
  },
  gotoProvision: function () {
    const wifiInfo = this.data.wifiInfo;
    const ssid = wifiInfo != null ? wifiInfo.SSID : null;
    const bssid = wifiInfo != null ? wifiInfo.BSSID : null;
    const password = this.data.password;
    if (wifiInfo == null) {
      util.showToast("没有Wi-Fi连接");
      return;
    } else {
      if (ssid == null || ssid == '' || password == '') {
        util.showToast("WiFi登录名和密码不能为空");
        return;
      } else {
        const info = {
          ssid: ssid,
          bssid: bssid,
          password: password,
          deviceIds: this.data.deviceId
        }
        this.blueConnect();
      }
    }
  },
  // 蓝牙链接
  blueConnect: function (event) {
    //console.log(' =============== blueConnect start ===============')
    var self = this;
    sequenceControl = 0;
    self.setData({
      flagEnd: false,
      serviceId: "",
      uuid: "",
      showBluetoothConnected: true
    });
    self.setProcess(0, util.descSucList[0], 1);
    wx.offBluetoothAdapterStateChange();
    //第一步检查蓝牙适配器是否可用
    wx.onBluetoothAdapterStateChange(function (res) {
      if (!res.available) {
        util.showToast('蓝牙不可用');
        return false;
      }
    });
    //console.log(app.data);
    if (app.data.sytem == 'ios') {

    }
    self.onTimeout(0);
    //console.log('deviceId = ' + self.data.deviceId)
    wx.createBLEConnection({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: self.data.deviceId,
      timeout: 10000,
      success: function (res) {
        wx.setBLEMTU({
          deviceId: self.data.deviceId,
          mtu: 128
        })
        //console.log("============ createBLEConnection success =============")
        //console.log(self.data.deviceId)
        self.getDeviceServices(self.data.deviceId);
      },
      fail: function (res) {
        console.log("============ createBLEConnection fail =============")
        console.log(res)
        console.log(self.data.blueConnectNum)
        var num = self.data.blueConnectNum;
        if (num < 3) {
          self.blueConnect();
          num++;
          self.setData({
            blueConnectNum: num
          })
        } else {
          self.setFailProcess(true, res.errCode + "::" + util.descFailList[0]);
        }
      }
    })
  },
  getDeviceServices: function (deviceId) {
    var self = this;
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: deviceId,
      success: function (res) {
        self.setProcess(10, util.descSucList[1], 2);
        var services = res.services;
        if (services.length > 0) {
          for (var i = 0; i < services.length; i++) {
            var uuid = services[i].uuid;
            if (uuid == app.data.service_uuid) {
              self.getDeviceCharacteristics(deviceId, uuid);
              return false;
            }
          }
        }
      },
      fail: function (res) {
        self.setFailProcess(true, res.errCode + "::" + util.descFailList[1]);
      }
    })
  },

  getDeviceCharacteristics: function (deviceId, serviceId) {
    //console.log(" ============== getDeviceCharacteristics =============== ");
    var self = this;
    wx.getBLEDeviceCharacteristics({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: deviceId,
      serviceId: serviceId,
      success: function (res) {
        self.setProcess(40, util.descSucList[2], 3);
        var list = res.characteristics;
        if (list.length > 0) {
          for (var i = 0; i < list.length; i++) {
            var uuid = list[i].uuid;
            if (uuid == app.data.characteristic_write_uuid) {
              self.openNotify(deviceId, serviceId, uuid);
              self.setData({
                serviceId: serviceId,
                uuid: uuid,
              })
              return false;
            }
          }
        }
      },
      fail: function (res) {
        console.log(res);
        self.setFailProcess(true, res.errCode + "::" + util.descFailList[2]);
      }
    })
  },

  //连接超时
  onTimeout: function (num) {
    const self = this;
    timeId = setInterval(function () {
      if (num < timeOut) {
        num++;
      } else {
        clearInterval(timeId);
        wx.showModal({
          title: '提示',
          content: '配网失败，请检查wifi密码或设备是否连接正常',
          showCancel: false
        });
        self.setData({
          showBluetoothConnected: false
        });
        // self.setFailProcess(true, util.descFailList[4]);
      }
    }, 1000)
  },
  //启用通知
  openNotify: function (deviceId, serviceId, characteristicId) {
    //console.log("=========== openNotify ============");
    var self = this;
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: app.data.characteristic_read_uuid,
      success: function (res) {
        //console.log(res);
        self.writeDevice(deviceId, serviceId, characteristicId, null);
        self.onNotify();
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  //监听通知
  onNotify: function () {
    //console.log("=========== onNotify ============");
    var self = this;
    wx.onBLECharacteristicValueChange(function (res) {
      //console.log(res);
      self.getResultType(util.ab2hex(res.value));
    })
  },

  getCharCodeat: function (str) {
    let utf8Bytes = [];
    for (let i = 0; i < str.length; i++) {
      let char = str.charCodeAt(i);
      if (char < 0x80) {
        utf8Bytes.push(char);
      } else if (char < 0x800) {
        utf8Bytes.push(0xc0 | (char >> 6));
        utf8Bytes.push(0x80 | (char & 0x3f));
      } else if (char < 0x10000) {
        utf8Bytes.push(0xe0 | (char >> 12));
        utf8Bytes.push(0x80 | ((char >> 6) & 0x3f));
        utf8Bytes.push(0x80 | (char & 0x3f));
      }
    }
    return utf8Bytes;
    // var list = [];
    // for (var i = 0; i < str.length; i++) {
    //   list.push(str.charCodeAt(i));
    // }
    // return list;
  },
  // 设备数据开始写入
  writeDevice: function (deviceId, serviceId, characteristicId, data) {
    //console.log("===== writeDevice =====");
    var self = this,
      obj = {};
    self.setProcess(60, util.descSucList[4], 3);
    sequenceControl = parseInt(sequenceControl) + 1;
    if (!util._isEmpty(data)) {
      obj = util.isSubcontractor(data, true, sequenceControl);
    } else {
      data = util.writeData(self.getCharCodeat('"' + self.data.ssid + '","' + self.data.password + '"'));
      obj = util.isSubcontractor(data, self.data.isChecksum, sequenceControl);
    }
    var typedArray = new Uint8Array(obj.lenData)
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: typedArray.buffer,
      success: function (res) {
        //console.log(res);
        if (obj.flag) {
          self.writeDevice(deviceId, serviceId, characteristicId, obj.laveData);
        } else {
          self.setProcess(80, util.descSucList[5], 4);
        }
      },
      fail: function (res) {
        console.log(res);
        self.setFailProcess(true, res.errCode + "::" + util.descFailList[3]);
      }
    })
  },
  getResultType: function (list) {
    console.log(' ========= getResultType ========= ');
    var self = this;
    console.log(list);
    var deviceList = wx.getStorageSync('deviceList');
    console.log(deviceList);
    if (list.length < 4) {
      self.setFailProcess(true, util.descFailList[4]);
      return false;
    }
    var val = list[4];
    if (val == "00") {
      var idx = self.data.deviceNo + 1;
      var doDevices = wx.getStorageSync('doDevices');
      if (doDevices) {
        if (doDevices.indexOf(self.data.deviceId) < 0) {
          doDevices.push(self.data.deviceId);
        }
      } else {
        doDevices = [self.data.deviceId];
      }
      wx.setStorageSync('doDevices', doDevices);
      var deviceSn = self.data.deviceId;
      for (var i = 0; i < deviceList.length; i++) {
        var itemSub = deviceList[i];
        if (itemSub.deviceId === self.data.deviceId) {
          deviceSn = itemSub.sn;
          break;
        }
      }

      if (idx < self.data.deviceIds.length) {
        self.setProcess(90, 'SN:' + deviceSn + ' 连接成功', 5);
        wx.closeBLEConnection({
          deviceId: self.data.deviceId,
          success: function (res) { }
        })
        self.setData({
          deviceNo: idx,
          deviceId: self.data.deviceIds[idx],
          blueConnectNum: 0
        });
        self.blueConnect();
      } else {
        self.setProcess(90, 'SN:' + deviceSn + ' 连接成功', 5);
        self.setProcess(100, util.descSucList[6], 7);
        self.setData({
          result: [],
        })
      }
    } else {
      self.setFailProcess(true,  util.descFailList[4])
    }
  },
  setProcess: function (value, desc, step = 0) {
    var self = this,
      list = [];
    list = self.data.processList;
    if (list.indexOf(desc) == -1) {
      list.push(desc);
    }
    if (self.data.value <= value) {
      self.setData({
        value: value,
        bluetoothConnectedStep: step
      });
    }
    self.setData({
      processList: list
    });
    //console.log(value);
    //console.log(desc);

    if (value == 100) {
      self.closeConnect();
      wx.closeBluetoothAdapter();
      self.setData({
        isBluetoothConnected: true,
        desc: util.descSucList[6]
      });
      clearInterval(timeId);
      sequenceControl = 0;
      self.commitUserData();
    }
  },

  setFailProcess: function (flag, desc) {
    var self = this,
      list = [];
    list = self.data.processList;
    list.push(desc);
    self.setData({
      failure: flag,
      processList: list
    });
  },
  closeConnect: function () {
    var self = this;
    wx.closeBLEConnection({
      deviceId: self.data.deviceId,
      success: function (res) { }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.authorize({
      scope: 'scope.bluetooth',
      success() {
        // 用户同意授权后再次获取位置  
      },
      fail() {
        // 用户拒绝授权  
      }
    });
    this.getWifiInfo();
    if (options.type && options.type == "edit") {
      wx.setNavigationBarTitle({
        title: "编辑床垫"
      })
      const item = wx.getStorageSync("item");
      if (item) {
        this.setData({
          isEdit: true,
          pid: item.pid,
          placeOfUse: item.location,
          usingHuman: item.person,
          deviceId: item.sn,
          sn: item.sn,
          ssid: "",
          password: "",
        })
        wx.removeStorageSync("item")
      }
    }

  },
  //   实验室
  // 测试
  //  332016850591
  //  sleep
  // sleep1234
  checkSn(sntram) {
    const that = this;
    wx.request({
      url: 'https://aipush.aidsleep.cn/wxchecksn',
      method: 'POST',
      data: {
        token: "89835e65993fee4a6a6cbbe4c271da51e5521822934e13769e61cadabaed72c3" || wx.getStorageSync('token'),
        sntram: sntram,
      },
      success: (res) => {
        var incustom = res.data.incustom;
        if (incustom == "true") {
          that.bindViewConnect();
        } else {
          wx.showToast({
            icon: 'none',
            title: "sn 不合法"
          });
        }
      },
      fail: () => {
        wx.showToast({
          icon: 'none',
          title: "sn 不合法"
        });
      }
    });
  },

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

  },

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

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.offWifiConnected({});
    wx.stopWifi({})
    wx.closeBluetoothAdapter();
    wx.offBluetoothDeviceFound();
    wx.removeStorageSync('doDevices')
    wx.removeStorageSync('deviceList')
    clearInterval(timeId);
    this.closeConnect()
    
  },

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

  },

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

  },

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

  }
})