//index.js
//获取应用实例
const app = getApp()
const HttpSever = require('../../../utils/http.js').HttpSever;
const $api = require('../../../config/api.js').$api;

Component({
  behaviors: [],
  properties: {},
  data: {
    UserInfo: app.globalData.UserInfo,
    EstateList: [{
      Name: '示例数据',
      Address: '江北 白马路',
      Distance: '21',
      Price: '1.8',
      Img: '/assets/images/img1.jpg'
    }, {
      Name: '示例数据',
      Address: '江北 白马路',
      Distance: '21',
      Price: '1.8',
      Img: '/assets/images/img1.jpg'
    }, {
      Name: '示例数据',
      Address: '江北 白马路',
      Distance: '21',
      Price: '1.8',
      Img: '/assets/images/img1.jpg'
    }]
  },
  lifetimes: {},
  ready: function() {
    const _that = this
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success() {
              _that.ShowLocation()
            }
          })
        } else {
          _that.ShowLocation()
        }
      }
    })
  },
  pageLifetimes: {
    show: function() {},
  },
  methods: {
    ListTap() { // 跳转楼盘详情
      wx.navigateTo({
        url: '/pages/EstateDetail/index?id='
      })
    },
    GetGreatCircleDistance(lat1, lng1, lat2, lng2) {
      if (lat1 === lat2 && lng1 === lng2) {
        return 0
      }
      var EARTH_RADIUS = 6378137.0//单位M
      var PI = Math.PI
      var radLat1 = lat1 * PI / 180.0
      var radLat2 = lat2 * PI / 180.0
      var a = radLat1 - radLat2
      var b = lng1 * PI / 180.0 - lng2 * PI / 180.0
      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
      s = s * EARTH_RADIUS
      s = Math.round(s * 10000) / 10000.0
      console.log(s)
      return s
    },
    ShowLocation() {
      const _that = this
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          console.log(res)
          HttpSever.Ajax({
            url: $api.building.list.url,
            method: $api.building.list.method,
          }).then((data) => {
            const eslist = data.data.map(x => {
              const distance = parseInt(_that.GetGreatCircleDistance(res.latitude, res.longitude, x.coordinate.split(',')[0], x.coordinate.split(',')[1] || res.longitude))
              return {
                buildingName: x.buildingName,
                price: x.price,
                address: x.address,
                buildingImg: (x.buildingImg[0] || {}).url,
                distance: distance / 1000
              }
            })
            _that.setData({
              EstateList: eslist
            })
          })
        }
      })
    }
  }
})