// pages/Security-control-echarts/index.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {

        biaoyangList: {},
        peidianList: [{
            text: '配电箱监测',
            id: 0
        }],
        PWRList: [{
            text: 'PWR.02731XTJ',
            id: 0
        }],
        indexNum: 0,
        indexNums: 0,
        lastChooseDevice: {},
        startTime: '',
        endTime: '',
        initData: {},
        projectId: '',
        projectData: {},
        tumidityTrendData:{},
        show:false
    },
    onClickBtn(e){
        this.setData({
            indexNum:e.currentTarget.dataset.set
        })
       this.onClickTemperatureTrend(e.currentTarget.dataset.set)
    },
    onClickBtns(e){
        this.setData({
            indexNums:e.currentTarget.dataset.set
        })
        this.onClickTumidityTrend(e.currentTarget.dataset.set)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this;
          //获取缓存数据
          wx.getStorage({
            key: 'userinfo',
            success:function(res){
              that.setData({
                loginName:res.data.loginName,
                userName:res.data.userName,
                projectId:app.globalData.projectId,
                projectNameArgs:app.globalData.projectName,
                initData:{text:app.globalData.projectName,id:app.globalData.projectId}
              })  
            }
          })
        that.setData({
            endTime:that.dateFormat(new Date(),"yyyy-MM-dd")+ " 23:59:59"
         })
        that.getProjectCorrespondence(app.globalData.projectId)
    },

    /**
    * 项目对应关系
    */
  getProjectCorrespondence(projectId) {
    var that = this;
    wx.request({
      url: app.globalData.reqUrl + '/weixin/training/getProjectCorrespondence',
      data: {
        "projectId": projectId,
      },
      method: "get",
      success: function (res) {
        that.setData({
          projectData: res.data
        })
       //获取设备列表
       that.gainDeviceList()
      }
    })
  },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },

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

    },
    //获取配电箱装置
    gainDeviceList() {
        let that = this
        wx.request({
            url: app.globalData.szhUrl + '/api/iot/power/deviceList',
            data: {
                typeName: "配电箱"
            },
            method: "POST",
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            success: function (res) {
                for(let row of res.data.rows){
                    row.id = row.deviceId
                    row.text = row.deviceId
                }
                that.setData({
                    selectData :res.data.rows,
                    lastChooseDevice:res.data.rows[0]
                })
                //温度监控
                that.onClickTemperatureTrend(that.data.indexNum)
                that.onClickTumidityTrend(that.data.indexNums)
            }
        })
    },
     //温度趋势
     onClickTemperatureTrend(n) {
         var that = this
         that.setData({
            indexNum:n,
            endTime:that.dateFormat(new Date(),"yyyy-MM-dd")+ " 23:59:59"
         })
         
        if (n == 0) {
            var time =  that.getBeforeDate(-6)+" 00:00:00"
            that.setData({
                startTime:time
            })
        } else {
            var time =  that.getBeforeDate(-29)+" 00:00:00"
            that.setData({
                startTime:time
            })
        }
        wx.request({
            url: app.globalData.szhUrl + '/api/iot/power/runList',
            data: {
                projectId: parseInt(that.data.projectData.szh),
                uid: that.data.lastChooseDevice.deviceId,
                startTime: that.data.startTime,
                endTime: that.data.endTime
            },
            header: {
                'content-type': 'application/x-www-form-urlencoded'
            },
            method: "POST",
            success: function (res) {
                if (res.data.code == 0) {
                    var data = {}
                    data.lineData = []
                    data.color = ['#008ffd', '#f6d023', '#5af9fd', '#fc6902']
                    data.legend = ['A相温度', 'B相温度', 'C相温度', '零线温度']
                    data.unit = '℃'
                    data.date = []
                    var data1 = []
                    var data2 = []
                    var data3 = []
                    var data4 = []
                    for (let row of res.data.rows) {
                        data.date.push((row.time.slice(0, row.time.length - 3)))
                        data1.push(row.t1)
                        data2.push(row.t2)
                        data3.push(row.t3)
                        data4.push(row.t4)
                    }
                    data.lineData.push(data1)
                    data.lineData.push(data2)
                    data.lineData.push(data3)
                    data.lineData.push(data4)
                    that.setData({
                        biaoyangList: data
                    })
                } else {
                    that.setData({
                        biaoyangList:{}
                    })
                }
            }
        })
    },
    //电流监控
    onClickTumidityTrend(n) {
        var that = this
        that.setData({
           indexNums:n,
           endTime:that.dateFormat(new Date(),"yyyy-MM-dd")+ " 23:59:59"
        })
        
       if (n == 0) {
           var time =  that.getBeforeDate(-6)+" 00:00:00"
           that.setData({
               startTime:time
           })
       } else {
           var time =  that.getBeforeDate(-29)+" 00:00:00"
           that.setData({
               startTime:time
           })
       }
       wx.request({
           url: app.globalData.szhUrl + '/api/iot/power/runList',
           data: {
               projectId: parseInt(that.data.projectData.szh),
               uid: that.data.lastChooseDevice.deviceId,
               startTime: that.data.startTime,
               endTime: that.data.endTime
           },
           header: {
               'content-type': 'application/x-www-form-urlencoded'
           },
           method: "POST",
           success: function (res) {
            if (res.data.code == 0) {
                var data = {}
                data.lineData = []
                data.color = ['#008ffd', '#f6d023', '#5af9fd', '#fc6902']
                data.legend = ['A相电流', 'B相电流', 'C相电流', '电流阈值']
                data.unit = 'A'
                data.date = []
                var data1 = []
                var data2 = []
                var data3 = []
                var data4 = []
                for (let row of res.data.rows) {
                    data.date.push((row.time.slice(0, row.time.length - 3)))
                    data1.push(row.c1)
                    data2.push(row.c2)
                    data3.push(row.c3)
                    data4.push(131)
                }
                data.lineData.push(data1)
                data.lineData.push(data2)
                data.lineData.push(data3)
                data.lineData.push(data4)
                that.setData({
                    tumidityTrendData: data
                })
            }else {
                that.setData({
                    tumidityTrendData:{}
                })
            }
           }
       })
    },
    /**
   * 格式化时间
   */
  dateFormat(date,fmt) {
    let ret;
    const opt = {
        "y+": date.getFullYear().toString(),        // 年
        "M+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "m+": date.getMinutes().toString(),         // 分
        "s+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
  },
  //获取之前的时间
  getBeforeDate(num) {
      var date1 = new Date()
      var date2 = new Date(date1)
      date2.setDate(date1.getDate() + num)
      var time2 = date2.getFullYear() + "-" + ((date2.getMonth() + 1) <= 9?"0"+(date2.getMonth() + 1):(date2.getMonth() + 1)) + "-" + date2.getDate()
      return time2
  },
  //项目切换 返回值
  onProjectSelect(e){
    var that = this
    let projectId = e.detail.id;
    let projectName = e.detail.text;
    app.globalData.projectId = projectId;
    app.globalData.projectName = projectName;  
    that.setData({
      projectId:projectId,
      projectName:projectName
    })

    that.onLoad();
  },
  //返回到安全管理页面
  goGCLB:function(){
    wx.redirectTo({
      url:'../newAddPage/safetyManagement/index'
    })
  },
  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },
  //配电箱改变
  peidianChange(e){
    console.log(e)
  },
  //设备改变
  pwdChange(e){
    console.log(e)
  },
})