// pages/server_point/server_point.js
const { api, rapi, formatTime, imgName, getUserInfo, wxLogin, alertTip, authAgainByUser, userLocation } = require('../../lib/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    first: true,
    imgLoc: imgName('pointloc.png'),
    imgNav: imgName('navigate.png'),
    imgPhone: imgName('security_settings_telephone_active.png'),
    imgLogo: imgName('logo.png'),
    activeIndex: 0,
    page: 1,//当前页面
    totalPage:1,
    hasMorePage:false,
    pointLists: [],//站点列表
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getPointLists()
  },
  //站点
  toPoint(e) {
    let that = this
    let { point } = e.currentTarget.dataset
    wx.openLocation({
      latitude: Number(point.latitude),
      longitude: Number(point.longitude),
      scale: 28
    })
  },
  //获取站点列表
  getPointLists() {
    let curPage =this.data.page
    let that = this
    userLocation()
      .then(res => {
        let { longitude: lng, latitude: lat } = res
        api.get('site/getNodeList', {
          lng,
          lat,
          curPage
        })
          .then(res => {
            let listArrays = res.items.map(item => { item.distance = item.distance.toFixed(1); return item })
            //首页)
            if (curPage == 1) {
              this.setData({
                pointLists: listArrays,
                page: res.page+1,
                totalPage: res.totalPage,
                hasMorePage: res.page<res.totalPage
              })
            } else {
              let newPoints = that.data.pointLists.concat(listArrays)
              this.setData({
                pointLists: newPoints,
                page: res.page + 1,
                totalPage: res.totalPage,
                hasMorePage: res.page < res.totalPage
              })
            }
          })
          .catch(err => {
            alertTip(err, () => {
              wx.navigateBack()
            })
          })
      })
      .catch(err => {
        alertTip('你拒绝了地理定位，请打开后重试', () => {
          wx.navigateBack()
        })
      })
  },

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

  },

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

  },
  //拨打电话
  callPointPhone(e) {
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.id
    })
  }
})