// pages/Hosts/Hosts.js 
const app = getApp() 
//导入酒店信息请求发方法 
import { 
  GetHostsInfo, 
  GetMAC, 
  GetFaceSN, 
  ErrorInfo, 
  CheckFaceSN, 
  OpenDoorTest, 
  GetRoomType, 
  GetRoomTypeAndModalsListLog,
  WebChatUpgrade,
  QueryUpdateHostStatus,
  ForwardQueryUpdateHostProgressBar,
  GetRoomTypeNode,
  SetRCULight,
  SetRCUAir,
  SetRCUCurtain,
} from '../../lib/RequestingCenter.js' 
import md5 from '../../utils/md5.min.js'

Page({ 
  /** 
   * 页面的初始数据 
   */ 
  data: { 
    islogs: false, 
    //手动输入 
    FaceSNinput: 0, 
     //手动输入 
     input: 0, 
    //显示 0 全部 1 主机 2 人脸机 
    showinfo:0, 
    //帮助 
    Help: false, 
    //弹窗 
    modal: 0, 
    //房间数据 
    HostsData: null, 
    //过滤后房间数据 
    HostsDataFilters: null, 
    //酒店信息 
    Hotelinfo: null, 
    //是否返回 只有一个酒店不能返回 
    isback: true, 
    //已经绑定是数量 
    YMac: 0, 
    //未绑定是数量 
    NMac: 0, 
    //筛选按钮的值 
    sel: 0, 
    //权限信息 
    autho: null, 
    //选择的房间信息 
    selHosts: null, 
    //扫描的条形码 
    code: null, 
    //swview高度 
    top_height: 0, 
    top_Nheight: 0, 
    //本次操作的状态数据 
    statusdata: [0, 0, 0, 0], 
    //mac绑定的酒店 服务器获取 
    bdHosts:[], 
    //房型信息
    roomtype:[], 
    //升级状态
    Upgradestatus:"",
    UpgradestatusTimeout:"",
    UpgradestatusTimeout2:"",
    UpgradestIstrue:true,
    Upgradenode:[],
    //房间信息
    roomtypeInfo:[],
    //房间回路信息
    roomtypeInfoNode:[],
    roomtypeInfoNodeinfo:[],
 
    ISLoopDebugging:0,
    // 播放音量
    VolumeLevel:30,
        
    roomGfilename:"",
    roomPfilename:"",
  }, 
 // 监听单个字段


 observersUpgradestatus: function() {   
      
      let Upgradestatus=this.data.Upgradestatus  
      let UpgradestatusTimeout2=this.data.UpgradestatusTimeout2
        if (Upgradestatus=="升级就绪"||Upgradestatus[0]=='.'||Upgradestatus[Upgradestatus.length-1]=="%") {    
          
          if (UpgradestatusTimeout2>0) {
             this.setData({
        UpgradestatusTimeout:UpgradestatusTimeout2
      })
      this.observersUpgradestatusTimeout()
          }
     
    } 

  },
  observersUpgradestatusTimeout:async function () {
    let  _this =this
    let Upgradestatus=this.data.Upgradestatus  
    var timestampSec = Math.floor(Date.now() / 1000);
    var UpgradestatusTimeout=this.data.UpgradestatusTimeout
    if ((timestampSec-UpgradestatusTimeout) >120) {
      _this.setData({
        Upgradestatus:"升级超时!",
        UpgradestatusTimeout2:0
      })
        
    }else{

   
      setTimeout(async function ()  {
        let UpgradestIstrue =_this.data.UpgradestIstrue
        let selHosts =_this.data.selHosts
        let ID =selHosts.HotelID       
        let bID =selHosts.Id
      let  Upgradenode=_this.data.Upgradenode
        let RoomTypeID = selHosts.RoomTypeID
        let dastr =_this.data.Upgradestatus
        let Version =Upgradenode.CFG_CURR_VER + ".0.0"
       let str= Upgradenode.App_Cfg_For_L4
       var getnode 
        //let gVersion =  str.split('_')[0]+"_"+ str.split('_')[1]+"_"+ str.split('_')[2]+"_"+ str.split('_')[3]+"_"+str.split('_')[4]
        if (dastr=="升级就绪") {
          dastr=''
        }
        if (dastr[dastr.length-1]=="%") {
          dastr=''
        }
        if (dastr.length>6) {
          dastr='.'
        }else{
          dastr=dastr+'.'
        }

        if (UpgradestIstrue ==true){
         await QueryUpdateHostStatus({
            hotelid:ID,
            roomTypeID:RoomTypeID
          }).then(res => {     
            if (res.total ==1) {
             
              if (res.rows.length>0) {
                getnode=res.rows[0]
               //配置
                    if (getnode.ConfigVersion==Version) {
                  _this.setData({ 
                    Upgradestatus:'升级完成！',
                    UpgradestatusTimeout2:0
                  }) 
                
                }  else{             
                  _this.setData({ 
                    Upgradestatus:dastr,
                    UpgradestatusTimeout2:timestampSec
                  })  
                }
  
              
  
              }else
              {
                _this.setData({ 
                Upgradestatus:dastr
              })  
              }
  
            } else{
              _this.setData({ 
                Upgradestatus:"服务器反馈设备升级失败！",
                UpgradestatusTimeout2:0
              })  
            }
            
          }, err => { 
            _this.setData({ 
              Upgradestatus:"服务器接口调用异常，设备升级失败！",
              UpgradestatusTimeout2:0
            })  
          }).catch(err => { 
            _this.setData({ 
              Upgradestatus:"服务器接口调用异常，设备升级失败！",
              UpgradestatusTimeout2:0
            })  
          });
        }else{
       
          await ForwardQueryUpdateHostProgressBar({
            hostIDList:'['+bID+']'
           
          }).then(res => {     
            if (res.IsSuccess ==true) {
              
              if (res.Response.length>0) {
                getnode=res.Response[0]
               
                  if (getnode.BaiFenBi=="100%") {
                    _this.setData({ 
                      Upgradestatus:'升级完成！',
                      UpgradestatusTimeout2:0
                    }) 
                  
                  }  else{   
                    if (getnode.BaiFenBi.length>0) {
                       _this.setData({ 
                      Upgradestatus:getnode.BaiFenBi,
                      UpgradestatusTimeout2:timestampSec
                    })  
                    }    else{
                      _this.setData({ 
                        Upgradestatus:dastr,
                        UpgradestatusTimeout2:timestampSec
                      })  
                    }      
                   
                  }
          
              
  
              }else
              {
                _this.setData({ 
                Upgradestatus:dastr
              })  
              }
  
            } else{
              _this.setData({ 
                Upgradestatus:"服务器反馈设备升级失败！",
                UpgradestatusTimeout2:0
              })  
            }
            
          }, err => { 
            _this.setData({ 
              Upgradestatus:"服务器接口调用异常，设备升级失败！",
              UpgradestatusTimeout2:0
            })  
          }).catch(err => { 
            _this.setData({ 
              Upgradestatus:"服务器接口调用异常，设备升级失败！",
              UpgradestatusTimeout2:0
            })  
          });
        }     
        _this.observersUpgradestatus()

      }, 1000)

        //定时询问
       
    }
  },
  changeVolumeLevel(e)
  {
   
    let VolumeLevel =e.detail.value
      console.log(e)
      this.setData({
        VolumeLevel:VolumeLevel
      })
  },
 
  GetFaceSN_long:function (params) { 
    if (!this.CheckFaceSNAutho()) { 
      app.toast(2, "无绑定权限~") 
      return; 
    } 
    let index = params.currentTarget.dataset['index'] 
    // console.log(index) 
    let selHosts = this.data.HostsDataFilters[index]; 
    selHosts.index = index; 
    this.setData({ 
      selHosts: selHosts, 
      FaceSNinput: 100 
    }) 
    if (this.data.HostsDataFilters[index].FaceSN != "" && this.data.HostsDataFilters[index].FaceSN != null) { 
      this.setData({ 
        modal: -1, 
        message: [ this.data.HostsDataFilters[index].FaceSN,selHosts.RoomNumber] 
      }) 
    } else { 
      this.ShowInputsn(); 
    } 
  }, 
  /// 解绑sn  
  JbSn:function(params) { 
    let jbjd = null; 
    let faceSN = null; 
    let that = this; 
    let index  = -1; 
    //debugger 
    if( typeof params.currentTarget.dataset['index'] != 'undefined'){ 
      faceSN = this.data.code; 
     index = params.currentTarget.dataset['index'] 
    //解绑的房间 
    jbjd = this.data.bdHosts[index]; 
        // 0 表示绑定成功~ 
          // 1 表示绑定失败~ 
          // 2 表示取消绑定~ 
    // xg  
  }else{ 
    jbjd = this.data.selHosts; 
    faceSN = this.data.selHosts.FaceSN; 
  } 
  console.log(jbjd) 

    GetFaceSN({faceSN:faceSN,roomID:jbjd.Id,roomNumber:jbjd.RoomNumber,faceAddress:this.data.address,HotelID:jbjd.HotelID,isjb:true}).then( 
      res => { 
        if (res.Status == 200) { 
      switch (res.Data) { 
        case 0: 
          try { 
            app.toast(1, "解绑成功~"); 
            let data = that.data.HostsData; 
            let OLD = -1; 
            try { 
            data.forEach( 
              (x, INDEX) => { 
                if (x.RoomNumber ===  jbjd.RoomNumber) { 
                  OLD = INDEX; 
                  throw new Error(); 
                } 
              } 
            )} catch (error) { 
            } 
            if (OLD >= 0) { 
              // 0 表示绑定成功~ 
              // 1 表示绑定失败~ 
              // 2 表示取消绑定~ 
              data[OLD].xg = 2; 
              data[OLD].FaceSN = ""; 
            } 
            let res = that.GetFilters(that.data.sel, data); 
            let databdHosts = that.data.bdHosts; 
            let selHosts = that.data.selHosts; 
          // 表示 是查询到 sn被绑定 index>-1   ==-1 表示是长安解绑 
          if(index>-1){ 
        databdHosts.splice(index,1); 
      }else{ 
        selHosts.FaceSN = null 
      } 
          that.setData({ 
            selHosts:selHosts, 
          HostsData: data, 
          bdHosts:databdHosts, 
          HostsDataFilters: res[0], 
          statusdata: res[1],  
          input: 0 
        }) 
          } catch (error) { 
            console.log(error) 
          } 
          break; 
      case 1: 
        app.toast(2, "SN已经绑定酒店~") 
        break; 
        case 2: 
        app.toast(2, "SN绑定酒店失败~") 
        break; 
        case 3: 
        app.toast(2, "SN注册绑定酒店失败~") 
        break; 
        case 4: 
        app.toast(2, "未知错误~") 
        break; 
        case 5: 
          app.toast(2, "数据不符合~") 
          break; 
          case 6: 
            app.toast(2, "解绑失败~") 
            break; 
        default: 
          app.toast(2, "其他错误~") 
          break; 
      } 
        /// 0 成功 
        /// 1 已经注册已经绑定酒店   
        /// 2 已经注册更新失败  
        /// 3 未注册为分配酒店  添加注册 添加酒店是啊比 
        /// 4 未能预计的结果-- 
        /// 5 数据不符合 
        /// 6 解绑失败 
        console.log(0) 
        
       } 
        else{ 
        app.toast(2, "网络繁忙") 
        } 
      }, 
      err => { 
        app.toast(2, "网络繁忙") 
      } 
      ).catch(err => { 
      app.toast(2, "网络繁忙") 
    }); 
  }, 
  CheckFaceMAC:function(vlues){ 
    return true; 
    console.log(vlues.length != 16) 
    return vlues.length == 16; 
  }, 
  SetDeviceSwitchStatus(e){
    let devarr=e.target.dataset.index
    let devval=parseInt(e.target.dataset.value)
    let ID=parseInt(e.target.id)
    let type =e.target.dataset.type
   debugger
   this.SetDevStartToHostMachine(ID,devarr,devval,type)
    console.log(e)
    
  },
  SetDeviceSwitchStatusslider(e){
    let devarr=e.target.dataset.index
    let devval=parseInt(e.detail.value)
    let ID=parseInt(e.target.id)
    
   this.SetDevStartToHostMachine(ID,devarr,devval,0)
    console.log(e)

  },
  SetDevStartToHostMachine: async function (id,devarr,Handletype,type){
    let roomtypeInfoNodeinfo=this.data.roomtypeInfoNodeinfo
    let narry=[]
    for (let index = 0; index < roomtypeInfoNodeinfo.length; index++) {
      const element = roomtypeInfoNodeinfo[index];
      if (element[0]===id) {
        for (let nindex = 0; nindex < element[1].length; nindex++) {
          const nelement = element[1][nindex];
          if (nelement[0]===devarr) {
            narry =this.SetloopDataChange(id,nelement[2] ,Handletype,type)
            let iset =await this.ControlStatusMainCircuit(id,narry,devarr)
            if (iset) {
              roomtypeInfoNodeinfo[index][1][nindex][2]=narry    
              this.setData({
                roomtypeInfoNodeinfo:roomtypeInfoNodeinfo
              })
            }
          
            
            return 
          }          
        }
        return
      }
    }
  },
  SetloopDataChange(id, dataarry,Handletype,type){
 
    let result =[]
    switch (id) {
      case 1:
        if (dataarry[0][2]==1) {
          dataarry[0][2]=0
        }else
        {
          dataarry[0][2]=1
        }
        result=dataarry
        break;
        case 23: 
        case 5:        
            dataarry[0][2]=Handletype
            result=dataarry
                  break;
        case 52:
          let devval=parseInt(type)    
          if (devval==1) {
            if (  dataarry[devval-1][2]==1) {
              dataarry[devval-1][2]=0
            result=dataarry
            }else{
              dataarry[devval-1][2]=1
              result=dataarry
            }
            
          }else{
             dataarry[devval-1][2]=Handletype
             result=dataarry
          }
        
          break;
          case 7:
            let bevval=parseInt(type)
            switch (bevval) {
              case 1:
                if (  dataarry[bevval-1][2]==1) {
                  dataarry[bevval-1][2]=0
                result=dataarry
                }else{
                  dataarry[bevval-1][2]=1
                  result=dataarry
                }
                break;
                case 3:
                case 2:
                  if (dataarry[bevval-1][2]==4) {  //制冷 制热 送风 自动
                    dataarry[bevval-1][2]=1
                  }else{
                    dataarry[bevval-1][2]= dataarry[bevval-1][2]+1
                  }
                
                  break;
                
                    case 4: //-
                      if (dataarry[bevval-1][2]==16) {
                        break;
                      }else{
                        dataarry[bevval-1][2]=dataarry[bevval-1][2]-1
                      }
                      break
                      case 5: //+
                    
                      if (dataarry[bevval-2][2]==32) {
                        break;
                      }else{
                        dataarry[bevval-2][2]=dataarry[bevval-2][2]+1
                      }

                      break;
            
              default:
                break;
            }

          // bint.push([7,[[1,'开关',0],[2,'模式',0],[3,'风速',0],[4,'温度',25],[5,'阀开',0]]])
          result=dataarry
          break;
      default:
        break;
    }
    return result
  },

  ControlStatusMainCircuit:async function (id, dataarry,addr){
    let HostsDataFilters =this.data.HostsDataFilters
    let selHosts =this.data.selHosts
    let  Hotelinfo=this.data.Hotelinfo
    let  timestr = HostsDataFilters[0].CreateTime
    console.log(timestr)
  
    let timestamp = parseInt(timestr.match(/\d+/)[0]);
    let date = new Date(timestamp);
    
    // 格式化输出（示例：YYYY-MM-DD HH:mm:ss）
    let year = date.getFullYear();
    let month = (date.getMonth() + 1).toString().padStart(2, '0');
    let day = date.getDate().toString().padStart(2, '0');  
    let CreateTime = `${year}-${month}-${day}`
    let res=[]
    let sw =dataarry[0][2]
   
    switch (id) {
      case 1:
        sw= sw==1 ? 1:2
        res =  await SetRCULight({ 
          roomNumber:selHosts.RoomNumber,
          code:Hotelinfo.Code,
          creatDate:CreateTime,
          status: sw,
          modalAddress:addr,
          brightness:0
        })
        break;
       
   
      case 5:
        res =  await SetRCUCurtain({
          roomNumber:selHosts.RoomNumber,
          code:Hotelinfo.Code,
          creatDate:CreateTime,
          modalAddress:addr,
          status:sw
        })
        break
        case 7:
         
          res =  await SetRCUAir({
            roomNumber:selHosts.RoomNumber,
            code:Hotelinfo.Code,
            creatDate:CreateTime,
            modalAddress:addr,
            onOff:sw,
            temperature:dataarry[3][2],
            fanSpeed:dataarry[2][2]==4? 0:dataarry[2][2],
            mode:dataarry[1][2]==4? 0:dataarry[1][2],
            valve:1
          })
          break
          case 23:
            res =  await SetRCULight({ 
              roomNumber:selHosts.RoomNumber,
              code:Hotelinfo.Code,
              creatDate:CreateTime,
              status: sw==0 ? 2:1,
              modalAddress:addr,
              brightness:sw
            })
            break;
      default:
        return false
        break;
    }
 
  if (res.IsSuccess==true) {
    return true
  }
  return false
 
  },
  GetFaceSNend:function(){ 
    this.GetHide(); 
    let that = this; 
    let xg = 1; 
    GetFaceSN({faceSN:this.data.code, roomID:this.data.selHosts.Id,roomNumber:this.data.selHosts.RoomNumber,faceAddress:this.data.address,HotelID:this.data.Hotelinfo.HotelId}).then( 
      res => { 
        if (res.Status == 200) { 
      switch (res.Data) { 
        case 0: 
          app.toast(1, "绑定成功~"); 
          xg  = 0; 
          break; 
      case 1: 
        app.toast(2, "SN已经绑定酒店~"); 
        break; 
        case 2: 
          xg  = 1; 
        app.toast(2, "SN绑定酒店失败~"); 
        break; 
        case 3: 
        app.toast(2, "SN注册绑定酒店失败~"); 
        break; 
        case 4: 
        app.toast(2, "未知错误~"); 
        break; 
        case 5: 
          app.toast(2, "数据不符合~"); 
          break; 
          case 6: 
            app.toast(2, "解绑失败~"); 
            break; 
        default: 
          app.toast(2, "其他错误~"); 
          break; 
      } 
 
        
        /// 0 成功 
        /// 1 已经注册已经绑定酒店   
        /// 2 已经注册更新失败  
        /// 3 未注册为分配酒店  添加注册 添加酒店是啊比 
        /// 4 未能预计的结果-- 
        /// 5 数据不符合 
        /// 6 解绑失败 
        try { 
          
        
        that.data.selHosts.xg = xg; 
        if(xg==0){ 
          that.data.selHosts.FaceSN = this.data.code; 
        } 
          let data = that.data.HostsData; 
          data[that.data.selHosts.index] = that.data.selHosts; 
          let res = that.GetFilters(that.data.sel, that.data.HostsData); 
        that.setData({ 
        HostsData: data, 
        HostsDataFilters: res[0], 
        statusdata: res[1], 
        code: null, 
        input: 0 
        }) 
      } catch (error) { 
          console.log(error) 
      } 
       } 
        else{ 
        app.toast(2, "网络繁忙") 
        } 
      }, 
      err => { 
        app.toast(2, "网络繁忙") 
      } 
      ).catch(err => { 
      app.toast(2, "网络繁忙") 
    }); 
  }, 
  CheckFaceMACWL(){ 
    let that = this; 
    CheckFaceSN({faceSN:this.data.code}).then( 
      res => { 
        if (res.Status == 200) { 
       if(res.Data<=0){    
        that.setData({ 
          modal:-521, 
        }) 
       }else{ 
        let remove = []; 
        let bdHosts = res.Data; 
        try { 
          //记录已经分配酒店但是未分配房间 且酒店是当前酒店  那就判断为没有绑定 
          that.data.autho.forEach((element, index) => { 
            element.Hotels.forEach((elements, indexs) => { 
             for (let index = 0; index < bdHosts.length; index++) { 
                if (elements.HotelId == bdHosts[index].HotelID) { 
                  if(bdHosts[index].HotelID == that.data.Hotelinfo.HotelId && bdHosts[index].Id==0){ 
                    remove.push(index); 
                  } 
                  elements.Auth.forEach (Auth=>{ 
                    if(Auth.AuthorityId == 21 && Auth.AuthotypeId == 3){ 
                      //有权限 
                      bdHosts[index].qx = 0; 
                    } 
                  })  
                } 
             } 
            }) 
          }); 
        } catch (error) { 
          console.log(error) 
        } 
        remove.forEach (x=>{ 
          bdHosts.splice(x, 1); 
        })  
        let modalval = -200; 
        if(bdHosts.length<=0){ 
          modalval = -521; 
        } 
        that.setData({ 
          modal:modalval, 
          bdHosts:bdHosts 
        }) 
        // app.toast(2, "已经被绑定") 
       } 
        }else{ 
        app.toast(2, "网络繁忙") 
        } 
      }, 
      err => { 
        console.log(err) 
        app.toast(2, "网络繁忙") 
      }).catch(err => { 
        console.log(err) 
      app.toast(2, "网络繁忙") 
    }); 
  }, 
  GetFaceSNOK:function(){ 
    let that = this; 
    if (!this.CheckFaceMAC(that.data.code)) { 
      this.setData({ 
        modal: 520 
      }) 
      return; 
    }; 
    if (that.data.selHosts.FaceSN == that.data.code) { 
      app.toast(2, "条码一致，无需更改~") 
      return; 
    } 
    this.CheckFaceMACWL() 
  }, 
  //GetFaceCode 人脸机扫码 
  GetFaceCode:function(){ 
    var that = this; 
    setTimeout(function () { 
      that.GetHide() 
    }, 100); 
    wx.scanCode({ 
      // onlyFromCamera: true,// 只允许从相机扫码 
      success(res) { 
        // 扫码成功后  在此处理接下来的逻辑 
        that.setData({ 
          code: res.result 
        }) 
        that.GetFaceSNOK(); 
      }, 
      fail(err) { 
        app.toast(2, "未识别到有效条形码") 
      } 
    }) 
  }, 
  //检查人脸机房间权限 
  CheckFaceSNAutho: function () { 
    let res = false; 
   this.data.Hotelinfo.Auth.forEach(x=>{ 
     if(x.AuthorityId==21 && x.AuthotypeId == 3){ 
       res = true; 
     } 
    }); 
    return res; 
  }, 
// 点击人脸机 
  GetFaceSN:function (params) { 
     //长按事件   
     if (this.endTime - this.startTime > 350) { 
      return; 
    } 
    if (!this.CheckFaceSNAutho()) { 
      app.toast(2, "无绑定权限~") 
      return; 
    } 
    let index = params.currentTarget.dataset['index'] 
    // console.log(index) 
    let selHosts = this.data.HostsDataFilters[index]; 
    selHosts.index = index; 
    this.setData({ 
      selHosts: selHosts, 
      FaceSNinput: 0 
    }) 
    if (this.data.HostsDataFilters[index].FaceSN != "" && this.data.HostsDataFilters[index].FaceSN != null) { 
      this.setData({ 
        modal:-1, 
        message: [this.data.HostsDataFilters[index].FaceSN, selHosts.RoomNumber] 
      }) 
    } else { 
      this.GetFaceCode() 
    } 
 
  }, 
//人脸机测试 
testinfo:function(e){ 
// console.log(e.currentTarget.id) 
var jbjd=this.data.selHosts 
// console.log(jbjd) 
wx.navigateTo({ 
  url: '/pages/test/test?Hotelinfo=' + e.currentTarget.id+'&RoomID='+jbjd.Id+'&faceadd='+this.data.address 
}) 
}, 
 
//开门测试 
OpenDoor:function(e){ 
  var that=this; 
  console.log(e.currentTarget.id) 
  var sn=e.currentTarget.id.split("_") 
  console.log(sn) 
  OpenDoorTest({faceSN:sn[2],isjb:true}).then( 
    res => { 
      if (res.Status == 200) { 
        app.toast(2, res.Message) 
     } 
      else{ 
      app.toast(2, res.Message) 
      } 
    }, 
    err => { 
      app.toast(2, "网络繁忙") 
    } 
    ).catch(err => { 
    app.toast(2, "网络繁忙") 
  }); 
  }, 
 
 
 
  //检查房间权限 
  CheckAutho: function () { 
    let res = false; 
    this.data.Hotelinfo.Auth.forEach(x=>{ 
     if(x.AuthorityId==16 && x.AuthotypeId == 3){ 
       res = true; 
     } 
    }); 
    return res; 
  }, 
  //touch start 开始触摸房间区域 
  handleTouchStart: function (e) { 
    this.startTime = e.timeStamp; 
    //console.log(" startTime = " + e.timeStamp);   
  }, 
  //touch end结束触摸房间区域 
  handleTouchEnd: function (e) { 
    this.endTime = e.timeStamp; 
    //console.log(" endTime = " + e.timeStamp);   
  }, 
  // 帮助 
  HelpClick: function (params) { 
    this.setData({ 
      islogs: false, 
      Help: !this.data.Help 
    }) 
  }, 
  //日志信息 
  islogsClick: function (params) { 
    this.setData({ 
      islogs: !this.data.islogs, 
      Help: false 
    }) 
  }, 
  // 长按房间 
  GetMAC_long: function (params) { 
    if (!this.CheckAutho()) { 
      app.toast(2, "无绑定权限~") 
      return; 
    } 
    let index = params.currentTarget.dataset['index'] 
    // console.log(index) 
    let selHosts = this.data.HostsDataFilters[index]; 
    selHosts.index = index; 
    this.setData({ 
      selHosts: selHosts, 
      input: 100 
    }) 
    if (this.data.HostsDataFilters[index].MAC != "" && this.data.HostsDataFilters[index].MAC != null) { 
      this.setData({ 
        modal: 1, 
        message: [selHosts.RoomNumber, this.data.HostsDataFilters[index].MAC] 
      }) 
    } else { 
      this.ShowInput(); 
    } 
  }, 
  // 手动输入mac 
  ShowInput: function (params) { 
    this.setData({ 
      modal: 1000, 
      code:"" 
    }) 
  }, 
   // 手动输入sn 
   ShowInputsn: function (params) { 
    this.setData({ 
      modal: -1000, 
      code:"" 
    }) 
  }, 
  //解绑MAC 
  Jb:async function(params) { 
   let index = params.currentTarget.dataset['index'] 
   //解绑的酒店 
   let jbjd = this.data.bdHosts[index]; 
  //  this.GetMacOKend(false); 
   let that = this; 
   await GetMAC({ 
    roomNumber: jbjd.RoomNumber, 
    roomID: jbjd.Id, 
    HotelID: jbjd.HotelID, 
    MAC: "", 
    NoCheck: false, 
    loc: that.data.address 
  }).then( 
    res => { 
      if (res.Status == 1000) { 
        app.toast(2, "无权限") 
      } 
      if (res.Status == 200) { 
        app.toast(1, "解绑成功") 
        var databdHosts = that.data.bdHosts; 
        databdHosts.splice(index,1); 
        that.setData({ 
          bdHosts:databdHosts 
        }) 
        //如果酒店是当前酒店 就把当前酒店的房间 标记为解绑 
        if(jbjd.HotelID != that.data.HotelId) 
        { 
          // console.log(jbjd.HotelID) 
          // console.log(that.data.HotelId) 
          return; 
        } 
        let data = that.data.HostsData; 
        let OLD = -1; 
        try { 
        data.forEach( 
          (x, INDEX) => { 
            if (x.RoomNumber ===  jbjd.RoomNumber) { 
              OLD = INDEX; 
              throw new Error(); 
            } 
          } 
        )} catch (error) { 
        } 
        if (OLD >= 0) { 
          // 0 表示绑定成功~ 
          // 1 表示绑定失败~ 
          // 2 表示取消绑定~ 
          data[OLD].xg = 2; 
          data[OLD].MAC = ""; 
        } 
        let res = that.GetFilters(that.data.sel, data); 
        that.setData({ 
          HostsData: data, 
          HostsDataFilters: res[0], 
          statusdata: res[1] 
        }) 
        console.log(data[OLD]) 
      } else { 
          app.toast(2, "解绑失败") 
      } 
    }, 
    err => { 
      app.toast(2, "网络繁忙") 
    }).catch(err => { 
    app.toast(2, "网络繁忙") 
  }); 
  }, 

  FuzzyMatch(astr,bstr  ){
    if (astr.includes(bstr)) {
      return true
    }else{
      return false
    }
  },


  //检查mac地址 
  GetMACOK: function () { 
    let that = this; 
    if (!this.CheckMAC(that.data.code)) { 
      this.setData({ 
        modal: 520 
      }) 
      return; 
    }; 
    var newmac = ""; 
    for (var i = 0; i < that.data.code.length; i += 2) { 
      if (i + 2 >= that.data.code.length) { 
        newmac += that.data.code[i] + that.data.code[i + 1]; 
      } else { 
        newmac += that.data.code[i] + that.data.code[i + 1] + "-"; 
      } 
    } 
    if (that.data.selHosts.MAC == newmac) { 
      app.toast(2, "条码一致，无需更改~") 
      return; 
    } 
    this.setData({ 
      modal: 521, 
    }) 
  }, 
  //最终绑定MAC 
  GetMacOKend: async function (type) { 
    let that = this; 
    if (type != true && type != false) { 
      type = type.currentTarget.dataset['type'] 
    } 
    this.GetHide(); 
    let xg = null; 
    await GetMAC({ 
      roomNumber: that.data.selHosts.RoomNumber, 
      HotelID: that.data.selHosts.HotelID, 
      MAC: that.data.code, 
      NoCheck: type, 
      loc: that.data.address 
    }).then( 
      res => { 
        if (res.Status == 1000) { 
          xg = 100; 
          app.toast(2, "无权限") 
        } 
        if (res.Status == 200) { 
          xg = 0; 
          app.toast(1, "绑定成功") 
        } else { 
          if (!type) { 
            xg = 1; 
            app.toast(2, "绑定失败") 
          } else { 
            try { 
              if (res.Status == 100) { 
                xg = 100; 
                let modal = 3; 
                let mesg = [that.data.code]; 
                //mac绑定的房间 
                let bdHosts = res.Data.Hosts; 
                try { 
                  that.data.autho.forEach((element, index) => { 
                    element.Hotels.forEach((elements, indexs) => { 
                     for (let index = 0; index < res.Data.Hosts.length; index++) { 
                        if (elements.HotelId == res.Data.Hosts[index].HotelID) { 
                            elements.Auth.forEach (Auth=>{ 
                              if(Auth.AuthorityId == 16 && Auth.AuthotypeId == 3){ 
                                //有权限 
                                bdHosts[index].qx = 0; 
                              } 
                            })  
                        } 
                     } 
                    }) 
                  }); 
                } catch (error) { 
                  console.log(error) 
                } 
                that.setData({ 
                  modal: modal, 
                  bdHosts:bdHosts, 
                  message: mesg 
                }) 
              } else { 
                if (res.Status == 150) { 
                  xg = 1; 
                  app.toast(2, "绑定失败") 
                } else { 
                  xg = 100; 
                  app.toast(2, "网络繁忙") 
                } 
              } 
            } catch (error) { 
              xg = 100; 
              console.log(error) 
            } 
          } 
        } 
      }, 
      err => { 
        xg = 100; 
        app.toast(2, "网络繁忙") 
      }).catch(err => { 
      xg = 100; 
      app.toast(2, "网络繁忙") 
    }); 
    try { 
      // 100表示检查MAC并没有执行绑定操作  或者  请求过程出错   不执行下面的操作 
      if (xg == 100) { 
        return; 
      } 
      //标记修改 
      that.data.selHosts.xg = xg; 
       
      // return; 
      var newmac = ""; 
      for (var i = 0; i < that.data.code.length; i += 2) { 
        if (i + 2 >= that.data.code.length) { 
          newmac += that.data.code[i] + that.data.code[i + 1]; 
        } else { 
          newmac += that.data.code[i] + that.data.code[i + 1] + "-"; 
        } 
      } 
      that.data.selHosts.MAC = newmac; 
      let data = that.data.HostsData; 
      // 本房间有相同的 mac的房间标记为取消绑定   已经弃用了 
      // let OLD = -1; 
      // try { 
      //   data.forEach( 
      //     (x, INDEX) => { 
      //       if (x.MAC == newmac && that.data.selHosts.Id != x.Id) { 
      //         OLD = INDEX; 
      //         throw new Error(); 
      //       } 
      //     } 
      //   ) 
      // } catch (error) { 
      //   console.log("房间 已经找到，无需循环~") 
      // } 
      // if (OLD >= 0) { 
      //   // 0 表示绑定成功~ 
      //   // 1 表示绑定失败~ 
      //   // 2 表示取消绑定~ 
      //   data[OLD].xg = 2; 
      //   data[OLD].MAC = ""; 
      // } 
      data[that.data.selHosts.index] = that.data.selHosts; 
      let res = that.GetFilters(that.data.sel, that.data.HostsData); 
      that.setData({ 
        HostsData: data, 
        HostsDataFilters: res[0], 
        statusdata: res[1], 
        code: null, 
        input: 0 
      }) 
    } catch (error) { 
      console.log(error) 
    } 
  }, 
  //检查Mac 
  CheckMAC: function (vlues) { 
    return (vlues.indexOf("34D0B8") == 0 && vlues.length == 12  && vlues.indexOf(" ") < 0); 
  }, 
  //扫码~ 
  GetCode: async function () { 
    var that = this; 
    setTimeout(function () { 
      that.GetHide() 
    }, 100); 
    wx.scanCode({ 
      // onlyFromCamera: true,// 只允许从相机扫码 
      success(res) { 
        // 扫码成功后  在此处理接下来的逻辑 
        that.setData({ 
          code: res.result 
        }) 
        that.GetMACOK(); 
      }, 
      fail(err) { 
        app.toast(2, "未识别到有效条形码") 
      } 
    }) 
  }, 
  //隐藏提示~ 
  GetHide() { 
    this.setData({ 
      modal: 0, 
      input: 0, 
      FaceSNinput:0 ,
      Upgradestatus:"",
      UpgradestatusTimeout2:0,
      ISLoopDebugging:0,
    }) 
  }, 
  GetReturnSet() { 
    this.setData({ 
     
      Upgradestatus:"",
      UpgradestatusTimeout2:0,
      ISLoopDebugging:0,
    }) 
  }, 
  // 房间点击事件 
   GetMAC:async function (e) { 
    let roomtypeInfo=this.data.roomtypeInfo
    let index = e.currentTarget.dataset['index'] 
    // console.log(index) 
    let selHosts = this.data.HostsDataFilters[index]; 

    for (let index = 0; index < roomtypeInfo.length; index++) {
      const element = roomtypeInfo[index];
      if (selHosts.RoomTypeID==element.ID) {
        this.setData({ 
          roomtypeInfoNode: element         
        }) 
        break
      }
    }

  let Gfilename="未知固件"
  let Pfilename="未知配置"
  await QueryUpdateHostStatus({
    hotelid:selHosts.HotelID,
    roomTypeID:selHosts.RoomTypeID
  }).then(res => {     
    if (res.total ==1) {
     
      if (res.rows.length>0) {   
        Gfilename=res.rows[0].Version
        Pfilename=res.rows[0].ConfigVersion
      }
    }     
  })
 debugger
    //长按事件   
    if (this.endTime - this.startTime > 350) { 
      return; 
    } 
    if (!this.CheckAutho()) { 
      app.toast(2, "无绑定权限~") 
      return; 
    } 
    // let index = e.currentTarget.dataset['index'] 
    // // console.log(index) 
    // let selHosts = this.data.HostsDataFilters[index]; 
    selHosts.index = index; 
    this.setData({ 
      selHosts: selHosts, 
      input: 0 ,
      roomGfilename:Gfilename,
      roomPfilename:Pfilename

    }) 
    if (this.data.HostsDataFilters[index].MAC != "" && this.data.HostsDataFilters[index].MAC != null) { 
      this.setData({ 
        modal: 1, 
        message: [this.data.HostsDataFilters[index].MAC, selHosts.RoomNumber] 
      }) 
    } else { 
      this.GetCode() 
    } 
  }, 
  // 未分配max  
  GetMaxby(type = 0, arry = null) { 
    let y = 0; 
    let n = 0; 
    if (arry == null) { 
      arry = this.data.HostsData; 
    } 
    arry.forEach(x => { 
      if (x.MAC == "" || x.MAC == null) { 
        n++; 
      } else { 
        y++; 
      } 
    }) 
    if (type == 0) { 
      return y; 
    } 
    return n; 
  }, 
  //分类过滤方法 
  GetFilters(type = -1, arry = null) { 
    if (type == -1) { 
      type = this.data.sel 
    } 
    if (arry == null && this.data.HostsData != null) { 
      arry = this.data.HostsData; 
    } 
    if (arry == null) { 
      return; 
    } 
    let ok = 0; 
    let err = 0; 
    let no = 0; 
    let df = 0; 
    let res = []; 
    arry.forEach(x => { 
      switch (x.xg) { 
        case 0: 
          ok++; 
          break; 
        case 1: 
          err++; 
          break; 
        case 2: 
          no++; 
          break; 
        default: 
          df++; 
          break; 
      } 
      if (type == 0) { 
        res.push(x) 
      } else { 
        if (x.MAC == "" || x.MAC == null) { 
          if (type == 2) { 
            res.push(x) 
          } 
        } else { 
          if (type == 1) { 
            res.push(x) 
          } 
        } 
      } 
    }) 
    return [res, [ok, err, no, df]]; 
  }, 
   // 分类点击事件  
   GetshowinfoClick(e) { 
    
    

    let showinfo = e.currentTarget.dataset['index'] 
   this.setData({ 
    showinfo:showinfo 
    }) 
       
  }, 
GetRoomTypeList(){ 
 //debugger 
  GetHostsInfo({ 
    HotelID: that.data.Hotelinfo.HotelId 
  }).then(res =>{ 
    if (res.Status == 200) { 
      console.log('获取房型成功') 
    } 
    else{ 
      console.log('获取房型失败：'+that.data.Hotelinfo.HotelId) 
    } 
  }).catch(err => { 
    console.log('网络访问错误')     
    console.log(err)     
  }); 
}, 
 
  GetshowinfoClick1(e){ 
    let showinfo = e.currentTarget.dataset['index'] 
var that=this; 
that.setData({ 
     showinfo:showinfo 
     }) 
 
      GetHostsInfo({ 
      HotelID: that.data.Hotelinfo.HotelId 
    }).then(res => { 
  
      if (res.Status == 200) { 
        that.setData({ 
          HostsData: res.Data, 
          HostsDataFilters: res.Data, 
          isback: (app.globalData.autho.length > 1 || app.globalData.autho[0].Hotels.length > 1), 
          HotelId: that.data.Hotelinfo.HotelId, 
          statusdata: [0, 0, 0, 0], 
          YMac: this.GetMaxby(0, res.Data), 
          NMac: this.GetMaxby(1, res.Data) 
        }) 
        that.GetLOC(); 
      } else { 
 
        app.toast(2, res.Message || "网络繁忙") 
      } 
    }, err => { 
      console.log(err) 
      app.toast(2, "网络繁忙") 
    }).catch(err => { 
      console.log(err) 
 
      app.toast(2, "网络繁忙") 
    }); 
 
 
      
  }, 
 
 
 
 
  // 绑定筛选分类点击事件  
  GetClick(e) { 
    this.setData({ 
      islogs: false, 
      Help: false 
    }) 
    let index = e.currentTarget.dataset['index'] 
    let res = this.GetFilters(index, this.data.HostsData); 
    this.setData({ 
      sel: index, 
      HostsDataFilters: res[0], 
      statusdata: res[1] 
    }) 
  }, 
  /** 
   * 生命周期函数--监听页面加载 
   */ 
  onLoad: async function (options) { 
    if (!options.HotelId || app.globalData.autho == null) { 
      app.toast(2, "无酒店信息~") 
      return; 
    } 
 

    this.setData({ 
      autho: app.globalData.autho 
    }) 
    // console.log(this.data.autho) 
     
    try { 
      this.data.autho.forEach((element, index) => { 
        element.Hotels.forEach((elements, indexs) => { 
          if (elements.HotelId == options.HotelId) { 
            this.setData({ 
              Hotelinfo: elements 
            }) 
            throw new Error(); 
          } 
        }) 
      }); 
    } catch (error) { 
      console.log("已经找到，无需循环~") 
    } 
    let that = this; 
    setTimeout(function () { 
      // 1.使用wx.createSelectorQuery()查询到需要滚动到的元素位置 
      wx.createSelectorQuery().select('#scroll').boundingClientRect(res => { 
        // 2.使用wx.getSysTemInfo()获取设备及页面高度windowHeight（px） 
        wx.getSystemInfo({ 
          success(ress) { 
            that.setData({ 
              top_height: ress.windowHeight - res.top ,
              top_Nheight:ress.windowHeight - res.top-80
            }) 
          } 
        }) 
      }).exec(function (params) { 
        console.log(params) 
      }) 
    }, 100) 

    await GetHostsInfo({ 
      HotelID: this.data.Hotelinfo.HotelId 
    }).then(res => { 
  
      if (res.Status == 200) { 
        that.setData({ 
          HostsData: res.Data, 
          HostsDataFilters: res.Data, 
          isback: (app.globalData.autho.length > 1 || app.globalData.autho[0].Hotels.length > 1), 
          HotelId: options.HotelId, 
          statusdata: [0, 0, 0, res.Data.length], 
          YMac: this.GetMaxby(0, res.Data), 
          NMac: this.GetMaxby(1, res.Data) 
        }) 
        app.globalData.HotelId=options.HotelId 
      
         
        that.GetLOC(); 
      } else { 
 
        app.toast(2, res.Message || "网络繁忙") 
      } 
    }, err => { 
      console.log(err) 
      app.toast(2, "网络繁忙") 
    }).catch(err => { 
      console.log(err) 
 
      app.toast(2, "网络繁忙") 
    }); 
    console.log(app.globalData.HotelId) 

    await  GetRoomType({ 
      HotelID: this.data.Hotelinfo.HotelId 
    }).then(res => {      
      app.SetroontypeListindex(res) 
        that.setData({ 
        roomtype:app.globalData.roomIDName 
      })      
    }, err => { 
      console.log('GetRoomType error') 
    }).catch(err => { 
     
    }); 

    await GetRoomTypeAndModalsListLog({
      code:this.data.Hotelinfo.Code 
    }).then(res =>{
      if (res.IsSuccess==true) {
     
        that.setData({ 
          roomtypeInfo:res.Result
        })   
      }
    })


  }, 
  //页面卸载 
  onUnload: function name(params) { 
    let data = wx.getStorageSync("oldHotelinfo") || [] 
    let ok = false; 
    try { 
      for (let index = 0; index < data.length; index++) { 
        const element = data[index]; 
        if (element.key == this.data.Hotelinfo.HotelId) { 
          ok = true; 
          data[index].data = this.data.HostsData; 
          throw new Error(); 
        } 
      } 
    } catch (error) { 
      console.log('已经找到了') 
    } 
    if (!ok) { 
      data.push({ 
        key: this.data.Hotelinfo.HotelId, 
        data: this.data.HostsData 
      }) 
    } 
    try { 
      wx.setStorageSync('oldHotelinfo', data) 
    } catch (error) { 
      console.log(error) 
    } 

    // 获取页面栈 
    var pages = getCurrentPages(); 
    var currPage = pages[pages.length - 1]; // 当前页 
    var prevPage = pages[pages.length - 2]; // 上一个页面 
    prevPage.setData({ 
      issel: this.data.Hotelinfo.HotelId 
    }); 
  }, 
   LoopDebugging:async function (e)
  {
    // 
    let roomtypeInfoNode =this.data.roomtypeInfoNode
    let roomtypeInfoNodeinfo=this.data.roomtypeInfoNode.Modals
    let roomstart =false
    let addrtype
    const myMap =[]
   let li =[]
    let addrtypelist =true
  
   let message =this.data.message
    for (let index = 0; index < roomtypeInfoNodeinfo.length; index++) {
      const element = roomtypeInfoNodeinfo[index];
      addrtype=this.GetloopType(element.ModalAddress)   
      if (addrtype.length==0) {
        continue 
      }
      addrtypelist=true
      for (let index2 = 0; index2 < myMap.length; index2++) {
        const element2 = myMap[index2];
      
        if (  element2[0] == addrtype[0][0]) {
          li= myMap[index2][1]
          li.push([element.ModalAddress,element.Name,addrtype[0][1]])
          myMap[index2][1]=li
          addrtypelist=false
          break
        }
      }
      
      if (addrtypelist) {
        li=[]
        li.push([element.ModalAddress,element.Name,addrtype[0][1]])
        myMap.push([addrtype[0][0],li])
      }


    }

    roomtypeInfoNodeinfo=myMap.sort((a, b) => a[0] - b[0])
    //获取房间在线状态  roomstart
    console.log(roomtypeInfoNodeinfo)

     await GetRoomTypeNode({ 
      hotelid: this.data.Hotelinfo.HotelId ,
      roomTypeID:roomtypeInfoNode.ID
    }).then(res => {      
     if (res.IsSuccess== true) {
       for (let index = 0; index < res.HostData.length; index++) {
         const element =  res.HostData[index];
         if (element.RoomNumber == message[1]) {
          roomstart=element.Status
          break
         }
       }
     }
    })

    roomtypeInfoNode.roomstart=roomstart
 
    this.setData({ 
      ISLoopDebugging:1,
      roomtypeInfoNode:roomtypeInfoNode,
      roomtypeInfoNodeinfo:roomtypeInfoNodeinfo
    })
    console.log(this.data.roomtypeInfoNode)
  },
  Mathceil(number,tval){
   return Math.ceil(number,tval)
  },
 GetloopType(loopaddr){
   let astr =loopaddr[0]+loopaddr[1]+loopaddr[2]
   let aint =parseInt(astr,10)
   let bint =[]

  switch (aint) {
    case 1 :
    // case 4 :
    // case 54:
    bint.push([1,[[1,'开关',0]]])//开关
    break;
    case 5: //开关停   
    bint.push([5,[[1,'开关',0]]])
        break;
        case 7: //开关停 
    
        bint.push([7,[[1,'开关',0],[2,'模式',1],[3,'风速',1],[4,'温度',25],[5,'阀开',0]]])
            break;
    case 23 :
    case 24:
      bint.push([23,[[1,'开关',10]]])
          break;
    case 52:
           bint.push([52,[[1,'开关',0],[2,'亮度',10],[3,'色温',10]]])
            break;    
    default:
      
      break;
  }

  return  bint
 },

//固件升级
  ConfigurationUpgrade: async function(e){
   let _this=this
    wx.showModal({
      title: "提示",
      content: "是否进行固件升级！",
      success (res) {
        if (res.confirm) {
          console.log('固件升级')
          _this.setData({ 
            ISLoopDebugging:2,
          })
          let selHosts =_this.data.selHosts
          _this.Carryoutupgrade(false)
        } else if (res.cancel) {
         return
        }
      }
    })

    
  },
  
//配置升级
FirmwareUpgrade: async function (e){
  console.log('配置升级')



  let _this=this
    wx.showModal({
      title: "提示",
      content: "是否进行配置升级！",
      success (res) {
        if (res.confirm) {
          console.log('固件升级')
          _this.setData({ 
            ISLoopDebugging:2,
          })
          let selHosts =_this.data.selHosts
          _this.Carryoutupgrade(true)
        } else if (res.cancel) {
         return
        }
      }
    })



},
// 进行升级
Carryoutupgrade:async function (params) {
  
  let selHosts =this.data.selHosts
  let ID =selHosts.Id
  let RoomTypeID = selHosts.RoomTypeID
  let  roontypeList =app.globalData.roontypeList
  let Gfilename =""
  let Pfilename =""
  let Upgradenode =[]
  var timestampSec = Math.floor(Date.now() / 1000);
  for (let index = 0; index < roontypeList.length; index++) {
    const element = roontypeList[index];
    if (RoomTypeID==element.ROOM_TYPE_OLD_ID) {
      Upgradenode=element
      if (element.App_Cfg_For_L2.length>0) {
        Gfilename=element.App_Cfg_For_L2
      }
      if (element.App_Cfg_For_L4.length>0) {
        Gfilename=element.App_Cfg_For_L4
      }
    if (element.APPTYPE=="App_Cfg") {
      Pfilename=element.CONFIG_BIN
    }else{
      Pfilename=""
    }
  break
    }
  }
  Upgradenode.Gfilename=this.data.roomGfilename
  Upgradenode.Pfilename=this.data.roomPfilename
  // debugger
  // await QueryUpdateHostStatus({
  //   hotelid:selHosts.HotelID,
  //   roomTypeID:RoomTypeID
  // }).then(res => {     
  //   if (res.total ==1) {
     
  //     if (res.rows.length>0) {
   
  //       Upgradenode.Gfilename=res.rows[0].Version
  //       Upgradenode.Pfilename="配置版本："+res.rows[0].ConfigVersion
  //     }
  //   }     
  // })



  Upgradenode.App_Cfg_For_L4=Gfilename
  Gfilename=Gfilename.replace('.hex','.bin')
  if (params) {
    if (Pfilename.length>0) {
      await WebChatUpgrade({
        roomTypeID:RoomTypeID,
        hostidLists:'['+ID+']',
        upgradefileName:Pfilename
      }).then(res => {     
        if (res.IsSuccess ==true) {
          this.setData({ 
            Upgradestatus:'升级就绪',
            UpgradestIstrue:params,
            UpgradestatusTimeout2:timestampSec,
            Upgradenode:Upgradenode
          })   
          this.observersUpgradestatus()
        } else{
          this.setData({ 
            Upgradestatus:'服务器升级配置失败！'
          }) 
          this.DisplayPrompt('服务器升级配置失败！',1000)  
        }
        
      }, err => { 
        this.setData({ 
          Upgradestatus:'升级配置失败，服务器响应异常'
        }) 
        this.DisplayPrompt('升级配置失败，服务器响应异常',1000)  
      }).catch(err => { 
        this.setData({ 
          Upgradestatus:'升级配置失败，服务器响应异常'
        }) 
        this.DisplayPrompt('升级配置失败，服务器响应异常',1000)  
      });

    }else{
      this.setData({ 
        Upgradestatus:'升级配置失败！服务器未获取到配置！'
      })   
      this.DisplayPrompt('升级配置失败！服务器未获取到配置！',1000)
    }
  }else{
    if (Gfilename.length>0) {
      await WebChatUpgrade({
        roomTypeID:RoomTypeID,
        hostidLists:'['+ID+']',
        upgradefileName:Gfilename
      }).then(res => {     
        if (res.IsSuccess ==true) {
          this.setData({ 
            Upgradestatus:'升级就绪',
            UpgradestIstrue:params,
            UpgradestatusTimeout2:timestampSec,
            Upgradenode:Upgradenode
          })   
          this.observersUpgradestatus()
        } else{
          this.setData({ 
            Upgradestatus:'服务器升级固件失败！'
          }) 
          this.DisplayPrompt('服务器升级固件失败！',1000)  
        }
        
      }, err => { 
        this.setData({ 
          Upgradestatus:'升级固件失败，服务器响应异常'
        })   
  
        this.DisplayPrompt('升级固件失败，服务器响应异常',1000)  
      }).catch(err => { 
        this.setData({ 
          Upgradestatus:'升级固件失败，服务器响应异常'
        })   
  
        this.DisplayPrompt('升级固件失败，服务器响应异常',1000)  
      });
    }else
    {
      this.setData({ 
        Upgradestatus:"升级固件失败！！"
      })   

      this.DisplayPrompt('升级固件失败！！',1000)     
    }
  }

},
DisplayPrompt(tipstr, showtime)
{
  wx.showLoading({
    title: tipstr,
  })      
  setTimeout(function () {
    wx.hideLoading()
  }, showtime)
},

  // 反馈异常 
  ErrorInfo: async function (e) { 
    let type = e.currentTarget.dataset['type'] 
    let that = this; 
    await ErrorInfo({ 
      type: type, 
      MAC: this.data.selHosts.MAC, 
      roomNumber: this.data.selHosts.RoomNumber, 
      HotelID: this.data.selHosts.HotelID, 
    }).then(res => { 
      if (res.Status == 200) { 
        that.GetHide(); 
        app.globalData.userinfo.error.push({ 
          HostsId: that.data.selHosts.Id, 
          MAC: that.data.selHosts.MAC, 
          type: type 
        }); 
        app.toast(1, "反馈成功~") 
      } else { 
        app.toast(2, "反馈失败~") 
      } 
    }, err => { 
      app.toast(2, "反馈失败~") 
    }).catch((e) => { 
      app.toast(2, "反馈失败~") 
    }) 
  }, 
  // 微信api，获取经纬度 
  getFuzzyLocations() { 
    wx.getFuzzyLocation({ 
      type: 'wgs84', 
      success: this.updateLocation, 
      fail: (e) => { 
        console.log(e) 
      } 
    }) 
  }, 
  // 根据经纬度，设置数据 
  updateLocation(res) { 
    let { 
      latitude: lat, 
      longitude: lon 
    } = res 
    let data = { 
      lat, 
      lon 
    } 
    // this.setData(data) 
    this.getAddress(lat, lon) 
  }, 
  // 根据经纬度，逆地址解析 
  getAddress(lat, lon) { 
    // 在wx.request中，this指向wx.request，故无法setData，此处将this指向that 
    var that = this 
    let SIG = md5("/ws/geocoder/v1?key=" + app.globalData.MapKey + "&location=" + String(lat) + "," + String(lon) + app.globalData.MapSk) 
    wx.request({ 
      url: 'https://apis.map.qq.com/ws/geocoder/v1', 
      data: { 
        key: app.globalData.MapKey, 
        location: `${lat},${lon}`, 
        sig: SIG 
      }, 
      success(res) { 
        let result = res.data.result 
        // console.log(result) 
        // formatted_addresses.recommend是经过腾讯地图优化过的描述方式，更具人性化特点 
        let formatted_addresses = result.formatted_addresses.recommend 
        // 此处的that指向app 
        that.setData({ 
          address: formatted_addresses 
        }) 
      }, 
      fail: (e) => { 
        console.log(e) 
      } 
    }) 
  }, 
  //每次展示获取一次定位 
  onShow() { 
    let that = this; 
    wx.getSetting({ 
      success: (res) => { 
        console.log(JSON.stringify(res)) 
        // res.authSetting['scope.userFuzzyLocation'] == undefined    表示 初始化进入该页面 
        // res.authSetting['scope.userFuzzyLocation'] == false    表示 非初始化进入该页面,且未授权 
        // res.authSetting['scope.userFuzzyLocation'] == true    表示 地理位置授权 
        if (res.authSetting['scope.userFuzzyLocation'] != undefined && res.authSetting['scope.userFuzzyLocation'] != true) { 
          //以前被拒绝授权指引用户授权 
          wx.showModal({ 
            title: '请求授权当前位置', 
            content: '需要获取您的地理位置，请确认授权', 
            success: function (res) { 
              if (res.cancel) { 
                app.toast(2, "拒绝授权") 
              } else if (res.confirm) { 
                wx.openSetting({ 
                  success: function (dataAu) { 
                    if (dataAu.authSetting["scope.userFuzzyLocation"] == true) { 
                      app.toast(1, "授权成功") 
                      that.getFuzzyLocations(); 
                    } else { 
                      app.toast(2, "授权失败") 
                    } 
                  } 
                }) 
              } 
            } 
          }) 
 
        } else if (res.authSetting['scope.userFuzzyLocation'] == undefined) { 
          //调用wx.getFuzzyLocation 
          that.getFuzzyLocations(); 
        } else { 
          that.getFuzzyLocations(); 
        } 
      } 
    }) 
  }, 

  Loopswitch(e){
    let addr =0
    //debugger
   
  },


  //读取本地历史缓存 并且 修改房间信息 
  GetLOC() { 
    let hc = null; 
    let data = wx.getStorageSync("oldHotelinfo") || [] 
    try { 
      for (let index = 0; index < data.length; index++) { 
        const element = data[index]; 
        if (element.key == this.data.Hotelinfo.HotelId) { 
          hc = data[index].data; 
          throw new Error(); 
        } 
      } 
    } catch (error) { 
      console.log('已经找到') 
    } 
    if (hc != null) { 
      let data = this.data.HostsData; 
      hc.forEach(x => { 
        for (let index = 0; index < data.length; index++) { 
          if (data[index].Id == x.Id) { 
            data[index].xg = x.xg; 
          } 
        } 
      }) 
      this.setData({ 
        HostsData: data, 
        HostsDataFilters: data 
      }) 
    } 
  } 
}) 