// pages/basics/MakingRounds/MakingRounds.js
const app = getApp() 
 //const upgrade = require('../../../utils/upgrade.js')
import { 
  GetHostsInfo, 
  GetMAC, 
  GetFaceSN, 
  ErrorInfo, 
  CheckFaceSN, 
  OpenDoorTest, 
  GetRoomType, 
  GetRoomTypeAndModalsListLog,
  WebChatUpgrade,
  QueryUpdateHostStatus,
  ForwardQueryUpdateHostProgressBar,
  GetRoomTypeNode,
  SetRCULight,
  SetRCUAir,
  SetRCUCurtain,
} from '../../../lib/RequestingCenter.js' 
import DeviceUpgrader from '../../../utils/upgrade.js';
// const DeviceUpgrader = require('../../../utils/upgrade.js');
const upgrader = new DeviceUpgrader();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    TabCur:1,
    RoomIndex:0,
 //权限信息 
 autho: null, 
 //酒店信息 
 Hotelinfo: null, 
 HostsData:null,
 HostsDataFilters:[],
 isback:null,
 HotelId:null,
 statusdata:null,
 onlineNumber:0,
 inputValue:"",
 toView:"",  
 scrollHeight: 0,
 RoomtypeNamearray: [], 
 Completed:false,    //是否处于升级状态
 RoomtypeName: "",
 devlist:[],
 Roomtypeinfo:[],
 Pfilename:"",
 Gfilename:"",
 Upgradenode:[],
 myArray:[],
 CurrentUpgradeDev:'', //当前升级设备
 CurrentUpgradeDevStart:'',//当前升级设备状态
 UpgradeAllCount:0,
 //MAC绑定相关
 selHosts: null, 
 code: null, 
 modal: 0, 
 input: 0, 
 bdHosts: [], 
 address: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function(options) {
    
    if (!options.HotelId ) { 
      app.toast(2, "无酒店信息~") 
      return; 
    }

    this.setData({ 
      autho: app.globalData.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
    await GetHostsInfo({ 
      HotelID: this.data.Hotelinfo.HotelId 
    }).then(res => { 
      
      if (res.Status == 200) {
       let  onlineNumber=0   
        for (let index = 0; index < res.Data.length; index++) {
          const element = res.Data[index];
          if (element.Status===1) {
            onlineNumber=onlineNumber+1
          }
        }

        that.setData({ 
          onlineNumber:onlineNumber,
          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]        
        })      
      
         console.log(this.data.HostsDataFilters)
       
      } else { 
        app.toast(2, res.Message || "网络繁忙") 
      } 
    }, err => { 
      console.log(err) 
      app.toast(2, "网络繁忙") 
    }).catch(err => { 
      console.log(err) 
 
      app.toast(2, "网络繁忙") 
    }); 
    app.globalData.HotelId=options.HotelId
    await  GetRoomType({ 
      HotelID: options.HotelId
    }).then(res => {      
      app.SetroontypeListindex(res) 
      this.setData({ 
        myArray:app.globalData.roomIDName ,
        RoomtypeNamearray:app.globalData.roomName 
      }) 
    }, err => { 
      console.log('GetRoomType error') 
    }).catch(err => { 
     
    }); 
   
   
    upgrader.on('progress', p => {
      console.log(p)
      this.setData({ CurrentUpgradeDevStart: p })   // 实时刷新 UI
    })
    upgrader.on('error', e => {
      wx.showToast({ title: '升级失败', icon: 'none' })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.calcScrollHeight();    
  },

  calcScrollHeight() {
    // 1. 拿到屏幕可用高度（px）
    const sys = wx.getSystemInfoSync();
    const screenHeight = sys.windowHeight;   // px

    // 2. 拿到 scroll-view 的 top（px）
    wx.createSelectorQuery()
      .in(this)
      .select('#myScroll')
      .boundingClientRect(rect => {
        if (rect) {
          const topPx = rect.top;                    // px
          const bottomPx = 10 / 2;                   // 10rpx → 5px（2倍屏）
          const heightPx = screenHeight - topPx - bottomPx;

          // 3. 转 rpx 并写入
          this.setData({
            scrollHeight: heightPx * 2   // px→rpx
          });
        }
      })
      .exec();
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    upgrader.cancelUpgrade()
    upgrader._cleanup()    
  },

  //MAC绑定相关方法
  //检查MAC地址合法性
  CheckMAC: function (vlues) {
    return (vlues.indexOf("34D0B8") == 0 && vlues.length == 12 && vlues.indexOf(" ") < 0);
  },

  //扫码获取MAC地址
  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,
    })
  },

  //房间点击事件 - 扫码绑定
  /**
   * 获取主机MAC地址
   * @async
   * @function GetMAC
   * @param {Object} e - 事件对象
   * @param {number} e.currentTarget.dataset.index - 当前选中主机的索引
   * @description 根据选中主机的索引获取MAC地址，如果MAC地址不存在则调用GetCode方法
   * @returns {Promise<void>}
   */
  GetMAC: async function (e) {
    let index = e.currentTarget.dataset['index'];
    let selHosts = this.data.HostsDataFilters[index];
    selHosts.index = index;
    
    this.setData({
      selHosts: selHosts,
      input: 0
    })
    
    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()
    }
  },

  //长按房间事件 - 手动输入MAC
  GetMAC_long: function (e) {
    let indexstr =  e.currentTarget.id.replace("msg-","")
    let index= Number(indexstr)
    
    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: ""
    })
  },

  //验证手动输入的MAC地址
  GetMACOK: function () {
    let that = this;
    if (!this.CheckMAC(that.data.code)) {
      this.setData({
        modal: 520
      })
      return;
    }
    
    this.setData({
      modal: 521
    })
  },

  //解绑MAC地址
  Jb: async function(params) {
    let index = params.currentTarget.dataset['index'];
    let jbjd = this.data.bdHosts[index];
    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) {
            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) {
            data[OLD].MAC = "";
          }
          
          let res = that.GetFilters(that.data.sel, data);
          that.setData({
            HostsData: data,
            HostsDataFilters: res[0],
            statusdata: res[1]
          })
        } else {
          app.toast(2, "解绑失败")
        }
      },
      err => {
        app.toast(2, "网络繁忙")
      }
    ).catch(err => {
      app.toast(2, "网络繁忙")
    });
  },

  //最终绑定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, "绑定成功")
          
          //更新本地数据
          let data = that.data.HostsData;
          let OLD = -1;
          try {
            data.forEach(
              (x, INDEX) => {
                if (x.RoomNumber === that.data.selHosts.RoomNumber) {
                  OLD = INDEX;
                  throw new Error();
                }
              }
            )
          } catch (error) {
          }
          
          if (OLD >= 0) {
            data[OLD].MAC = that.data.code;
          }
          
          that.setData({
            HostsData: data,
            HostsDataFilters: data
          })
        } else {
          if (!type) {
            xg = 1;
            app.toast(2, "绑定失败")
          } else {
            try {
              if (res.Status == 100) {
                xg = 100;
                let modal = 3;
                let mesg = [that.data.code];
                
                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, "网络繁忙")
    });
  },

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

  },

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

  },

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

  },

  inputSearchForHotels(e){
    this.setData({
      inputValue: e.detail.value
    })
  },
  async UpgradeTheEquipment(e){
    let se=e
    let _this =this
    let updataDev = e.currentTarget.dataset.id
    let errstr =""
    if (updataDev == 1) {
      errstr="固件"     
    }
    if (updataDev == 2) {
      errstr="配置"    
    }
    wx.showModal({
      title: "提示",
      content: "是否进行"+errstr+"升级！",
      async  success (res) {
        if (res.confirm) {
       await _this.UpgradeTheEquipment2(se)
        } else if (res.cancel) {
         return
        }
      }
    })
  },
  async UpgradeTheEquipment2(e){
    
    let updataDev = e.currentTarget.dataset.id
    let errstr =""
    let devlist =this.data.devlist
    let UpgradeType =""
    let filename  = ""
    let RoomtypeName =this.data.RoomtypeName
    let _this =this
    let  RoomTypeID=""
    let HotelId= app.globalData.HotelId
    let UpgradeCount=0
    if (updataDev == 1) {
      errstr="升级固件失败" 
      UpgradeType='firmware'
      filename=_this.data.Gfilename
      filename=filename.replace('.hex','.bin')
    }
    if (updataDev == 2) {
      errstr="升级配置失败"       
      UpgradeType=''
      filename=_this.data.Pfilename
    }
    if (filename.length ==0) {
      _this.DisplayPrompt("未获取到升级文件！升级失败",3000)
      return
    }
    RoomTypeID=this.GetRoomTypeId(RoomtypeName)

    let newdevlist =[]
    for (let i = 0; i < this.data.devlist.length; i++) {
       
      devlist[i].UpgradeStatus = 0
   
    if (devlist[i].checkbox) {  //勾选
      if (devlist[i].Status) {  //离在线            
        newdevlist.push(devlist[i])         
      }
    }
  }

  if (newdevlist.length>0) {
        _this.setData({ 
          UpgradeCount:0,  //升级计数
          CurrentUpgradeDev:"", //当前升级设备
          CurrentUpgradeDevStart:"",//当前升级设备状态
          Completed:true,
          UpgradeAllCount:newdevlist.length,//升级总数
          devlist:devlist
        })
        
      }else
      {
        this.DisplayPrompt2("未选中升级设备", 1000)
        return
      }
  
     

      for (let Nvindex = 0; Nvindex < newdevlist.length; Nvindex++) {
        const element = newdevlist[Nvindex];
        _this.setData({ 
        //升级计数
        CurrentUpgradeDev:element.RoomNumber, //当前升级设备
        CurrentUpgradeDevStart:'升级就绪',//当前升级设备状态      
      }) 

        try {
       await upgrader.startUpgrade(UpgradeType, {
            roomTypeID: RoomTypeID,
            hostidLists:'['+element.ID+']',
            upgradefileName: filename,
            hotelid:HotelId
          })
          .then(res => {           
            _this.setData({ 
              UpgradeCount:_this.data.UpgradeCount+1,  //升级计数             
            })
          console.log('升级完成', res)
          })
          .catch(err =>{

         
          console.log('升级失败', err)
          });
        }catch (error) {
          _this.setData({ 
            //升级计数
            CurrentUpgradeDev:element.RoomNumber, //当前升级设备
            CurrentUpgradeDevStart:errstr+'，服务器响应异常',//当前升级设备状态
            Completed:false
          })  
         //this.DisplayPrompt(errstr+'，服务器响应异常',1000)  
          return
        }

      }

 this.DisplayPrompt2("升级完成！", 1000)

  },
  DisplayPrompt2(tipstr, showtime)
  {
    wx.showToast({
      title: tipstr,
      icon: 'none'
    })
    setTimeout(function () {
      wx.hideToast()
    }, showtime)
  },
  ALLcheckboxSub(e){
  
    let devlist =this.data.devlist
    let ALLcheckbox =this.data.Allcheckbox
    let values =  !ALLcheckbox
    for (let index = 0; index < devlist.length; index++) {
     devlist[index].checkbox=values  
    }
    this.setData({ 
      devlist:devlist,
      Allcheckbox:values
}); 
  },
  checkboxSub(e){
    let devlist =this.data.devlist
    let ALLcheckbox =this.data.Allcheckbox      
    let index = e.currentTarget.dataset.id
    let values =!devlist[index].checkbox
    devlist[index].checkbox=values
    let checksun =0
    for (let nindex = 0; nindex < devlist.length; nindex++) {
      if (values) {
        if (   devlist[nindex].checkbox!=values) {
          values=devlist[nindex].checkbox
        }          

      }
   if (devlist[nindex].checkbox) {
    checksun=checksun+1
   }
      
     }

    this.setData({ 
      devlist:devlist,
      Allcheckbox:values,
      checksun:checksun
}); 
  },
  SearchForHotels(e){
    //debugger
    let myarry =this.data.HostsDataFilters
    let inputValue =this.data.inputValue.trim()
    const CNaelement  =this.sortHotelsByFuzzyMatch(myarry,inputValue)
    this.setData({
      HostsDataFilters:CNaelement
    })
  },
  goProcess(e) {

    let indexstr =  e.currentTarget.id.replace("msg-","")
    let index= Number(indexstr)
   

    const { room, hotel, status,roomtypeid,hotelcode,createTime} = e.currentTarget.dataset;
    let HostsDataFilters =this.data.HostsDataFilters
    let  timestr = HostsDataFilters[0].CreateTime
    if (status !== 1) {
      if (!HostsDataFilters[index].MAC||HostsDataFilters[index].MAC.length==0) {
         //长按事件   
    if (this.endTime - this.startTime > 350) { 
      return; 
    } 
        this.setData({
          selHosts: HostsDataFilters[index]
        })
        this.GetCode() 
      }

    } else{       // 不为1时不跳转
      wx.navigateTo({
          url: `/pages/basics/HostUpgrade/EquipmentCaontrol/EquipmentCaontrol?RoomNumber=${room}&HotelName=${hotel}&HotelId=${this.data.Hotelinfo.HotelId }&roomtypeid=${roomtypeid }&HotelCode=${hotelcode}&createTime=${timestr}`
        });
    }       
  
  },
  RefreshTheRoom:async function(e){
    let that = this
    await GetHostsInfo({ 
      HotelID: this.data.Hotelinfo.HotelId 
    }).then(res => { 
      
      if (res.Status == 200) {
       let  onlineNumber=0   
        for (let index = 0; index < res.Data.length; index++) {
          const element = res.Data[index];
          if (element.Status===1) {
            onlineNumber=onlineNumber+1
          }
        }

        that.setData({ 
          onlineNumber:onlineNumber,
          HostsData: res.Data, 
          HostsDataFilters: res.Data, 
          isback: (app.globalData.autho.length > 1 || app.globalData.autho[0].Hotels.length > 1), 
          statusdata: [0, 0, 0, res.Data.length]        
        })      
      
         console.log(this.data.HostsDataFilters)
       
      } else { 
        app.toast(2, res.Message || "网络繁忙") 
      } 
    }, err => { 
      console.log(err) 
      app.toast(2, "网络繁忙") 
    }).catch(err => { 
      console.log(err) 
 
      app.toast(2, "网络繁忙") 
    }); 
  },
  //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);   
  }, 
  sortHotelsByFuzzyMatch:function(hotels, keyword) {
    // 1. 参数验证
    if (!Array.isArray(hotels)) {
      console.warn('第一个参数必须是数组');
      return [];
    }
  
    if (typeof keyword !== 'string') {
      console.warn('第二个参数必须是字符串');
      return hotels.slice();
    }
  
    // 2. 处理空数组或空关键字的情况
    const trimmedKeyword = keyword.trim();
    if (hotels.length === 0 || trimmedKeyword === '') {
      return hotels.slice();
    }
  
    const lowerKeyword = trimmedKeyword.toLowerCase();
  
    // 3. 分离匹配和不匹配的酒店
    const matchedHotels = [];
    const unmatchedHotels = [];
  
    hotels.forEach(hotel => {
      // 检查是否为有效酒店对象
      if (!hotel || typeof hotel !== 'object' || !hotel.RoomNumber) {
        unmatchedHotels.push(hotel);
        return;
      }
  
      const hotelName = String(hotel.RoomNumber).toLowerCase();
      const isMatch = hotelName.includes(lowerKeyword);
      
      if (isMatch) {
        matchedHotels.push(hotel);
      } else {
        unmatchedHotels.push(hotel);
      }
    });
  
    // 4. 合并数组并返回
    return [...matchedHotels, ...unmatchedHotels];
  },
  RefreshTheRoomType(e){
    e.detail=this.data.RoomtypeName
    this.bindPickerChange(e)
  },
  GetRoomTypeId(roomTypeName){
    if (roomTypeName.length>0) {
      let myArray =this.data.myArray
      
      for (let index = 0; index < myArray.length; index++) {
        let strbuf  = myArray[index].split('|')  ;
        if (strbuf[1]==roomTypeName) {
          return strbuf[0]
        }
      }
    }else{
      return ""
    }
  },
  DisplayPrompt(tipstr, showtime)
{

  // wx.showModal({
  //   title: '提示',
  //   content: '确认执行此操作吗？',
  //   success(res) {
  //     if (res.confirm) { /* 用户点击确定 */ }
  //   }
  // });

  wx.showLoading({
    title: tipstr,
  })    

  
  setTimeout(function () {
    wx.hideLoading()
  }, showtime)
},
  async bindPickerChange(e) { 
    
    let Completed =this.data.Completed
    let _this =this
    if (Completed) {
      this.DisplayPrompt("正在升级中！",1000)
      return
    }
    let devlist=[]
    let Roomtypeinfo=[]
    
    let roomid = this.GetRoomTypeId(e.detail)
    if (roomid.length==0) {
      return
    }
    let Pfilename =""
    let Gfilename =""
    let Upgradenode =[]
       try { 
      // 调用 GetRoomTypeNode 
      const res = await GetRoomTypeNode({ 
        hotelid: app.globalData.HotelId, 
        roomTypeID: roomid, 
      }); 
      if (res.IsSuccess==true) {
        devlist = res.HostData
        for (let nindex = 0; nindex < devlist.length; nindex++) {
          devlist[nindex].show=1    
          devlist[nindex].checkbox=0  
          devlist[nindex].UpgradeStatus=0   
          devlist[nindex].Model =_this.removeNullCharsAndInvisibleChars(devlist[nindex].Model) 
        }
      }
              const Nres  = await  GetRoomType({ 
        HotelID:app.globalData.HotelId 
      })
if (Nres.Status==200) {
  Roomtypeinfo=Nres.Data
  for (let index = 0; index < Roomtypeinfo.length; index++) {
    const element = Roomtypeinfo[index];
 
    if (element.ROOM_TYPE_OLD_ID == roomid) {
      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
    }
    
  }
 }

      this.setData({ 
        RoomtypeName: e.detail,
        devlist:devlist,
        Roomtypeinfo:Roomtypeinfo,
        Pfilename:Pfilename,
        Gfilename:Gfilename,
        Upgradenode:Upgradenode
      }); 
      console.log(devlist)
    } catch (err) { 
      console.log('GetRoomTypeNode error', err); 
    } 
  }, 
  removeNullCharsAndInvisibleChars(str) {
    try {
    
     return str.replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g, '');
    } catch (error) {
      return "NULL"
    }
  
 },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,      
    })
  },

})