<script lang="ts" setup>
import AMapWX from '@/plugIns/amap-wx.130.js'
import { addLine, getLoalcation, getMapContext, getRoutePlan } from '@/utils/map'

const { VITE_AMAP_KEY } = import.meta.env
const amapsdk = new AMapWX({
  key: VITE_AMAP_KEY,
})

definePage({
  style: {
    navigationBarTitleText: '地图找车',
    navigationBarBackgroundColor: '#1488f5',
    navigationBarTextStyle: 'white',
  },
})

const mapRef = ref(null)
const oMap = ref(null)
const polylines = ref([])
const mapConfig = reactive({
  latitude: 0,
  longitude: 0,
  scale: 16,
  elng: 0,
  elat: 0,
})

function mapUpdated() {

}

onLoad((query) => {
  try {
    const data = JSON.parse(decodeURIComponent(query.params))
    const { elng, elat } = data
    mapConfig.elat = elat
    mapConfig.elng = elng
  }
  catch (err) {
    console.log('onLoad:fail-------------->', err)
  }
})
onMounted(() => {
  oMap.value = getMapContext('mapRef', getCurrentInstance())
  if (oMap.value) {
    getLoalcation({
      mapContext: oMap.value,
      success(res: any) {
        const { latitude, longitude } = res
        mapConfig.latitude = latitude
        mapConfig.longitude = longitude

        getRoutePlan({
          mapsdk: amapsdk,
          slng: longitude,
          slat: latitude,
          elng: mapConfig.elng,
          elat: mapConfig.elat,
          success(res) {
            const { arrPoint, distance } = res
            if (oMap.value) {
              oMap.value.includePoints({
                points: arrPoint,
                padding: [50, 50, 50, 50], // 视野边缘与点的间距
                success: () => {
                  console.log('distance', distance)
                  polylines.value = [
                    addLine({
                      sColor: '#1082FF',
                      arrPoint,
                      width: 10,
                      arrowLine: true,
                    }),
                  ]
                  console.log(oMap)
                },
                fail(err: any) {
                  console.error(err)
                },
              })
            }
          },
          fail(err) {
            console.log(err)
          },
        })
      },
      fail(err) {
        console.log(err)
      },
    })
  }
})
</script>

<template>
  <view class="container">
    <map
      id="mapRef"
      ref="mapRef"
      :latitude="mapConfig.latitude"
      :longitude="mapConfig.longitude"
      show-location
      :scale="mapConfig.scale"
      :polyline="polylines"
      style="width: 100%; height: 100%;"
      @updated="mapUpdated"
    />
  </view>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
}
</style>
