// miniprogram/pages/applog/applog.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    startX: 0, //开始坐标
    startY: 0,
    buttonClicked: false,
    deviceloglist: [],
    isSeach: "false",
    params: {},
    total: 0,
    show: false,
    delBtnWidth: 100, //删除按钮宽度单位（rpx）
    activeIndex: -1,
    list_style: ''
  },
  onLoad: function (options) {
      console.log('-----', options, options.params);
    if (options.params) {
      this.setData({
        params: JSON.parse(options.params),
        isSeach: "true"
      })
      this.initPages(true)
    }
    // else{
    //   this.setData({
    //     show: false
    //   })
    //   //清空参数，重新加载
    //   this.clearParams();
    //   this.initPages();
    // }

  },

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

  },

  //点击tabBar事件
  onTabItemTap(item) {
    //隐藏历史显示总记录条数
    this.setData({
      show: false
    })
    //清空参数，重新加载
    this.clearParams();
    this.initPages(true);
  },


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

    // this.setData({
    //   show: false
    // })
    // if (this.data.isSeach == "false") {
    //   this.clearParams();
    //   this.initPages();
    // }
    // this.setData({
    //   isSeach: "false"
    // })
  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
      console.log('触发下拉刷新');
    this.initPages(true)
  },

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

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

  },


  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.deviceloglist.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      deviceloglist: this.data.deviceloglist
    })
  },

  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.deviceloglist.forEach(function (v, i) {
      // v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      deviceloglist: that.data.deviceloglist
    })
  },

  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  //删除事件
  delItem: function (e) {
    console.log(app.globalData.role, ']]]]]]]');
    if(app.globalData.role!='repair'){
      wx.showToast({
        icon: 'none',
        title: '无权限删除',
        duration:2000
      })
      return false
    }
    var that = this
    wx.showModal({
      content: '是否删除？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            method: "POST",
            url: app.globalData.httpsUrl + "appDeviceAdd/delete",
            data: {
              appDeviceAddId: e.currentTarget.dataset.devid
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
            },
            success(res) {
              if(res.data.code=='200'){
                that.data.deviceloglist.splice(e.currentTarget.dataset.index, 1)
                that.setData({
                  deviceloglist: that.data.deviceloglist,
                  total:  that.data.deviceloglist.length
                })
                wx.showToast({
                  title: '删除成功!',
                  icon: 'none',
                  duration: 1000
                })
              }
            },
            fail(err) {
              wx.showToast({
                title: '删除失败!',
                icon: 'none',
                duration: 2000
              })
            }
          })
        } else { //这里是点击了取消以后 
          console.log('用户点击取消')
        }
      }
    })
  },

  showLoading: function (message) {
    if (wx.showLoading) {
      // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
      wx.showLoading({
        title: message,
        mask: true
      });
    } else {
      // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
      wx.showToast({
        title: message,
        icon: 'loading',
        mask: true,
        duration: 20000
      });
    }
  },
  hideLoading: function () {
    if (wx.hideLoading) {
      // 基础库 1.1.0 微信6.5.6版本开始支持，低版本需做兼容处理
      wx.hideLoading();
    } else {
      wx.hideToast();
    }
  },

  clearParams: function () {
    this.setData({
      params: {},
      deviceloglist: []
    })
  },
  //查询列表数据
  initPages: function (needClear = false) {
    var that = this
    that.setData({
      show: false
    })
      if(needClear) {
     var offsetValue = 1
   } else {
     var offsetValue = that.data.deviceloglist.length % 15 > 0 ? parseInt(that.data.deviceloglist.length / 15) + 2 : parseInt(that.data.deviceloglist.length / 15) + 1
   }

    wx.request({
      method: "POST",
      url: app.globalData.httpsUrl + "appDeviceLog/listPage",
      data: {
        project: that.data.params.project || app.globalData.selectProjectName,
        devcode: that.data.params.devcode,
        devtype: that.data.params.devtype,
        installtimeFmt: that.data.params.installtimeFmt,
        // project: that.data.params.project,
        installPerson: that.data.params.installPerson,
        limit: 15,
        offset: offsetValue
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success(res) {
        if (res.data.data.rows.length > 0) {
          var resultJson = res.data
          var listArr = resultJson.data.rows
          listArr.forEach(function (v, i) {
            listArr[i]['isTouchMove'] = false
          })
            if(needClear) {
                that.setData({
                    deviceloglist: listArr
                })
            } else {
                that.setData({
                    deviceloglist: that.data.deviceloglist.concat(listArr)
                })
            }
        } else if (that.data.deviceloglist.length > 0) {
          that.setData({
            show: true,
            total: that.data.deviceloglist.length
          })
          wx.showToast({
            title: '数据已全部加载完',
            icon: 'none',
            duration: 2000
          })
        }
        if (offsetValue == 1 && res.data.data.rows.length < 15) {
          that.setData({
            show: true,
            total: that.data.deviceloglist.length
          })
        }
        wx.stopPullDownRefresh() // 下拉刷新回弹
      }
    })

  },

  addDetail: function (event) {
    var that = this
    that.showLoading("数据请求中...");
    wx.request({
      method: "POST",
      url: app.globalData.httpsUrl + "appDeviceLog/deviceDetail",
      data: {
        devcode: event.target.dataset.devcode,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      success(res) {
        that.hideLoading();
        // var resultObject = JSON.parse(res.data);
        var resultObject = res.data;
        var pageName = '../applog/applog'
        if (resultObject.code == 200) {
            wx.setStorageSync('resultObject', resultObject.data)
          wx.navigateTo({
            url: '../addDevicelog/addDeviceLog?detail=' + "&pageName=" + pageName
          })
        }
      },
      fail(err) {
        that.hideLoading();
      }
    })

  },
  add: function (event) {
    app.globalData.devcode = event.target.dataset.devcode;
    wx.switchTab({
      url: '../earth/earth'
    })
    // wx.reLaunch({
    //   url: '../earth/earth?devcode=' + event.target.dataset.devcode
    //   // url: '../earth/earth'
    // })
  },
  onSearch: function () {
      var _this = this
    wx.navigateTo({
      url: '../searchLog/searchLog?params=' + JSON.stringify(_this.data.params)
    })
  }
})