/**
  *连接蓝牙设备
  *
  *
**/

var host,ble,uuID,serviceUUID,characteristicUUID;

serviceUUID = '6e400001-b5a3-f393-e0a9-e50e24dcca9e'; //服务uuid
characteristicUUID = '6e400003-b5a3-f393-e0a9-e50e24dcca9e'; //特征uuid

//初始化页面
function initBle()
{
    ble = api.require('ble');
    var systemType = api.systemType;  // 比如： ios
    if(systemType == "android"){
        ble.openBluetooth(function(ret) {
            if(ret.status){
                initLocation('location','位置');//检查位置权限
            }
        });
    }
    //打开蓝牙
    setTimeout(function(){
      //初始化蓝牙
      ble.initManager(function(ret) {
          if (ret.state == "poweredOn") {
              console.log("初始化成功");
          }
      });
    },1000)
}

//获取定位权限
function initLocation(permission,text)
{
    var resultList = api.hasPermission({
       list: [permission]
     });
     if (resultList[0].granted) {
         // 已授权，可以继续下一步操作
         console.log(permission + '已授权');
         //开启蓝牙及位置信息 后判断是否已连接蓝牙
     } else {
       api.confirm({
           title: '提醒',
           msg: '没有获得 ' + text + " 权限,应用无法正常运行，是否前往设置？",
           buttons: ['去设置','取消',]
       }, function(ret) {
           if (ret.buttonIndex == 1) {
               api.requestPermission({
                   list: [permission],
                   code:1
               }, function(res) {
                   if (res.list[0].granted) {
                       // 已授权，可以继续下一步操作
                       console.log(permission + '已授权');
                       //开启蓝牙及位置信息 后判断是否已连接蓝牙
                   }
               });
           }
       });
     }
}

//蓝牙扫描
function scanBlue()
{
    //扫描之前先清空数据
    $(".blueul").html("");
    console.log('scanBlue: '+uuID)

    //判断uuid 是否已存在 如果已存在先断开蓝牙在扫描
    if(uuID){
        ble.disconnect({
            peripheralUUID: uuID
        }, function(ret,err) {
            console.log('disconnect: '+JSON.stringify(ret));
            if (ret) {
                doscanBlue();
            }
        });
    }
    else
    {
        doscanBlue();
    }
}

//执行蓝牙扫描
function doscanBlue()
{
    // $api.setStorage('uuID', '');//清除uuid
    // $api.setStorage('blueLists','');
    ble.scan({
      serviceUUIDs: [],
      clean:true
    }, function(ret) {
      if (ret.status) {
          var toast = new auiToast();
          // 创建一个div设置遮罩的效果，添加aui遮罩的样式
          var tostdiv = document.createElement("div");
          tostdiv.classList.add("aui-mask");
          tostdiv.classList.add("aui-mask-in");
          document.body.appendChild(tostdiv);
          // 自定义弹窗的内容
          toast.loading({
              title:"正在扫描",
              duration:2000
          },function(ret){
              setTimeout(function(){
                  ble.getPeripheral(function(ret) {
                      tostdiv.classList.remove("aui-mask");
                      tostdiv.classList.remove("aui-mask-in");
                      toast.hide();
                      ble.stopScan();//结束扫描
                      if (ret) {
                          var data = ret.peripherals;
                          var arr = [];
                          if(data && data.length)
                          {
                              for(var i=0;i<data.length;i++){
                                  var name = data[i]['name'];
                                  if(name && name.indexOf('JFDIII') != -1){
                                      arr.push(data[i]);
                                  }
                              }
                          }
                          if(arr.length)
                          {
                              //扫描到蓝牙设备 保存
                              // $api.setStorage('blueLists', JSON.stringify(arr));
                              initHtml(arr);
                          }
                          else
                          {
                              customToast('未扫描到蓝牙设备', 2000);
                          }
                      }
                  });
              }, 2000)
          })
      }
    })
}


//渲染 页面
function initHtml(data)
{
    // var lists = $api.getStorage('blueLists');
    var html = '';
    if(data)
    {
        // var data = JSON.parse(lists);
        for(var i=0;i<data.length;i++)
        {
            //判断
            html += '<li class="aui-list-item blueli" onclick="connectBlue(this)" data_uuid="'+data[i]['uuid']+'">'
                    +'    <div class="aui-list-item-inner">'
                    +'        <div class="aui-list-item-title">'+data[i]['name']+'</div>'
                    +'        <div class="aui-list-item-right">'
                    +'            <div class="aui-label aui-label-btn">'
                    +'              <span class="no">连接</span>'
                    +'              <span class="yes">已连接</span>'
                    +'            </div>'
                    +'        </div>'
                    +'    </div>'
                    +'</li>';
        }
    }
    $("."+blueul).html(html);
}

//连接蓝牙
function connectBlue(obj)
{
    //判断是否已连接
    var status = $(obj).hasClass('active');
    // if(status){
    //     customToast('蓝牙已连接', 2000);
    //     return false;
    // }
    uuID = $(obj).attr('data_uuid');//点击连接蓝牙
    if(uuID)
    {
        ble.connect({
            peripheralUUID: uuID
        }, function(ret, err) {
            if (ret.status)
            {
                //连接成功
                $(obj).addClass('active');
                // $api.setStorage('uuID', uuID);//保存uuid
                discoverService();//获取服务 uuid
            }
            else
            {
                customToast('连接失败，请重新连接', 2000);
            }
        });
    }
    else
    {
      alert('请选择蓝牙设备');
    }
}


//获取服务uuid
function discoverService()
{
    //获取设备所有服务
    ble.discoverService({
        peripheralUUID: uuID
    }, function(ret) {
        console.log('discoverService: '+JSON.stringify(ret));
        if (ret) {
            discoverCharacteristics();//特征uuid
        }
        else
        {
            customToast('获取服务uuid失败', 2000);
        }
    });
}

//获取特征uuid
function discoverCharacteristics()
{
    //获取特征 uuid
    ble.discoverCharacteristics({
        serviceUUID:serviceUUID,
        peripheralUUID: uuID
    }, function(ret) {
        console.log('discoverCharacteristics: '+JSON.stringify(ret));
        if (ret)
        {
            setNotify();
        }
        else
        {
            customToast('获取特征uuid失败', 2000);
        }
    });
}

//监听数据
function setNotify()
{
    //监听数据回发
    ble.setNotify({
        peripheralUUID: uuID,
        serviceUUID: serviceUUID,
        characteristicUUID: characteristicUUID
    }, function(ret) {
          console.log('setNotify: '+JSON.stringify(ret));
          //{"status":true,"characteristic":{"uuid":"6e400003-b5a3-f393-e0a9-e50e24dcca9e","serviceUUID":"6e400001-b5a3-f393-e0a9-e50e24dcca9e","permissions":"0","propertie":"notify","value":"aaffff800000130001642900"}}
          if(ret && ret.characteristic && ret.characteristic.value){
              //处理字符串
              var bluestr = ret.characteristic.value;//'aaffff801369730001645000'
              var symbol = bluestr.substring(6,7); //符号
              var value = bluestr.substring(7,13); //值
              var point = bluestr.substring(13,14); //小数位数

              var startnewstr = value.slice(0,'-'+point);
              var endnewstr = value.slice('-'+point);
              var symbolstr = symbol==8?'-':'';
              var newstr = symbolstr+parseInt(startnewstr)+'.'+endnewstr;
              console.log('setNotify返回值: '+newstr);
              //监听到蓝牙设备返回的值后广播出去
              if(newstr){
                  api.sendEvent({
                      name: 'ble_hasNUM',
                      extra: {
                          number: newstr
                      }
                  });
              }
          }
          else
          {

          }
    });
}
