const app = getApp() 
import { 
  GetHostsInfo, 
  GetMAC, 
  GetFaceSN, 
  ErrorInfo, 
  CheckFaceSN, 
  OpenDoorTest, 
  GetRoomType, 
  GetRoomTypeAndModalsListLog,
  WebChatUpgrade,
  QueryUpdateHostStatus,
  ForwardQueryUpdateHostProgressBar,
  GetRoomTypeNode,
  SetRCULight,
  SetRCUAir,
  SetRCUCurtain,
  QueryRoomVisitLog,
  WriteRoomVisitLog,
  UpdateRoomVisitLog
} from '../../../lib/RequestingCenter.js' 
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    RoomIndex:0,
    //权限信息 
    autho: null, 
    //酒店信息    
    HostsDataFilters:[],   
    toView:"", 
    RoomNumber:"",
    HotelId:"",
    // 时间范围查询相关
    seltime:4, // 时间范围：4-全部，1-今日，2-本周，3-本月，5-指定时间
    starttime:"", // 起始时间
    endtime:"", // 结束时间
    // 设备访问日志数据
    visitLogList: [],
    // 选中的记录ID，用于控制故障原因的显示
    selectedId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function(options) {
    if (!options.HotelId || app.globalData.autho == null) { 
      app.toast(2, "无酒店信息~") 
      return; 
    }
    if (!options.RoomNumber) {
      this.setData({ 
        autho: app.globalData.autho,
        HotelId: options.HotelId      
      }) 
    }else{
      this.setData({ 
        autho: app.globalData.autho,
        HotelId: options.HotelId,
        RoomNumber:options.RoomNumber      
      }) 
      
    }
    
    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("已经找到，无需循环~") 
    } 




  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    await this.getRoomVisitLog();
  },
  
  // 获取房间设备访问日志
  async getRoomVisitLog() {
    // 检查是否有HotelId
    if (!this.data.HotelId) {
      console.error("缺少HotelId参数");
      app.toast(2, "缺少酒店信息");
      // 确保visitLogList始终是数组
      this.setData({
        visitLogList: [],
        HostsDataFilters: []
      });
      return;
    }
    
    let params = {
      HotelID: this.data.HotelId,
      RoomNumber: this.data.RoomNumber, // 初始加载时不按房号筛选，获取所有异常记录
      StartTime: this.data.starttime,
      EndTime: this.data.endtime
    };
    
    console.log("请求参数:", params);
    
    try {
     
      let logs = []
      const res = await QueryRoomVisitLog(params);
      if (res && res.Status === 1) {
        console.log(res.Data)
       // 初始化 logs 数组
let logs = [];

for (let index = 0; index < res.Data.length; index++) {
    const element = res.Data[index]; // element 是一个数组
    
    // 查找每个字段对应的值
    const findValue = (key) => {
        const item = element.find(obj => obj.Key === key);
        return item ? item.Value : null;
    };
    
    logs[index] = {
        Id: findValue("ID"),
        HotelID: findValue("HotelID"),
        RoomNumber: findValue("RoomNumber"),
        EquipmentStatus: findValue("EquipmentStatus"),
        FaultDescription: findValue("FaultDescription"),
        UpdateDate: findValue("UpdateDate"),
        DevName: findValue("DevName"),
        EquipmentStatusType: findValue("EquipmentStatusType"),
        EquipmentOnlineStatus: findValue("EquipmentOnlineStatus"),
        EquipmentOnlineStatusShow:0
    };
}

   
        // 如果有搜索房号，将符合条件的记录放到头部
        if (this.data.RoomNumber) {
          logs=  this.sortHotelsByFuzzyMatch(logs,this.data.RoomNumber)
        }
        
     
        
        this.setData({
          visitLogList: logs, // 明确设置为数组
          HostsDataFilters: logs // 更新异常记录数量显示
        });
        
        // 打印最终数据长度
        console.log("最终显示数据数量:", logs.length);
      } else {
        console.error("API请求失败:", res);
        app.toast(2, res.Message || "查询失败");
        // 清空数据列表，明确设置为数组
        this.setData({
          visitLogList: [],
          HostsDataFilters: []
        });
      }
    } catch (err) {
      console.error("查询设备访问日志失败:", err);
      app.toast(2, "查询失败，请重试");
      // 清空数据列表，明确设置为数组
      this.setData({
        visitLogList: [],
        HostsDataFilters: []
      });
    }
  },
  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 
    }
  
    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];
  },

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

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

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

  },

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

  },
  // 房号输入
  inputSearchForHotels(e){
    this.setData({
      RoomNumber: e.detail.value
    })
  },
  
  // 搜索按钮点击
  searchRoomLog() {
    const { visitLogList, RoomNumber } = this.data;
    if (!RoomNumber) {
      // 如果搜索框为空，直接返回
      return;
    }
    
    // 在现有数据上进行房号匹配
    const filteredLogs = visitLogList.filter(log => log.RoomNumber && log.RoomNumber.includes(RoomNumber));
    const otherLogs = visitLogList.filter(log => !log.RoomNumber || !log.RoomNumber.includes(RoomNumber));
    
    // 将符合条件的数据放到头部
    this.setData({
      visitLogList: [...filteredLogs, ...otherLogs]
    });
  },
  
  // 时间范围选择
  seltime: function(e) {
    let sel = Number(e.target.dataset.val);
    let starttime = "";
    let endtime = "";
    const now = new Date();
    
    switch (sel) {
      case 1: // 今日
        starttime = now.toISOString().split('T')[0];
        endtime = now.toISOString().split('T')[0];
        break;
      case 2: // 本周
        let time = this.getThisWeekData();
        starttime = time.start_day;
        endtime = time.end_day;
        break;
      case 3: // 本月
        starttime = util.getCurrentMonthFirst(new Date());
        endtime = util.getCurrentMonthLast(new Date());
        break;
      case 4: // 全部
        starttime = "";
        endtime = "";
        break;
    }
    
    this.setData({
      seltime: sel,
      starttime: starttime,
      endtime: endtime
    });
  },
  
  // 自定义时间选择
  bindTimeChange: function(e) {
    if (e.target.dataset.type == 1) {
      this.setData({
        seltime: 5,
        starttime: e.detail.value
      });
    } else {
      this.setData({
        seltime: 5,
        endtime: e.detail.value
      });
    }
  },
  
  // 时间范围查询
  async searchByTime() {
    await this.getRoomVisitLog();
  },
  
  // 全部记录查询
  async RefreshTheRoom() {
    this.setData({
      seltime: 4,
      starttime: "",
      endtime: "",
      RoomNumber: "" // 清空搜索框内容
    });
    await this.getRoomVisitLog();
  },
  
  // 获取本周的起止日期
  getThisWeekData: function() {
    var thisweek = {};
    var date = new Date();
    // 本周一的日期
    date.setDate(date.getDate() - date.getDay() + 1);
    thisweek.start_day = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    
    // 本周日的日期
    date.setDate(date.getDate() + 6);
    thisweek.end_day = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
    return thisweek;
  },
  
  // 切换故障原因显示状态
  toggleFaultReason(e) {
    const id = e.currentTarget.dataset.id;
    const { selectedId } = this.data;
    
    // 如果点击的是当前显示的项，则隐藏；否则显示点击的项
    this.setData({
      selectedId: selectedId === id ? null : id
    });
  },
  
  // 确认维修完成
  async confirmRepair(e) {
    const id = e.currentTarget.dataset.id;
    console.log("确认维修完成，设备ID:", id);
    
    // 找到对应的设备记录
    const deviceIndex = this.data.visitLogList.findIndex(item => item.Id === id);
    if (deviceIndex === -1) {
      console.error("未找到对应的设备记录");
      return;
    }
    
    const device = this.data.visitLogList[deviceIndex];
    
    // 获取当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    
    try {
      // 1. 先调用UpdateRoomVisitLog接口，将原来的故障记录设置为维修完成
      const updateParams = {
        id: id,
        faultDescription: "维修完成",
        equipmentStatusType: "1"
      };
      
      const updateRes = await UpdateRoomVisitLog(updateParams);
      if (updateRes.Status !== 1) {
        wx.showToast({
          title: updateRes.Message || "更新故障记录失败",
          icon: 'none',
          duration: 2000
        });
        console.log("更新故障记录失败", updateRes);
        return;
      }
      
      // 2. 调用WriteRoomVisitLog接口，写入一条新的正常记录
      const writeParams = {
        HotelID: this.data.HotelId,
        RoomNumber: device.RoomNumber,
        EquipmentList: [{
          EquipmentStatus: "正常",
          FaultDescription: "已维修完成",
          DevName: device.DevName,
          EquipmentStatusType: "3",
          EquipmentOnlineStatus: "1",
          UpdateDate: currentTime
        }]
      };
      
      const writeRes = await WriteRoomVisitLog(writeParams);
      
      // 处理返回结果
      if (writeRes.Status === 1) {
        wx.showToast({
          title: '维修完成',
          icon: 'success',
          duration: 2000
        });
        
        // 从visitLogList中移除对应的故障记录
        const updatedVisitLogList = [...this.data.visitLogList];
        updatedVisitLogList.splice(deviceIndex, 1);
        
        // 更新页面数据
        this.setData({
          visitLogList: updatedVisitLogList,
          HostsDataFilters: updatedVisitLogList
        });
        
        // 如果当前选中的是被移除的记录，清空选中状态
        if (this.data.selectedId === id) {
          this.setData({
            selectedId: null
          });
        }
      } else {
        wx.showToast({
          title: writeRes.Message || "写入正常记录失败",
          icon: 'none',
          duration: 2000
        });
        console.log("写入正常记录失败", writeRes);
      }
    } catch (error) {
      wx.showToast({
        title: "维修完成失败，请检查网络连接",
        icon: 'none',
        duration: 2000
      });
      console.error("维修完成出错", error);
    }
  },
  
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})