// pages/ranqidetails/ranqidetails.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    status: '',
    temp: '',
    humi: '',
    voltage: '',
    electric: '',
    error: '',
    oilfume: '',
    hydrocarbon: '',
    oiltemp: '',
    oilhumi: '',
    puri: '',
    fan: '',
    switchChecked: false,
    time: '',
    errorcolor: '#11EE11',
    sensor_state: 'close',
    inductor_fenstate: 'close',
    inductor_purifierstate: 'close',
    highpower_state: 'close',
    devicestate: 'offline',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    app.globalData.imei = e.imei; //修改全局变量-imei
    //获取设备列表
    wx.request({
      url: 'https://api.mpecloud.cn/iotsystem/client/allData',
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + app.globalData.token + ''
      },
      success: res => {
        if (res.data.msg == '操作成功') {
          console.log(res.data)
          //设置设备数据       
          var datas = new Array(); //创建数据
          datas = res.data.data.datas;
          //设置设备数据
          var devices = new Array();
          devices = res.data.data.devices;
          for (var i = 0; i < datas.length; i++) {
            if (e.imei == datas[i]['imei']) {
              app.globalData.productId = datas[i]['productId'];
              var str = datas[i]['dataValue'];
              var strToObj = JSON.parse(str);
              let iosDate = datas[i]['createTime'].slice(0, 22).replace(/-/g, '/').replace('T', ' ') + '+0000';
              var createdate = new Date(iosDate);
              var month = createdate.getMonth() + 1;
              if (month < 10) {
                month = "0" + month;
              }
              var day = createdate.getDate();
              if (day < 10) {
                day = "0" + day;
              }
              var hour = createdate.getHours();
              if (hour < 10) {
                hour = "0" + hour;
              }
              var min = createdate.getMinutes();
              if (min < 10) {
                min = "0" + min;
              }
              var sec = createdate.getSeconds();
              if (sec < 10) {
                sec = "0" + sec;
              }
              var cdate = month + "/" + day + " " + hour + ":" + min + ":" + sec;
              this.setData({
                id: datas[i]['imei'],
                time: cdate,
                temp: parseInt(strToObj.internal_temperature),
                humi: parseInt(strToObj.internal_humidity),

                voltage: parseInt(strToObj.power_voltage),
                electric: parseFloat(strToObj.power_electricity).toFixed(1),

                oilfume: parseFloat(strToObj.Soot_concentration).toFixed(1),
                hydrocarbon: parseFloat(strToObj.NMHC).toFixed(1),
                oiltemp: parseInt(strToObj.sensor_temperature),
                oilhumi: parseInt(strToObj.sensor_humidity),

                puri: parseFloat(strToObj.purifier_electricity).toFixed(1),
                fan: parseFloat(strToObj.fan_electricity).toFixed(1),
              })
              if (strToObj.openiostate == 0) {
                this.setData({
                  switchChecked: false,
                })
              } else {
                this.setData({
                  switchChecked: true,
                })
              }
              if (strToObj.power_error == 0) {
                this.setData({
                  error: '正常',
                  errorcolor: '#11EE11',
                })
              } else {
                this.setData({
                  error: '故障',
                  errorcolor: 'red',
                })
              }

              //油烟传感器状态
              if (strToObj.sensor_state == 0) {
                this.setData({
                  sensor_state: 'open',
                })
              } else if (strToObj.sensor_state == 1) {
                this.setData({
                  sensor_state: 'erro',
                })
              } else if (strToObj.sensor_state == 2) {
                this.setData({
                  sensor_state: 'close',
                })
              }

              //风扇状态
              if (strToObj.inductor_fenstate == 0) {
                this.setData({
                  inductor_fenstate: 'open',
                })
              } else if (strToObj.inductor_fenstate == 1) {
                this.setData({
                  inductor_fenstate: 'erro',
                })
              } else if (strToObj.inductor_fenstate == 2) {
                this.setData({
                  inductor_fenstate: 'close',
                })
              }

              //净化器状态
              if (strToObj.inductor_purifierstate == 0) {
                this.setData({
                  inductor_purifierstate: 'open',
                })
              } else if (strToObj.inductor_purifierstate == 1) {
                this.setData({
                  inductor_purifierstate: 'erro',
                })
              } else if (strToObj.inductor_purifierstate == 2) {
                this.setData({
                  inductor_purifierstate: 'close',
                })
              }

              //高压电源状态
              if (strToObj.highpower_state == 0) {
                this.setData({
                  highpower_state: 'open',
                })
              } else if (strToObj.highpower_state == 1) {
                this.setData({
                  highpower_state: 'erro',
                })
              } else if (strToObj.highpower_state == 2) {
                this.setData({
                  highpower_state: 'close',
                })
              }
            }
            if (e.imei == devices[i]['imei']) {
              app.globalData.deviceId = devices[i]['deviceId'];
              //网络状态
              if (devices[i]['isOnline'] == 0) {
                this.setData({
                  devicestate: 'offline',
                })
              } else if (devices[i]['isOnline'] == 1) {
                this.setData({
                  devicestate: 'green',
                })
              }
              //设备状态
              if (devices[i]['deviceStatus'] == 0) {
                this.setData({
                  status: '创建成功',
                })
              } else if (devices[i]['deviceStatus'] == 1) {
                this.setData({
                  status: '注册失败',
                })
              } else if (devices[i]['deviceStatus'] == 2) {
                this.setData({
                  status: '注册成功',
                })
              } else if (devices[i]['deviceStatus'] == 3) {
                this.setData({
                  status: '已激活',
                })
              }
            }
          }
        }
      },
      fail: function () {
        wx.showToast({
          title: '设备详细数据获取错误！',
          icon: 'none',
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.refreshPull();
    wx.stopPullDownRefresh();
  },

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

  },

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

  },
  refreshPull: function () {
    var imei = app.globalData.imei;
    if (imei != 0) {
      //获取设备列表
      wx.request({
        url: 'https://api.mpecloud.cn/iotsystem/client/allData',
        header: {
          'content-type': 'application/json',
          'Authorization': 'Bearer ' + app.globalData.token + ''
        },
        success: res => {
          if (res.data.msg == '操作成功') {
            console.log(res.data)
            //设置设备数据       
            var datas = new Array(); //创建数据
            datas = res.data.data.datas;
            //设置设备数据
            var devices = new Array();
            devices = res.data.data.devices;
            for (var i = 0; i < datas.length; i++) {
              if (imei == datas[i]['imei']) {
                app.globalData.productId = datas[i]['productId'];
                var str = datas[i]['dataValue'];
                var strToObj = JSON.parse(str);
                let iosDate = datas[i]['createTime'].slice(0, 22).replace(/-/g, '/').replace('T', ' ') + '+0000';
                var createdate = new Date(iosDate);
                var month = createdate.getMonth() + 1;
                if (month < 10) {
                  month = "0" + month;
                }
                var day = createdate.getDate();
                if (day < 10) {
                  day = "0" + day;
                }
                var hour = createdate.getHours();
                if (hour < 10) {
                  hour = "0" + hour;
                }
                var min = createdate.getMinutes();
                if (min < 10) {
                  min = "0" + min;
                }
                var sec = createdate.getSeconds();
                if (sec < 10) {
                  sec = "0" + sec;
                }
                var cdate = month + "-" + day + " " + hour + ":" + min + ":" + sec;
                this.setData({
                  id: datas[i]['imei'],
                  time: cdate,
                  temp: parseInt(strToObj.internal_temperature),
                  humi: parseInt(strToObj.internal_humidity),

                  voltage: parseInt(strToObj.power_voltage),
                  electric: parseFloat(strToObj.power_electricity).toFixed(1),

                  oilfume: parseFloat(strToObj.Soot_concentration).toFixed(1),
                  hydrocarbon: parseFloat(strToObj.NMHC).toFixed(1),
                  oiltemp: parseInt(strToObj.sensor_temperature),
                  oilhumi: parseInt(strToObj.sensor_humidity),

                  puri: parseFloat(strToObj.purifier_electricity).toFixed(1),
                  fan: parseFloat(strToObj.fan_electricity).toFixed(1),
                })
                if (strToObj.openiostate == 0) {
                  this.setData({
                    switchChecked: false,
                  })
                } else {
                  this.setData({
                    switchChecked: true,
                  })
                }
                if (strToObj.power_error == 0) {
                  this.setData({
                    error: '正常',
                    errorcolor: '#11EE11',
                  })
                } else {
                  this.setData({
                    error: '故障',
                    errorcolor: 'red',
                  })
                }

                //油烟传感器状态
                if (strToObj.sensor_state == 0) {
                  this.setData({
                    sensor_state: 'open',
                  })
                } else if (strToObj.sensor_state == 1) {
                  this.setData({
                    sensor_state: 'erro',
                  })
                } else if (strToObj.sensor_state == 2) {
                  this.setData({
                    sensor_state: 'close',
                  })
                }

                //风扇状态
                if (strToObj.inductor_fenstate == 0) {
                  this.setData({
                    inductor_fenstate: 'open',
                  })
                } else if (strToObj.inductor_fenstate == 1) {
                  this.setData({
                    inductor_fenstate: 'erro',
                  })
                } else if (strToObj.inductor_fenstate == 2) {
                  this.setData({
                    inductor_fenstate: 'close',
                  })
                }

                //净化器状态
                if (strToObj.inductor_purifierstate == 0) {
                  this.setData({
                    inductor_purifierstate: 'open',
                  })
                } else if (strToObj.inductor_purifierstate == 1) {
                  this.setData({
                    inductor_purifierstate: 'erro',
                  })
                } else if (strToObj.inductor_purifierstate == 2) {
                  this.setData({
                    inductor_purifierstate: 'close',
                  })
                }

                //高压电源状态
                if (strToObj.highpower_state == 0) {
                  this.setData({
                    highpower_state: 'open',
                  })
                } else if (strToObj.highpower_state == 1) {
                  this.setData({
                    highpower_state: 'erro',
                  })
                } else if (strToObj.highpower_state == 2) {
                  this.setData({
                    highpower_state: 'close',
                  })
                }
              }
              if (imei == devices[i]['imei']) {
                app.globalData.deviceId = devices[i]['deviceId'];
                //网络状态
                if (devices[i]['isOnline'] == 0) {
                  this.setData({
                    devicestate: 'offline',
                  })
                } else if (devices[i]['isOnline'] == 1) {
                  this.setData({
                    devicestate: 'green',
                  })
                }
                //设备状态
                if (devices[i]['deviceStatus'] == 0) {
                  this.setData({
                    status: '创建成功',
                  })
                } else if (devices[i]['deviceStatus'] == 1) {
                  this.setData({
                    status: '注册失败',
                  })
                } else if (devices[i]['deviceStatus'] == 2) {
                  this.setData({
                    status: '注册成功',
                  })
                } else if (devices[i]['deviceStatus'] == 3) {
                  this.setData({
                    status: '已激活',
                  })
                }
              }
            }
          }
        },
        fail: function () {
          wx.showToast({
            title: '设备详细数据获取错误！',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  },
  RetClick: function (e) {
    var that = this;
    //跳转到设备列表
    wx.switchTab({
      url: '../homefree/homefree'
    })
  },
  REshClick: function () {
    wx.request({
      url: 'https://api.mpecloud.cn/iotsystem/command',
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + app.globalData.token + ''
      },
      data: {
        "commandValue": "{\"refreshing\":\"1\"}",
        "createBy": "admin",
        "createUserName": app.globalData.userid,
        "deviceId": app.globalData.deviceId,
        "identifier": "issue_refresh",
        "productId": app.globalData.productId,
        "serviceId": 8008,
        "serviceName": "刷新数据指令",
        "serviceType": "Command",
      },
      method: 'post',
      success: res => {
        console.log(res.data)
        wx.showToast({
          title: '刷新成功',
          icon: 'none',
          duration: 2000
        })
      },
      fail: function () {
        wx.showToast({
          title: '无法刷新数据！',
          icon: 'none',
          duration: 2000
        })
      }

    })
  },
  switchChange: function (e) {
    var swithstate = 0;
    if (e.detail.value == true) {
      swithstate = 1;
    }
    console.log(e.detail.value);

    console.log(app.globalData.userid);
    console.log(app.globalData.deviceId);
    console.log(app.globalData.productId);
    console.log(app.globalData.token);
    wx.request({
      url: 'https://api.mpecloud.cn/iotsystem/command',
      header: {
        'content-type': 'application/json',
        'Authorization': 'Bearer ' + app.globalData.token + ''
      },
      data: {
        "commandValue": "{\"openiostate\":\"" + swithstate + "\"}",
        "createBy": "admin",
        "createUserName": app.globalData.userid + "",
        "deviceId": app.globalData.deviceId + "",
        "identifier": "remote_control",
        "productId": app.globalData.productId + "",
        "serviceId": "8005",
        "serviceName": "远程开关控制",
        "serviceType": "Command",
      },
      method: 'post',
      success: res => {
        console.log(res.data)
        wx.showToast({
          title: '远程开关设备已成功！',
          icon: 'none',
          duration: 2000
        })
      },
      fail: function () {
        wx.showToast({
          title: '无法远程开关设备！',
          icon: 'none',
          duration: 2000
        })
      }

    })

  }
})