// pages/index/index.js
const app = getApp();
var myRequest = require("../../utils/api.js");
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
import tool from "./tool.js";
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    singleSelect: {
      value: '',
      options: [],
    },
    userInfo: [],
    keys: {
      value: 'id',
      label: 'name',
    },
    slateX:'',
    label: '请选择项目',
    markers: [],
    deviceData: [],
    projectName: '',
    projectId: '',
    scale: 10,
    bottmwidth:"100%",
    slipFlag:'',
    startPoint:'',
    transfromX:[],
    pageIndex:0,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
     this.getUserLocation();
  },
  // 搜索
  search() {
    wx.navigateTo({
      url: '../search/search?userid='+this.data.userInfo.id,
    })
  },
  //获取当前位置
  getUserLocation() {
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        console.log("经纬度:",res)
        var latitude = res.latitude
        var longitude = res.longitude
        that.setData({
          latitude: latitude,
          longitude: longitude,
        })
        // that.getLocal(latitude, longitude)//在这里调用getLocal方法把经纬度传入来获取城市位置
      },
      fail: function(errInfo) {
        console.info(errInfo)
      }
    })
  },
  //获取项目下所有站点位置
  getDeviceLocation() {
    var that = this;
    myRequest.myRequest('system/devicesLocation', {
      projectId: wx.getStorageSync('projectId'),
    },'get').then(function(res){
      if (res.data.data.length == 0) {
        that.getUserLocation();
      }else {
        that.setData({
          deviceData: res.data.data,
          latitude: res.data.data[0].latitude,
          longitude: res.data.data[0].longitude,
        })
        that.setMarkersData();
      }
    }).catch(function(res){
      console.log(res);
    })
  },
  setMarkersData() {
    var deviceData = this.data.deviceData;
    var markers = [];
    for (let i = 0; i < deviceData.length; i++) {
      markers.push({
        iconPath: '../../assets/device.png',
        latitude: deviceData[i].latitude,
        longitude: deviceData[i].longitude,
        width: 30,
        height: 30,
        title: deviceData[i].name,
        id: deviceData[i].id, 
      })
    }
    this.setData({
      markers
    })
  },
  // 获取当前地理位置
  // getLocal: function (latitude, longitude) {
  //   let that = this;
  //   qqmapsdk = new QQMapWX({
  //     key: 'RQJBZ-6ZOCX-3QI4R-Z3JUH-GFDOS-YYBJ4'
  //   });
  //   console.log(qqmapsdk);
  //   qqmapsdk.reverseGeocoder({
  //     location: {
  //       latitude: latitude,
  //       longitude: longitude
  //     },
  //     success: function (res) {
  //       //这里的res参数里有具体的城市数据
  //       console.log(res); 
  //       that.setData({
  //         address: res.result.address_component.city 
  //       })
  //     },
  //     fail: function (res) {
  //       console.log(res); 
  //       that.setData({
  //         address: '定位失败' 
  //       })
  //     },
  //     complete: function (res) {
  //     }
  //   });
  // },
  handleSingleSelect(e) {
    this.setData({
      'singleSelect.value': e.detail.value,
      deviceData: [],
    });
    this.setSelectLabel(e.detail.value)
    wx.setStorageSync('projectId', e.detail.value)
    wx.setStorageSync('deviceCode','')
    this.getDeviceLocation();
  },
  setSelectLabel(value) {
    var options = this.data.singleSelect.options;
    for (let i = 0; i < options.length; i++) {
      if(options[i].id == value) {
        this.setData({
          label: options[i].name
        })
        wx.setStorageSync('projectName', options[i].name)
      }
    }
  },
  toJump(e) {
    var path = e.currentTarget.dataset.path;
    wx.navigateTo({
      url: path,
    })
  },
  getUserInfo: function()
  {
    var that = this;
    myRequest.myRequest('system/getMiniUserInfo', {}).then(function(res){
      var userInfo = res.data.data;
      let menus = userInfo.menus
      let menusArr = []
      menus.forEach((item,index)=>{
        if(!menusArr[ parseInt(index/8)]) 
         menusArr[ parseInt( index/8)]=[]
         menusArr[ parseInt( index/8)].push(item)
      })
        userInfo.menus = menusArr
      let transfromX = []
      for(let i=0;i<menusArr.length;i++){
        transfromX[i]=i/menusArr.length*100
      }
      console.log(transfromX)
      that.setData({
        userInfo: userInfo,
        transfromX:transfromX,
        bottmwidth:menusArr.length*100+'%'
      })
      that.getProjectData();
    }).catch(function(res){
      console.log(res);
    })
  },

myTouchStart(e) {
 let slipFlag = true
 let startPoint = e.touches[0]
  this.setData({
    startPoint,
    slipFlag}
  )
  //---------------------记录滑动事件信息end---------------------
},

myTouchMove:tool.throttle(function (e){
  e= e[0]
  let {startPoint,slipFlag,pageIndex,transfromX} = this.data
    if (((startPoint.clientX - e.touches[e.touches.length - 1].clientX) > 5) && slipFlag) {
     
      slipFlag = false
      pageIndex++
      if(pageIndex<transfromX.length){
        this.setData({pageIndex})
        this.setData({slateX:'-'+transfromX[pageIndex]+'%'})
      }

      return
  } else if (((startPoint.clientX - e.touches[e.touches.length - 1].clientX) < -5) && slipFlag) {
      pageIndex--
      if(pageIndex>=0){
        this.setData({pageIndex})
        this.setData({slateX:'-'+transfromX[pageIndex]+'%'})
        slipFlag = false
      }
      return
  }
  
  // ----------------监听手势左右滑事件----------------

}),
  //获取用户绑定的项目
  getProjectData: function()
  {
    var that = this;
    myRequest.myRequest('system/getProjectsByUserId', {userId:this.data.userInfo.id}).then(function(res){
      var projectData = res.data.data;
      that.setData({
        'singleSelect.options': projectData,
      });
      var projectId = that.data.projectId;
      if (projectId != '') {
        that.setSelectLabel(projectId)
      }else{
        that.setData({
          'singleSelect.value': projectData[0].id,
        });
        wx.setStorageSync('projectId', projectData[0].id)
        that.setSelectLabel(projectData[0].id)
      }
    }).catch(function(res){
      console.log(res);
    })
  },
  

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var projectId = wx.getStorageSync('projectId');
    var projectName = this.data.projectName == '' ? wx.getStorageSync('projectName') : this.data.projectName
    if (projectId && projectName) {
      this.setData({
        projectId: projectId,
        'singleSelect.value': projectId,
        label: projectName,
        projectName: projectName
      })
      this.getDeviceLocation();
    }
    this.getUserInfo();
  },

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

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

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

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

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