//index.js
import fetch from '../../../utils/http'

//获取应用实例
const app = getApp()

const $api = require('../../../config/api.js').$api;

Component({
  behaviors: [],
  properties: {},
  data: {
    UserInfo: app.globalData.UserInfo,
    EstateList: []
  },
  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(e) { // 跳转楼盘详情
      wx.navigateTo({
        url: '/pages/EstateDetail/index?id=' + e.currentTarget.dataset.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
      return s/100
    },
    ShowLocation() {
      const _that = this
      wx.getLocation({
        type: 'wgs84',
        success(res) {
          fetch({
            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 {
                buildingId: x.buildingId,
                buildingName: x.buildingName,
                price: x.price,
                address: x.address,
                buildingImg: (x.buildingImg[0] || {}).url,
                distance: distance / 10
              }
            })
            _that.setData({
              EstateList: eslist
            })
          })
        }
      })
    }
  }
})