<template>
  <view>
    <!-- H5定位必须运行在HTTPS协议下（开发环境localhost除外） -->
    <button @click="getLocation">获取当前位置</button>
    <view v-if="position">经度: {{ position.longitude }}, 纬度: {{ position.latitude }}</view>
    <view v-if="error">{{ error }}</view>

    <button @click="getLocationUni">获取位置</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      position: null,
      error: null,
      parkList: [
        {
          name: '停车场1',
          longitude: 120.312786,
          latitude: 36.064812
        },
        {
          name: '停车场2',
          longitude: 120.426597,
          latitude: 36.242712
        },
        {
          name: '停车场3',
          longitude: 120.095783,
          latitude: 36.359697
        }
      ]
    }
  },
  methods: {
    // 计算两点之间的距离（使用Haversine公式）
    calculateDistance(lat1, lon1, lat2, lon2) {
      const R = 6371 // 地球半径（公里）
      const dLat = ((lat2 - lat1) * Math.PI) / 180
      const dLon = ((lon2 - lon1) * Math.PI) / 180
      const a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI) / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2)
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
      return R * c
    },

    // 根据当前位置匹配最近的停车场
    findNearestParking(currentPos, parkList) {
      if (!currentPos || !parkList || parkList.length === 0) {
        return null
      }

      let nearestPark = null
      let minDistance = Infinity

      for (const park of parkList) {
        const distance = this.calculateDistance(currentPos.latitude, currentPos.longitude, park.latitude, park.longitude)

        if (distance < minDistance) {
          minDistance = distance
          nearestPark = {
            ...park,
            distance: distance.toFixed(2) // 保留两位小数
          }
        }
      }

      return nearestPark
    },

    getLocationUni() {
      uni.getLocation({
        type: 'wgs84',
        success: (res) => {
          this.position = {
            longitude: res.longitude,
            latitude: res.latitude
          }
          console.log('🚀 ~ this.position:', this.position)
          // 找到最近的停车场
          const nearestPark = this.findNearestParking(this.position, this.parkList)
          console.log('最近的停车场:', nearestPark)
        },
        fail: (err) => {
          this.error = err.errMsg
        }
      })
    },

    getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          (pos) => {
            this.position = {
              longitude: pos.coords.longitude,
              latitude: pos.coords.latitude
            }
            // 找到最近的停车场
            const nearestPark = this.findNearestParking(this.position)
            console.log('最近的停车场:', nearestPark)
          },
          (err) => {
            switch (err.code) {
              case err.PERMISSION_DENIED:
                this.error = '用户拒绝了定位请求'
                break
              case err.POSITION_UNAVAILABLE:
                this.error = '位置信息不可用'
                break
              case err.TIMEOUT:
                this.error = '请求超时'
                break
              default:
                this.error = '未知错误'
            }
          },
          {
            enableHighAccuracy: true, // 高精度模式
            timeout: 10000, // 超时时间10秒
            maximumAge: 0 // 不使用缓存位置
          }
        )
      } else {
        this.error = '您的浏览器不支持地理定位'
      }
    }
  }
}
</script>
