// 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 upgrader = new DeviceUpgrader();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    RoomNumber:"",
    HotelName:"",
    HotelId:"",
    HotelCode:"",
    roomtypeid:"",
    devNode:null,
    Gfilename:"",
    Pfilename:"",
    TabCur:1,
    scrollHeight:0,
    Completed:false,    //是否处于升级状态
    CurrentUpgradeDev:'', //当前升级设备
    CurrentUpgradeDevStart:'',//当前升级设备状态
    UpgradeCount:0,      //已升级设备数量
    UpgradeAllCount:1,   //总升级设备数量
    // 回路调试相关数据
    roomtypeInfoNode:{},
    roomtypeInfoNodeinfo:[],
    VolumeLevel:30,
    showinfo:0,
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function(options){
    // 初始化升级器事件监听
    upgrader.on('progress', p => {
      console.log(p)
      this.setData({ CurrentUpgradeDevStart: p })   // 实时刷新 UI
    })
    upgrader.on('error', e => {
      wx.showToast({ title: '升级失败', icon: 'none' })
    })
  
    if (!options.RoomNumber  || !options.HotelName ||!options.HotelId ||!options.roomtypeid ||!options.HotelCode||!options.createTime){ 
      app.toast(2, "无酒店信息~") 
      return; 
    }
    console.log(options.RoomNumber)
    this.setData ({
      RoomNumber:options.RoomNumber,
      HotelName:options.HotelName,
      HotelId:options.HotelId,
      roomtypeid:options.roomtypeid,
      HotelCode:options.HotelCode,
      createTime:options.createTime
    })
    try { 
      
      // 调用 GetRoomTypeNode 
      const res = await GetRoomTypeNode({ 
        hotelid:options.HotelId,
        roomTypeID: options.roomtypeid
      }); 
      if (res.IsSuccess==true) {
      let  devlist = res.HostData
        for (let nindex = 0; nindex < devlist.length; nindex++) {
          if (devlist[nindex].RoomNumber==options.RoomNumber) {
            devlist[nindex].Model =devlist[nindex].Model.trim().replace(/\0/g, "")
            console.log(devlist[nindex].Model)
            this.setData ({
              devNode:devlist[nindex]             
            })
            break
          }
        }
      }
        const Nres  = await  GetRoomType({ 
        HotelID:options.HotelId,
      })
      let Gfilename=""
  let Pfilename=""
if (Nres.Status==200) {
  let Roomtypeinfo=Nres.Data
  
  for (let index = 0; index < Roomtypeinfo.length; index++) {
    const element = Roomtypeinfo[index];
 
    if (element.ROOM_TYPE_OLD_ID == options.roomtypeid) {
      
      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
    }
    
  }
 }
 await GetRoomTypeAndModalsListLog({
  code:options.HotelCode
}).then(res =>{
  if (res.IsSuccess==true) {
 
    for (let index = 0; index < res.Result.length; index++) {
      const element = res.Result[index];
      if (element.ID == options.roomtypeid) {
        this.setData({ 
          roomtypeInfo:res.Result,
          roomtypeInfoNodeinfo:element.Modals
        }) 
        break
      }
    }
    console.log(this.data.roomtypeInfoNodeinfo)
    this.LoopDebugging(null)
  }
})


      this.setData({       
        Pfilename:Pfilename,
        Gfilename:Gfilename,
      }); 
    
    } catch (err) { 
      console.log('GetRoomTypeNode error', err); 
    } 

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

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

  },

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

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  // 手动关闭升级进度显示
  closeUpgradeProgress() {
    this.setData({
      Completed: false
    })
  },

  onShareAppMessage() {

  },
  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();
  },
  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id,      
    })
  },

  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 UpgradeType = ""
    let filename = ""
    let _this = this
    let RoomTypeID = this.data.roomtypeid
    let HotelId = this.data.HotelId
    let devNode = this.data.devNode

    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
    }

    _this.setData({
      UpgradeCount: 0,  //升级计数
      CurrentUpgradeDev: devNode.RoomNumber, //当前升级设备
      CurrentUpgradeDevStart: '升级就绪',//当前升级设备状态
      Completed: true,
      UpgradeAllCount: 1,//升级总数
    })

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

      _this.DisplayPrompt2("升级完成！", 1000)
    } catch (error) {
      _this.setData({
        CurrentUpgradeDev: devNode.RoomNumber, //当前升级设备
        CurrentUpgradeDevStart: errstr + '，服务器响应异常',//当前升级设备状态
      })
      // this.DisplayPrompt(errstr + '，服务器响应异常', 1000)
      return
    }
  },

  DisplayPrompt2(tipstr, showtime) {
    wx.showToast({
      title: tipstr,
      icon: 'none',
      duration: showtime
    })
  },

  DisplayPrompt(tipstr, showtime) {
    wx.showToast({
      title: tipstr,
      icon: 'none',
      duration: showtime
    })
  },

  LoopDebugging:async function (e)
  {
    // 
   
    let roomtypeInfoNodeinfo=this.data.roomtypeInfoNodeinfo
    let addrtype
    const myMap =[]
    let li =[]
    let addrtypelist =true
  
   let message =this.data.message
    for (let index = 0; index < roomtypeInfoNodeinfo.length; index++) {
      const element = roomtypeInfoNodeinfo[index];
      addrtype=this.GetloopType(element.ModalAddress)   
      if (addrtype.length==0) {
        continue 
      }
      addrtypelist=true
      for (let index2 = 0; index2 < myMap.length; index2++) {
        const element2 = myMap[index2];
      
        if (  element2[0] == addrtype[0][0]) {
          li= myMap[index2][1]
          li.push([element.ModalAddress,element.Name,addrtype[0][1]])
          myMap[index2][1]=li
          addrtypelist=false
          break
        }
      }
      
      if (addrtypelist) {
        li=[]
        li.push([element.ModalAddress,element.Name,addrtype[0][1]])
        myMap.push([addrtype[0][0],li])
      }


    }

    roomtypeInfoNodeinfo=myMap.sort((a, b) => a[0] - b[0])
    //获取房间在线状态  roomstart
    console.log(roomtypeInfoNodeinfo)

  


 
    this.setData({ 
      roomtypeInfoNodeinfo:roomtypeInfoNodeinfo
    })
    console.log(this.data.roomtypeInfoNode)
  },
  GetloopType(loopaddr){
    let astr =loopaddr[0]+loopaddr[1]+loopaddr[2]
    let aint =parseInt(astr,10)
    let bint =[]
 
   switch (aint) {
     case 1 :
     // case 4 :
     // case 54:
     bint.push([1,[[1,'开关',0]]])//开关
     break;
     case 5: //开关停   
     bint.push([5,[[1,'开关',0]]])
         break;
         case 7: //开关停 
     
         bint.push([7,[[1,'开关',0],[2,'模式',1],[3,'风速',1],[4,'温度',25],[5,'阀开',0]]])
             break;
     case 23 :
     case 24:
       bint.push([23,[[1,'开关',10]]])
           break;
     case 52:
            bint.push([52,[[1,'开关',0],[2,'亮度',10],[3,'色温',10]]])
             break;    
     default:
       
       break;
   }
 
   return  bint
  },
 
  // 播放欢迎词
  GetshowinfoClick() {
    this.setData({
      showinfo: this.data.showinfo + 1
    })
  },

  // 调整音量
  changeVolumeLevel(e) {
    this.setData({
      VolumeLevel: e.detail.value
    })
  },

  // 设置设备开关状态
  SetDeviceSwitchStatus(e) {
    let devarr = e.target.dataset.index
    let devval = parseInt(e.target.dataset.value)
    let ID = parseInt(e.target.id)
    let type = e.target.dataset.type
    this.SetDevStartToHostMachine(ID, devarr, devval, type)
    console.log(e)
  },

  // 设置设备调光亮度
  SetDeviceSwitchStatusslider(e) {
    let devarr = e.target.dataset.index
    let devval = parseInt(e.detail.value)
    let ID = parseInt(e.target.id)
    this.SetDevStartToHostMachine(ID, devarr, devval, 0)
    console.log(e)
  },

  // 设备控制主方法
  SetDevStartToHostMachine: async function (id, devarr, Handletype, type) {
    let roomtypeInfoNodeinfo = this.data.roomtypeInfoNodeinfo
    let narry = []
    for (let index = 0; index < roomtypeInfoNodeinfo.length; index++) {
      const element = roomtypeInfoNodeinfo[index];
      if (element[0] === id) {
        for (let nindex = 0; nindex < element[1].length; nindex++) {
          const nelement = element[1][nindex];
          if (nelement[0] === devarr) {
            narry = this.SetloopDataChange(id, nelement[2], Handletype, type)
            let iset = await this.ControlStatusMainCircuit(id, narry, devarr)
            if (iset) {
              roomtypeInfoNodeinfo[index][1][nindex][2] = narry
              this.setData({
                roomtypeInfoNodeinfo: roomtypeInfoNodeinfo
              })
            }
            return
          }
        }
        return
      }
    }
  },

  // 回路数据变更
  SetloopDataChange(id, dataarry, Handletype, type) {
    let result = []
    switch (id) {
      case 1:
        if (dataarry[0][2] == 1) {
          dataarry[0][2] = 0
        } else {
          dataarry[0][2] = 1
        }
        result = dataarry
        break;
      case 23:
      case 5:
        dataarry[0][2] = Handletype
        result = dataarry
        break;
      case 52:
        let devval = parseInt(type)
        if (devval == 1) {
          if (dataarry[devval - 1][2] == 1) {
            dataarry[devval - 1][2] = 0
            result = dataarry
          } else {
            dataarry[devval - 1][2] = 1
            result = dataarry
          }
        } else {
          dataarry[devval - 1][2] = Handletype
          result = dataarry
        }
        break;
      case 7:
        let bevval = parseInt(type)
        switch (bevval) {
          case 1:
            if (dataarry[bevval - 1][2] == 1) {
              dataarry[bevval - 1][2] = 0
              result = dataarry
            } else {
              dataarry[bevval - 1][2] = 1
              result = dataarry
            }
            break;
          case 3:
          case 2:
            if (dataarry[bevval - 1][2] == 4) {
              dataarry[bevval - 1][2] = 1
            } else {
              dataarry[bevval - 1][2] = dataarry[bevval - 1][2] + 1
            }
            break;
          case 4: // -
            if (dataarry[bevval - 1][2] == 16) {
              break;
            } else {
              dataarry[bevval - 1][2] = dataarry[bevval - 1][2] - 1
            }
            break
          case 5: // +
            if (dataarry[bevval - 2][2] == 32) {
              break;
            } else {
              dataarry[bevval - 2][2] = dataarry[bevval - 2][2] + 1
            }
            break;
          default:
            break;
        }
        result = dataarry
        break;
      default:
        break;
    }
    return result
  },

  // 控制状态主回路
  ControlStatusMainCircuit: async function (id, dataarry, addr) {
    let RoomNumber = this.data.RoomNumber
    let HotelId = this.data.HotelCode
    let devNode = this.data.devNode
    let res = []
    let sw = dataarry[0][2]

    // 解析.NET风格的日期格式 "/Date(1473004800000)/"
    let dotNetDate = this.data.createTime
    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}`

    switch (id) {
      case 1:
        sw = sw == 1 ? 1 : 2
        res = await SetRCULight({
          roomNumber: RoomNumber,
          code: HotelId,
          creatDate: CreateTime,
          status: sw,
          modalAddress: addr,
          brightness: 0
        })
        break;

      case 5:
        res = await SetRCUCurtain({
          roomNumber: RoomNumber,
          code: HotelId,
          creatDate: CreateTime,
          modalAddress: addr,
          status: sw
        })
        break
      case 7:
        res = await SetRCUAir({
          roomNumber: RoomNumber,
          code: HotelId,
          creatDate: CreateTime,
          modalAddress: addr,
          onOff: sw,
          temperature: dataarry[3][2],
          fanSpeed: dataarry[2][2] == 4 ? 0 : dataarry[2][2],
          mode: dataarry[1][2] == 4 ? 0 : dataarry[1][2],
          valve: 1
        })
        break
      case 23:
        res = await SetRCULight({
          roomNumber: RoomNumber,
          code: HotelId,
          creatDate: CreateTime,
          status: sw == 0 ? 2 : 1,
          modalAddress: addr,
          brightness: sw
        })
        break;
      default:
        return false
        break;
    }

    if (res.IsSuccess == true) {
      return true
    }
    return false
  },
})