// pages/basics/MakingRounds/MakingRounds.js
const app = getApp() 
import { 
  GetHostsInfo, 
  GetMAC, 
  GetFaceSN, 
  ErrorInfo, 
  CheckFaceSN, 
  OpenDoorTest, 
  GetRoomType, 
  GetRoomTypeAndModalsListLog,
  WebChatUpgrade,
  QueryUpdateHostStatus,
  ForwardQueryUpdateHostProgressBar,
  GetRoomTypeNode,
  SetRCULight,
  SetRCUAir,
  SetRCUCurtain,
} from '../../lib/RequestingCenter.js' 
Page({ 
  data: { 
    userInfo: null, 
    autho: null, 
    selectGroupIndex:-1, 
    ishotel: false, 
    hotelIndex: 0, 
    issel:false ,
    curNav:1,
    curIndex:0,
    top_height:0,
    inputValue:""
  }, 
  selectNav (event) {
		let id = event.target.dataset.id,
			index = parseInt(event.target.dataset.index);
			self = this;
		this.setData({
			curNav:id,
			curIndex:index
		})
	},
  ///选择酒店 
  SelHotel: function (e) { 
    let index = e.currentTarget.dataset['index']; 
    this.setData({ 
      hotelIndex: index 
    }) 
    wx.setStorageSync(this.data.userInfo.Id + '_xiaoxi_hotelId', this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].HotelId) 
  }, 
  //确定选择酒店 
  ShowSelHotel: async function (e) { 
    
    let HotelCode
    let id = e.currentTarget.dataset['id']; 
    if(id==-1){ 
     id = this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].HotelId;
     HotelCode= this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].Code;
    } 
    if(this.data.hotelIndex>=0){ 
      
      app.globalData.HotelId=id
      app.globalData.HotelCode=HotelCode
     

    wx.navigateTo({       
      url: '/pages/NewHome/NewHome?HotelId=' + id
    }) 
    }else{ 
      app.toast(2,'未选择酒店') 
    } 
  }, 
  //选择酒店组 
  bindgroup: function (e) {
   
    let index 
    try {
      index = e.currentTarget.dataset['index'] 
    } catch (error) {
      index=0
    }

  
    this.setData({ 
      selectGroupIndex: index, 
      hotelIndex: 0, 
      ishotel: true 
    }) 
    wx.setStorageSync(this.data.userInfo.Id + '_xiaoxi_hotelId', this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].HotelId) 
    wx.setStorageSync(this.data.userInfo.Id + '_xiaoxi_selectGroupId', this.data.autho[this.data.selectGroupIndex].HotelGroupsId) 
  }, 
  codebindgroup: function (GroupIndex,hotelIndex) {
   
    this.setData({ 
      selectGroupIndex: GroupIndex, 
      hotelIndex:hotelIndex, 
      ishotel: true 
    }) 
    wx.setStorageSync(this.data.userInfo.Id + '_xiaoxi_hotelId', this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].HotelId) 
    wx.setStorageSync(this.data.userInfo.Id + '_xiaoxi_selectGroupId', this.data.autho[this.data.selectGroupIndex].HotelGroupsId) 
  }, 


  //登录 
  onLoad: async function (option) { 
    let that=this

    this.setData({ 
      userInfo: app.globalData.userinfo, 
      autho: app.globalData.autho 
    }) 
   
    if (this.data.userInfo == null) { 
      app.checkLoginReadyCallback = res => { 
      this.setData({ 
        userInfo: app.globalData.userinfo, 
        autho: app.globalData.autho 
      }) 
      this.ReaSel() 
      }; 
    } else { 
      this.ReaSel() 
    } 
    setTimeout(function () { 
      // 1.使用wx.createSelectorQuery()查询到需要滚动到的元素位置 
      wx.createSelectorQuery().select('#Headcustom').boundingClientRect(res => { 
        // 2.使用wx.getSysTemInfo()获取设备及页面高度windowHeight（px） 
        wx.getSystemInfo({ 
          success(ress) { 
            
            that.setData({ 
              top_height: ress.windowHeight - res.bottom,             
            }) 
        
          } 
        }) 
      }).exec(function (params) { 
        console.log(params) 
      }) 
    }, 100) 
    let e=[]


    this.bindgroup(e)
     console.log(this.data.top_height)
  }, 
  inputSearchForHotels(e){
    this.setData({
      inputValue: e.detail.value
    })
  },


  SearchForHotels(e) {
//debugger    //hotelIndex
  let inputValue =this.data.inputValue.trim()
  if (inputValue.length==0) {
    wx.showModal({
      title: "提示",
      content: "无效搜索",
      showCancel:false
    })
     return
  }

  
  let autho = this.data.autho
  let selectGroupIndex = this.data.selectGroupIndex
  const Naelement = autho[selectGroupIndex]
  const CNaelement  =this.sortHotelsByFuzzyMatch(Naelement.Hotels,inputValue)
  autho[selectGroupIndex].Hotels=CNaelement
  this.setData({
    autho:autho
  })

   for (let aindex = 0; aindex < autho.length; aindex++) {
     const aelement = autho[aindex];
    
     for (let bindex = 0; bindex <  aelement.Hotels.length; bindex++) {
       const belement = aelement.Hotels[bindex];
        if (belement.Code==inputValue) {
          this.codebindgroup(aindex,bindex)
          return
        }
        if (belement.HotelName==inputValue) {
          this.codebindgroup(aindex,bindex)
          return
        }
     }
     
   }
   wx.showModal({
    title: "提示",
    content: "未找到该酒店！",
    showCancel:false
  })
 } ,
  //读取历史选择酒店 
  ReaSel: function () { 
    let _xiaoxi_hotelId = wx.getStorageSync(this.data.userInfo.Id + '_xiaoxi_hotelId') 
    let _xiaoxi_selectGroupId = wx.getStorageSync(this.data.userInfo.Id + '_xiaoxi_selectGroupId') 
    let _xiaoxi_selectGroupIndex = -1; 
    let _xiaoxi_hotelIndex = -1; 
    this.data.autho.forEach((element, index) => { 
      if (element.HotelGroupsId == _xiaoxi_selectGroupId) { 
        _xiaoxi_selectGroupIndex = index; 
        element.Hotels.forEach((elements, indexs) => { 
          if (elements.HotelId == _xiaoxi_hotelId) { 
            _xiaoxi_hotelIndex = indexs; 
          } 
        }) 
      } 
    }); 
    this.setData({ 
      selectGroupIndex: _xiaoxi_selectGroupIndex, 
      hotelIndex: _xiaoxi_hotelIndex 
    }) 

  
    //非选择 读取上次进行跳转  
    if(!this.data.issel && this.data.hotelIndex>-1){ 
      let HotelCode= this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].Code;
      let HotelId=this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].HotelId
      app.globalData.HotelId=HotelId
      app.globalData.HotelCode=HotelCode
      wx.navigateTo({ 
        url: '/pages/NewHome/NewHome?HotelId='+this.data.autho[this.data.selectGroupIndex].Hotels[this.data.hotelIndex].HotelId 
      }) 
    } 
      // console.log(this.data.autho.length==1 && this.data.autho[0].Hotels.length==1 && option.issel!=0) 
    //非选择 如果只有一个酒店就直接进行跳转 
    if(this.data.autho.length==1 && this.data.autho[0].Hotels.length==1 && !this.data.issel){ 
      let HotelCode= this.data.autho[0].Hotels[0].Code;
      let HotelId=this.data.autho[0].Hotels[0].HotelId
      app.globalData.HotelId=HotelId
      app.globalData.HotelCode=HotelCode
      wx.navigateTo({ 
        url: '/pages/NewHome/NewHome?HotelId='+this.data.autho[0].Hotels[0].HotelId 
      }) 
    } 
  } ,
   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.HotelName) {
        unmatchedHotels.push(hotel);
        return;
      }
  
      const hotelName = String(hotel.HotelName).toLowerCase();
      const isMatch = hotelName.includes(lowerKeyword);
      
      if (isMatch) {
        matchedHotels.push(hotel);
      } else {
        unmatchedHotels.push(hotel);
      }
    });
  
    // 4. 合并数组并返回
    return [...matchedHotels, ...unmatchedHotels];
  }
}) 