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

const emits = defineEmits(['change'])
const { VITE_AMAP_KEY } = import.meta.env
const amapsdk = new AMapWX({
  key: VITE_AMAP_KEY,
})
const oMap = ref(null)
const mapRef = ref(null)
const formatted_address = ref('')

function regionchange(e: any) {
  if (e.type === 'end') {
    const { centerLocation } = e.detail
    const { longitude, latitude } = centerLocation
    console.log(e)
    reverseGeocoder({
      mapsdk: amapsdk,
      longitude,
      latitude,
      success(data: any) {
        const { regeocodeData, longitude, latitude } = data
        formatted_address.value = regeocodeData.formatted_address
        emits('change', {
          longitude,
          latitude,
          formatted_address,
        })
      },
      fail(error: any) {
        console.log(error)
      },
    })
  }
}

const centerLat = ref(39.904989) // 默认北京
const centerLng = ref(116.405285)

onMounted(() => {
  oMap.value = uni.createMapContext('mapRef', {
    this: getCurrentInstance().proxy,
  })
  if (oMap.value) {
    getLoalcation({
      mapContext: oMap.value,
      success(res: any) {
        const { latitude, longitude } = res
        centerLat.value = latitude
        centerLng.value = longitude
      },
    })
  }
})
</script>

<template>
  <view class="container">
    <view>
      <view class="title">
        <uv-icon name="ditu_dingwei" color="#71a2e3" custom-prefix="custom-icon" size="26" style="margin-right: 10rpx;" />
        请确定损坏车辆当前位置
      </view>
      <view class="location">
        {{ formatted_address || '--' }}
      </view>
      <view class="tips">
        拖动地图可修改位置
      </view>
    </view>
    <map
      id="mapRef"
      ref="mapRef"
      style="width: 100%; height: 660rpx;position: relative;"
      :latitude="centerLat"
      :longitude="centerLng"
      :scale="18"
      :show-location="false"
      @regionchange="regionchange"
    >
      <view class="marker">
        <uv-icon name="zuobiaodian_lixian" color="#21243e" custom-prefix="custom-icon" size="30" style="margin-right: 10rpx;" />
      </view>
    </map>
  </view>
</template>

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

  .title {
    display: flex;
    align-items: center;
    font-size: 32rpx;
    font-weight: bold;
    margin: 20rpx 0;
  }

  .location {
    position: relative;
    left: 9%;
    font-size: 30rpx;
    width: 90%;
    color: #565656;
    margin: 10rpx 0;
  }

  .tips {
    position: relative;
    left: 9%;
    font-size: 28rpx;
    color: #9d9d9d;
    margin-bottom: 30rpx;
  }

  .marker {
    position: absolute;
    width: 30rpx;
    height: 40rpx;
    top: 50%;
    left: 50%;
    margin-left: -15rpx;
    margin-top: -20rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
