const app = getApp() 
import {
  GetRoomAddressStatus,
  QueryDeviceList,
  WriteRoomVisitLog,
  SetRCUService
} from '../../../../lib/RequestingCenter.js' 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    RoomNumber:"",
    HotelName:"",
    deviceList:[],
    deviceListindex:0,
    inputValue:"",
    toView:"",  
    scrollHeight: 0 ,
    modalName: "",
    note:"",
    noteok:"",
    errorsNumber:0,
    HotelId:"",
    RoomTypeID:"",
    showErrorReasonInput: false, // 控制异常原因输入框显示/隐藏
    errorReason: "", // 异常原因内容
  },
  
  // 定时器ID
  timer5s: null,
  timer1min: null,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function(options) {
  
    if (!options.RoomNumber  || !options.HotelName ||!options.HotelId ||!options.RoomTypeID) { 
      app.toast(2, "无酒店信息~") 
      return; 
    }
    console.log(options.RoomNumber)
    this.setData ({
      RoomNumber:options.RoomNumber,
      HotelName:options.HotelName,
      HotelId:options.HotelId,
      RoomTypeID:options.RoomTypeID
    })
    console.log(app.globalData.HotelCode)
    
    // let HotelId  =parseInt(app.globalData.HotelCode);
    // await GetRoomAddressStatus({ 
    //   Code: HotelId,
    //   RoomNum:options.RoomNumber
    // }).then(res => { 
      
    //   if (res.Status == 200) {
      
     
       
    //   } else { 
    //     app.toast(2, res.Message || "网络繁忙") 
    //   } 
    // }, err => { 
    //   console.log(err) 
    //   app.toast(2, "网络繁忙") 
    // }).catch(err => { 
    //   console.log(err)  
    //   app.toast(2, "网络繁忙") 
    // }); 

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady:async function() {
    //debugger
    this.calcScrollHeight();
    
    // 页面加载完毕时调用QueryDeviceList获取设备列表
    await this.getDeviceList();
  },
  
  /**
   * 获取设备列表
   */
  getDeviceList:async function() {
    try {
      const res = await QueryDeviceList({
        HotelID: app.globalData.HotelCode,
        RoomTypeID: this.data.RoomTypeID
      });
      
      if (res.Status == 1) {
        console.log('设备列表获取成功:', res.Data);
        // 更新设备列表数据
        let deviceList = [];
        for (let index = 0; index < res.Data.length; index++) {
          const element = res.Data[index];
          // 检查是否已存在相同名称的设备
          const isExist = deviceList.some(item => item.name === element.DevName);
          if (!isExist) {
            deviceList.push({
              id: deviceList.length + 1,
              name: element.DevName,
              status: "在线",
              note: element.Process,
              isnote: 0,
              Addrlist: [element.DevAddr]
            });
          } else {
            // 如果设备已存在，将新地址添加到Addrlist中
            const existingDevice = deviceList.find(item => item.name === element.DevName);
            if (existingDevice) {
              // 检查Addrlist中是否已存在该地址，避免重复添加
              if (!existingDevice.Addrlist.includes(element.DevAddr)) {
                existingDevice.Addrlist.push(element.DevAddr);
              }
            }
          }
        }
        this.setData({
          deviceList: deviceList
        });

      } else {
        console.log('设备列表获取失败:', res.Message);
        app.toast(2, res.Message || "获取设备列表失败");
      }
    } catch (error) {
      console.log('获取设备列表出错:', error);
      app.toast(2, "获取设备列表失败");
    }
  },
  calcScrollHeight() {
    // 1. 拿到屏幕可用高度（px）
    const sys = wx.getSystemInfoSync();
    const screenHeight = sys.windowHeight;   // px

    // 2. 拿到 scroll-view 的 top（px）
    wx.createSelectorQuery()
      .in(this)
      .select('#NmyScroll')
      .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() {
    // 启动定时器
    this.startTimers();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 停止定时器
    this.stopTimers();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 停止定时器
    this.stopTimers();
  },

  /**
   * 启动定时器
   */
  startTimers() {
    // 先调用一次SetRCUService
    this.callSetRCUService();
    // 再调用一次GetRoomAddressStatus
    this.callGetRoomAddressStatus();
    
    // 设置5秒定时器，查询设备离在线状态
    this.timer5s = setInterval(() => {
      this.callGetRoomAddressStatus();
    }, 5000);
    
    // 设置1分钟定时器，启动设备巡检
    this.timer1min = setInterval(() => {
      this.callSetRCUService();
    }, 60000);
  },

  /**
   * 停止定时器
   */
  stopTimers() {
    if (this.timer5s) {
      clearInterval(this.timer5s);
      this.timer5s = null;
    }
    if (this.timer1min) {
      clearInterval(this.timer1min);
      this.timer1min = null;
    }
  },

  /**
   * 调用SetRCUService接口
   */
  async callSetRCUService() {
    // 解析.NET风格的日期格式 "/Date(1473004800000)/"
    let dotNetDate = app.globalData.CreatDate
    let timestamp, pageCreateTime
    try {
      timestamp = parseInt(dotNetDate.match(/\d+/)[0])
      pageCreateTime = new Date(timestamp)
    } catch (error) {
      console.error('日期解析错误:', error)
      // 如果解析失败，使用当前日期作为备选
      pageCreateTime = new Date()
    }
    let year = pageCreateTime.getFullYear()
    let month = (pageCreateTime.getMonth() + 1).toString().padStart(2, '0')
    let day = pageCreateTime.getDate().toString().padStart(2, '0')
    let CreateTime = `${year}-${month}-${day}`

    try {
      
      const params = {
        code: app.globalData.HotelCode,
        creatDate:CreateTime,
        roomNumber: this.data.RoomNumber,
        modalAddress:"004000029",
        status: "1"
      };
      const res = await SetRCUService(params);
      console.log('SetRCUService调用成功:', res);
    } catch (error) {
      console.error('SetRCUService调用失败:', error);
    }
  },

  /**
   * 调用GetRoomAddressStatus接口
   */
  async callGetRoomAddressStatus() {
    //debugger
    try {
      const params = {
        Code: parseInt(app.globalData.HotelCode),
        RoomNum: this.data.RoomNumber
      };
      const res = await GetRoomAddressStatus(params);
      //console.log('GetRoomAddressStatus调用成功:', res);
      
      // 更新设备状态
      if (res.Status === 1 && res.Data) {
        this.updateDeviceStatus(res.Data);
      }
    } catch (error) {
      console.error('GetRoomAddressStatus调用失败:', error);
    }
  },

  /**
   * 更新设备状态
   */
  updateDeviceStatus(data) {
    let deviceList = this.data.deviceList;
    
    // 检测data和deviceList是否有数据，若无数据则退出函数
    if (!data || !deviceList || deviceList.length === 0) return;
    
    // 先将所有设备标记为在线
    deviceList = deviceList.map(device => ({
      ...device,
      status: '在线'
    }));
    
    // 遍历设备异常数据集合data
    for (const exceptionAddr in data) {
      if (data.hasOwnProperty(exceptionAddr)) {
        // 取异常地址的前6个字符
        const exceptionAddrPrefix = exceptionAddr.toString().substring(0, 6);
        
        // 遍历设备列表
        for (let index = 0; index < deviceList.length; index++) {
          const device = deviceList[index];
          let isMatched = false;
          
          // 遍历设备的地址集合
          for (let addrIndex = 0; addrIndex < device.Addrlist.length; addrIndex++) {
            const deviceAddr = device.Addrlist[addrIndex];
            // 取设备地址的前6个字符
            const deviceAddrPrefix = deviceAddr.toString().substring(0, 6);
            
            // 比较地址前缀
            if (deviceAddrPrefix === exceptionAddrPrefix) {
              // 地址匹配，将设备标记为离线
              deviceList[index].status = '离线';
              isMatched = true;
              break; // 退出当前设备的地址循环
            }
          }
          
          if (isMatched) {
            continue; // 匹配成功，遍历下一个设备
          }
        }
      }
    }
    
    // 更新设备列表
    this.setData({
      deviceList: deviceList
    });
    
    console.log('设备状态更新完成:', deviceList);
  },

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

  },

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

  },

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

  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target,
      deviceListindex:e.currentTarget.dataset.id-1
    })
  },
  DialogModal1(e){
    let deviceList = this.data.deviceList
    let deviceListindex=this.data.deviceListindex
    const status = e.currentTarget.dataset.id
    
    // 如果选择异常，显示异常原因弹窗
    if (status === 'hideModal_0') {
      // 先设置设备状态为异常
      deviceList[deviceListindex].equipmentstatus = status
      
      // 重新计算异常数量
      const errorsNumber = deviceList.filter(device => device.equipmentstatus === 'hideModal_0').length;
      
      this.setData({
        errorReason: deviceList[deviceListindex].errorReason || "", // 显示已有的异常原因
        modalName: "DialogModal4",
        deviceList: deviceList,
        errorsNumber: errorsNumber
      })
    } else {
      // 选择正常，直接保存状态并关闭弹窗
      deviceList[deviceListindex].equipmentstatus = status
      // 清除异常原因
      deviceList[deviceListindex].errorReason = undefined
      
      // 重新计算异常数量
      const errorsNumber = deviceList.filter(device => device.equipmentstatus === 'hideModal_0').length;
      
      this.setData({
        modalName: null,
        deviceList: deviceList,
        errorsNumber: errorsNumber
      })
    }
    console.log(this.data.deviceList)
  },
  DialogModal2(e){
    this.setData({
      modalName: "DialogModal3"
    })
    console.log(this.data.deviceList)
  },

  DialogModal3(e){
    this.setData({    
      modalName:""
    })
  },

  inputSearchForHotels(e){
    this.setData({
      note: e.detail.value
    })
    console.log(this.data.note)
  },
  checkWardRoundRecords(e){
   
    wx.navigateTo({
      url: `/pages/basics/MakingRoundsAbnormal/MakingRoundsAbnormal?HotelId=${this.data.HotelId}&RoomNumber=${this.data.RoomNumber}`
    });
  },
  saveTheText(e){
    let deviceList = this.data.deviceList
    let deviceListindex=this.data.deviceListindex
    let note=this.data.note
    let noteok=e.currentTarget.dataset.id
    if (noteok==="ok") {
      deviceList[deviceListindex].note= note
    }
    this.setData({
      deviceList:deviceList,
      modalName: "DialogModal1"
    })
  },
  // 处理异常原因输入
  inputErrorReason(e){
    this.setData({
      errorReason: e.detail.value
    })
  },
  // 确认异常原因弹窗
  confirmErrorReasonModal(){
    let deviceList = this.data.deviceList
    let deviceListindex=this.data.deviceListindex
    
    // 保存异常原因到设备节点
    deviceList[deviceListindex].errorReason = this.data.errorReason
    
    this.setData({
      deviceList: deviceList,
      modalName: null, // 退出所有弹窗
      errorReason: ""
    })
    
    console.log("异常原因已保存:", deviceList[deviceListindex])
  },
  // 取消异常原因弹窗
  cancelErrorReasonModal(){
    let deviceList = this.data.deviceList
    let deviceListindex=this.data.deviceListindex
    
    // 如果还没有保存过异常原因，将设备状态改回未检测
    if (!deviceList[deviceListindex].errorReason) {
      deviceList[deviceListindex].equipmentstatus = undefined
      
      // 重新计算异常数量
      const errorsNumber = deviceList.filter(device => device.equipmentstatus === 'hideModal_0').length;
      
      this.setData({
        deviceList: deviceList,
        errorsNumber: errorsNumber
      })
    }
    
    this.setData({
      modalName: "DialogModal1", // 返回之前的弹窗
      errorReason: ""
    })
  },
  /**
   * 上传查房状态
   */
  async uploadWardRoundStatus() {
    const deviceList = this.data.deviceList
    // 检查所有设备是否已设置equipmentstatus状态
    const allSet = deviceList.every(device => device.equipmentstatus !== undefined && device.equipmentstatus !== null)
    if (!allSet) {
      app.toast(2, "请先完成所有设备的状态检测")
      return
    }
    
    try {
      // 构造请求参数
      const params = {
        HotelID: this.data.HotelId,
        RoomNumber: this.data.RoomNumber,
        EquipmentList: deviceList.map(device => ({
          EquipmentStatus: device.equipmentstatus === 'hideModal_1' ? '正常' : device.equipmentstatus === 'hideModal_0' ? '故障' : '',
          FaultDescription: device.errorReason || '',
          DevName: device.name,
          EquipmentStatusType: device.equipmentstatus === 'hideModal_1' ? '1' : device.equipmentstatus === 'hideModal_0' ? '2' : '',
          EquipmentOnlineStatus: device.status === '在线' ? '1' : '2'
        }))
      }
      
      // 调用接口上传数据
      const res = await WriteRoomVisitLog(params)
      
      // 处理返回结果
      if (res.Status === 1) {
        app.toast(1, res.Message || "上传成功")
        console.log("上传成功", res)
      } else {
        app.toast(2, res.Message || "上传失败")
        console.log("上传失败", res)
      }
    } catch (error) {
      app.toast(2, "上传失败，请检查网络连接")
      console.error("上传出错", error)
    }
  },
  /**
   * 刷新设备列表
   */
  refreshDeviceList() {
    // 调用getDeviceList函数刷新设备列表
    this.getDeviceList()
  },
})