// pages/basics/progress/progress.js
const app = getApp() 
import { 
  GetHostsInfo, 
  GetMAC, 
  GetFaceSN, 
  ErrorInfo, 
  CheckFaceSN, 
  OpenDoorTest, 
  GetRoomType, 
  GetRoomTypeAndModalsListLog,
  WebChatUpgrade, 
  QueryUpdateHostStatus,
  ForwardQueryUpdateHostProgressBar,
  GetRoomTypeNode,
  SetRCULight,
  SetRCUAir,
  SetRCUCurtain,
  GetRoomAddressStatus
} from '../../../lib/RequestingCenter.js' 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    RoomIndex:0,
 //权限信息 
 autho: null, 
 //酒店信息 
 Hotelinfo: null, 
 HostsData:null,
 HostsDataFilters:[],
 isback:null,
 HotelId:null,
 statusdata:null,
 onlineNumber:0,
 inputValue:"",
 toView:"",  
 scrollHeight: 0  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function(options) {
    if (!options.HotelId || app.globalData.autho == null) { 
      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, "网络繁忙") 
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  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() {

  },

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

  },

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

  },

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

  },

  inputSearchForHotels(e){
    this.setData({
      inputValue: e.detail.value
    })
  },
  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 } = e.currentTarget.dataset;
    this.setData({
      RoomIndex:index
    } )
   let HostsDataFilters=  this.data.HostsDataFilters
      console.log(HostsDataFilters[index].RoomNumber)

    // 取消状态检查，无论状态如何都允许跳转
    wx.navigateTo({
      url: `/pages/basics/progress/RoomTypeControlLog/RoomTypeControlLog?RoomNumber=${room}&HotelName=${hotel}&HotelId=${this.data.Hotelinfo.HotelId }`
    });
  },
  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({ 
          RoomIndex:0,
          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, "网络繁忙") 
    }); 
  },

  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];
  },
})