const app = getApp()
//buffer转16进制，解析nfc扫描结果的id
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('').toUpperCase();
}
Page({
  data: {
    filePath: app.globalData.$filePath,
    modalHidden:true,
    region: [],
    isIOS:false,
    seleteType:[{transportStatus:'00',transportStatusName:'入库'},{transportStatus:'10',transportStatusName:'出库'},{transportStatus:'20',transportStatusName:'结束'}],
    showDialog: false,// 详情弹窗
  },
  onUnload() {
    this.onHide()
  },
  onHide() {
    var nfc = this.nfc
    if (nfc) {
      nfc.offDiscovered(this.discoverHandler)
    }
  },
  onShow() {
    const that = this;
    if(that.data.isIOS){
      that.goApp()
      return;
    }
    const nfc = wx.getNFCAdapter();
    that.nfc = nfc;
    const type = that.data.type;
    const {path,addLabel,loginRole} = that.data;
    that.discoverHandler = function (res) {
      var message = res.messages && res.messages[0].records[0].payload;
      message = message && ab2hex(message);
      if(type != 'X104'){
        if (message && message.length >= 58) {
          if(path == 'factorycheck'){
            that.getInfo(message);
          }
          message = message.substring(6, 80);
          if(message.indexOf('72') == 0){
            message = message.substring(0,52);
          }
         if(path == 'iodep'){
            that.iodep(message);
          }else if(addLabel == 20){
            that.chainBind(message);
          }else if(path == 'find' && loginRole != 'doctor'){
            // that.goDetail(message);
            that.goDetailInfo(message);
          }else if(path == 'find' && loginRole == 'doctor'){
            that.goPdf(message);
            that.writeMsg();
          }
        }else{
          app.showToptip(that,'error','请换一个'+type+'标签');
          return;
        }
      }else if(type == 'X104'){
        var id = res.id && ab2hex(res.id);
        if(message && message.length >= 58){
          message = message.substring(6, 80);
          if(message.indexOf('72') == 0){
            app.showToptip(that,'error','请换一个'+type+'标签');
            return;
          }
          app.showToptip(that,'error','请换一个'+type+'标签');
          return;
        }
        if(path == 'iodep'){
          that.iodep(id);
        }else if(addLabel == 20){
          that.chainBind(id)
        }else if(path == 'find' && loginRole !='doctor'){
          // that.goDetail(id);
          that.goDetailInfo(id);
        }else if(path == 'find' && loginRole == 'doctor'){
          that.writeMsg();
          that.goPdf(id);
        }
      }
    }
    nfc.onDiscovered(that.discoverHandler)
    nfc.startDiscovery({
      fail(err) {
        if (err.errCode == 13000) {
          that.goApp();
          app.showToptip(that, "worning", "设备不支持NFC，请扫码下载app");
        }
        if (err.errCode == 13001) {
          app.showToptip(that, "worning", "系统NFC开关未打开")
        }
        if (err.errCode == 13016) {
          app.showToptip(that, "worning", "连接失败")
        }
      }
    })
  },
  getInfo(message){
    var that = this;
    app.requestP({
      url: "/query/scanChip1",
      method:"post",
      needToken:false,
      contentType:' application/json',
      data:{
        payload:message
      }
    }).then(res=>{
      wx.navigateTo({
        url: '/pages/nfc/outNfcTempInfo/outNfcTempInfo?data='+JSON.stringify(res.data.data),
      })
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
  iodep(code){
    var that =this;
    app.requestP({
      url:'/chainBound/checkBind',
      method:'post',
      // contentType:' application/json',
      data:{
        deviceCode:code,
      }
    }).then(res=>{
      if(res.data.data!=1){
        app.showToptip(that,'error',res.data.msg);
        return;
      }
      app.requestP({
        url:'/chain/scan',
        method:'post',
        contentType:' application/json',
        data:{
          inoculatorId:'',
          payload:code,
          type:that.data.type,
        }
      }).then(res=>{
        const {transportStatus,id,code} = res.data.chain;
        that.setData({
          transportStatus,
          iodepId:id,
          modalHidden:!that.data.modalHidden,
          seleteType:that.setSeleteType(transportStatus),
        });
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg)
      })
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg);
    })
  },
  setTransportStatus(transportStatus){
    var seleteType = this.data.seleteType;
    var deptType;
    for(var i=0;i<seleteType.length;i++){
      if(seleteType[i].transportStatus == transportStatus){
        deptType = i;
        break;
      }
    }
    return deptType;
  },
  setSeleteType(transportStatus){
    var seleteType = this.data.seleteType;
    var type;
    for(var i=0;i<seleteType.length;i++){
      if(seleteType[i].transportStatus == transportStatus){
        seleteType.splice(i,1);
        break;
      }
    }
    this.setTransportStatus(transportStatus);
    return seleteType;
  },
  goDetailInfo(message){
    var that = this;
    app.requestP({
      url:'/chainBound/checkBind',
      method:'post',
      // contentType:' application/json',
      data:{
        deviceCode:message,
      }
    }).then(res=>{
      if(res.data.data !=1){
        app.showToptip(that,'error',res.data.msg);
        return;
      }
      app.requestP({
        url:'/chain/scan',
        method:'post',
        contentType:' application/json',
        data:{
          inoculatorId:'',
          payload:message,
          type:that.data.type
        }
      }).then(res=>{
        var id = res.data.msg;
        that.setData({
          showDialog: !this.data.showDialog,
          detailId:id,
          deviceCode:message
        });
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg)
      })
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg);
    })
  },
  goPdf(message){
    var that = this;
    app.requestP({
      url:'/chainBound/checkBind',
      method:'post',
      // contentType:' application/json',
      data:{
        deviceCode:message,
      }
    }).then(res=>{
      if(res.data.data != 1){
        app.showToptip(that,'error',res.data.msg);
        return;
      }
      app.requestP({
        url:'/chain/scan',
        method:'post',
        contentType:' application/json',
        data:{
          inoculatorId:that.data.inoculatorId,
          payload:message,
          type:that.data.type
        }
      }).then(res=>{
        const {id} = res.data.chain;
        wx.navigateTo({
          url: '/pages/workbench/scanningType/reportPdf/reportPdf?id='+id,
        })
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg);
      })
    })
  },
  setModalVal(e){
    this.setData({
      modalVal:e.detail.value
    })
  },
  onLoad:function(option) {
    const that = this;
    //获取定位信息
    wx.getLocation({
      altitude: 'altitude',
      success(res) {
        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
        })
      },
      error() {
        app.showToptip(that, "worning", "获取位置信息失败")
      }
    })
    //判断是否是iOS
    wx.getSystemInfo({
      success:function(res){
        if(res.platform=="ios"){
          that.isIOS = true; 
        }
      }
    })
    this.setData({
      path:option.path,
      type:option.type,
      id:option.id,// 绑定标签ID
      addLabel:option.addLabel,//判断是否是添加 20
      loginRole:option.loginRole,//医生身份
      inoculatorId:option.inoculatorId // 接种者 id
    })
    // this.iodep('02656E721801110001000800000000000011111111000000000009672900000000000967290000000000000000000000000000000041000000C4000000000002EFFFF9ECC7616C4183306610C598D31B624C498D316620C3981B09604C057E2FD5ECBF57D2F45F2BD97BAF45F0BE579AF35ECBE17B2F35DEBD9792F55EEBC181B0861EC2D8AB24628C3187316630C718F31A648C858AB0C622C1D85302616C25802FF5FAC01802FC5F2BF17CAF85F2BD97D2F85F6BED7B2F65ECBE17AB015FCC018530F626C6588314636C798F32463CC858FB21640C5D8930F616C4185B0B610C0982306606C198230260AC1582B025FEC0580B015FEC0D7FB0160AC198330B63EC8991B2063EC6D8FB2866ECAD9532765ACC99131E62CC5986B0D616C2D8430A60CC2583308610C3184B09602C0982B0960EC0D83B055F6C1D832FC5F4C358831863AC658B313640C7190B4069ACA195B430')
    // this.iodep('027A686174')
  },
  chainBind(deviceCode){
    var that = this;
    const {id,type,latitude,longitude} = that.data;
    app.requestP({
      url:'/chainBound/checkBind',
      method:'post',
      data:{
        deviceCode,
      }
    }).then(res=>{
      if(res.data.data == 0){
        app.requestP({
          url:'/chainBound/bind',
          method:'post',
          contentType:' application/json',
          data:{
            chainId:id,
            deviceCode,
            type,
            lat:latitude,
            lng:longitude
          }
        }).then(response=>{
          app.showToptip(that,'success',response.data.msg)
          that.writeMsg(deviceCode);
        }).catch(err=>{
          app.showToptip(that,'error',err.data.msg)
        })
      }else{
        app.showToptip(that,'error',res.data.msg);
      }
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
  goApp(e) {
    this.setData({
      modalName: "goApp"
    })
  },
  modalBindaconfirm(){  //一型保存地址
    var that = this;
    var {region,modalVal,transportStatus,iodepId,seleteType,deptType} = that.data;
    var addr = region.join('')+modalVal;
    if(region.join('') && modalVal && seleteType[deptType].transportStatus){
      app.requestP({
        url:'/chain/editTransport',
        // contentType:' application/json',
        method:'post',
        data:{
          addr,
          chainId:iodepId,  // 00 在库 //10 运输 // 20 已结束
          // transportStatus:transportStatus == '00' ? '10':transportStatus == '10' ?'00':'',
          transportStatus:seleteType[deptType].transportStatus,
        }
      }).then(res=>{
        that.setData({
          modalHidden:!that.data.modalHidden,
          region:[],
          modalVal:'',
          iodepId:'',
        })
        app.showToptip(that,'success',res.data.msg);
      }).catch(err=>{
        app.showToptip(that,'error',err.data.msg);
      })
    }else{
      app.showToptip(that,'error','地址不能为空');
    }
  },
  //取消按钮点击事件
  modalBindcancel:function(){
    this.setData({
      modalHidden:!this.data.modalHidden,
      region:[],
      modalVal:'',
      iodepId:'',
    })
  },
  regionChange: function(e) {
    this.setData({
      region: e.detail.value
    })
  },
  writeMsg(){
    const that = this
    const nfc = that.nfc
    const ndef = nfc.getNdef()
    ndef.connect({
      fail(){
        // app.showToptip(that, "worning", "标签连接失败，请贴近不要离开")
      },
      success(){
        console.log("连接成功")
        let records = [{
          id: new ArrayBuffer(0),
          payload: ab2hex("at"),
          type: new ArrayBuffer(0),
          tnf: 1
        }]
        ndef.writeNdefMessage({
          records,
          success(){
            console.log("写入成功")
            //指令发送成功，请求绑定接口
            // that.proBindSend()
          },
          fail(){
            // app.showToptip(that, "worning", "指令发送失败")
          },
          complete(res) {
            ndef.close()
          }
        })
      },
      complete(){
        //that.nfc.stopDiscovery(that.discoverHandler)
      }
    })
  },
  saveCode(e) {
    var that = this
    wx.downloadFile({
      url:'http://oss.zhongyihz.cn/group156/images/06619e9e4bfc54382290d931bf9814c2.png',
      success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath, // 此为图片路径
          success: (res) => {
            wx.showToast({
              title: '保存成功，请到相册中查看'
            });
          },
          fail: (err) => {
            wx.showToast({
              icon: 'none',
              title: '保存失败，请稍后重试'
            });
          }
        })
      },
      fail() {
        wx.showToast({
          icon: 'none',
          title: '保存失败，请稍后重试'
        });
      }
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  setType(e){
    var value = e.detail.value;
    var that = this;
    that.setData({
      deptType:value
    })
  },
  toggleDialog() { //详情弹窗
    this.setData({
      showDialog: !this.data.showDialog
    });
  },
  goDetail(){
    var detailId = this.data.detailId;
    var deviceCode = this.data.deviceCode || '';
    wx.navigateTo({
      url: '/pages/query/details?id='+detailId+'&deviceCode='+deviceCode,
    })
    this.setData({
      showDialog:!this.data.showDialog,
    })
  },
  clearBind(){
    var that = this;
    var detailId = that.data.detailId || '';
    var deviceCode = that.data.deviceCode || '';
    app.requestP({
      url:'/chainBound/unbind',
      method:'post',
      contentType:' application/json',
      data:{
        chainId:detailId,
        deviceCode,
      }
    }).then(res=>{
      that.setData({
        detailId:'',
        showDialog:!that.data.showDialog,
      })
      app.showToptip(that,'success',res.data.msg)
    }).catch(err=>{
      app.showToptip(that,'error',err.data.msg)
    })
  },
})