<template>
  <el-form-item label="经纬度：">
    <el-cascader
      v-model="selectedOptions"
      placeholder="请选择地区"
      size="default"
      :options="regionData"
      @change="handleChange"
    />
  </el-form-item>
  <tlbs-map
    ref="mapRef"
    api-key="3SVBZ-6MYYZ-Q75X5-7YN43-BMIBZ-YABND"
    :center="center"
    :zoom="zoom"
    :control="control"
    class="mapBox"
    :options="mapOption"
    @click="onClick"
    @map_inited="onMapInited"
  >
    <tlbs-multi-marker
      ref="markerRef"
      :geometries="geometries"
      :styles="styles"
      @click="openInfo"
    />
  </tlbs-map>
</template>

<script setup>
import { ref, watch } from 'vue'
// 地区选择
import { regionData, codeToText } from 'element-china-area-data'
import { jsonp } from 'vue-jsonp'
import { useCoordinateStore } from '@/pinia/modules/coordinate'
const useCoordinate = useCoordinateStore()
const handleChange = async(value) => {
  const province = codeToText[value[0]] // 省-->
  const city = codeToText[value[1]] // 市-->
  const district = codeToText[value[2]] // 区-->
  const fullAddress = `${province}${city}${district}`
  if (value.length < 3) {
    console.log('请选择完整的省市区')
    return
  }
  // 3SVBZ-6MYYZ-Q75X5-7YN43-BMIBZ-YABND
  jsonp('https://apis.map.qq.com/ws/geocoder/v1/?address=', {
    output: 'jsonp',
    address: fullAddress,
    key: '3SVBZ-6MYYZ-Q75X5-7YN43-BMIBZ-YABND'
  }).then(res => {
    center.value = res.result.location
  }).catch(err => {
    console.log('地图错误：', err)
  })
}
const openInfo = (val) => {
}
const selectedOptions = ref('')
const control = {
  scale: {},
  zoom: {
    position: 'topRight',
  },
}

const styles = {
  marker: {
    width: 20,
    height: 30,
    anchor: { x: 10, y: 30 },
  },
}

// 地图
const mapRef = ref(null)
const markerRef = ref(null)
const center = ref(useCoordinate.place)
const zoom = ref(10)
const mapOption = ref({
  mapStyleId: 'style1'
})
const geometries = ref([{ styleId: 'marker', position: useCoordinate.place }])
const onClick = (e) => {
  geometries.value = [{ styleId: 'marker', position: { lat: e.latLng.lat, lng: e.latLng.lng }}]
  useCoordinate.changeModifyPlace({ lat: e.latLng.lat, lng: e.latLng.lng })
}

const onMapInited = () => {
  // 地图加载完成后，可以获取地图实例、点标记实例，调用地图实例、点标记实例方法
  // console.log(mapRef.value.map)
  // console.log(markerRef.value.marker)
}

watch(() => useCoordinate.place, () => {
  center.value = useCoordinate.place
  geometries.value = [{ styleId: 'marker', position: useCoordinate.place }]
})

</script>

