<template>
  <view>
    <map
      id="mapId"
      :latitude="latitude"
      :longitude="longitude"
	  :layers="layers"
      @markertap="onMarkerTap"
      @callouttap="onCalloutTap"
      @labeltap="onLabelTap"
      :markers="markers"
      :include-points="includePoints"
      show-location
      style="width: 100%; height: 100vh;"
    >
	 <custom-layer
	      id="tdtLayer"
	      width="350"
	      height="800"
	      is-transparent
	      type="raster"
	      :src="getTileUrl"
	    ></custom-layer>
	</map>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const latitude = ref(23.584863449735067)
const longitude = ref(113.61702297075017)

const markers = ref([])
const includePoints = ref([])
const mapCtx = ref(null)
const img = ref('../../../../static/map/point.png')

const TDT_KEY = 'e95115c454a663cd052d96019fd83840'

const getTileUrl = ({ x, y, z }) => {
  const s = Math.floor(Math.random() * 8) // 0-7
  return `https://t1.tianditu.gov.cn/img_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=c&FORMAT=tiles&TILEMATRIX=${z}&TILEROW=${y}&TILECOL=${x}&tk=${TDT_KEY}`
}
// const layers = [
//         {
//           // 添加腾讯地图默认底图（可选）
//           type: 'vector',
//           subdomains: ['0', '1', '2'],
//           url: 'https://{s}.map.qq.com/tile/{z}/{x}/{y}',
//           zIndex: 0,
//         },
//         {
//           // 叠加天地图影像（WMTS）
//           type: 'wmts',
//           layer: 'img',
// 		  url: 'https://t{s}.tianditu.gov.cn/img_c/wmts?tk=e95115c454a663cd052d96019fd83840&service=wmts&request=GetTile&version=1.0.0&layer=img&style=default&tilematrixset=c&format=tiles',
//           // url: 'https://t{s}.tianditu.gov.cn/img_c/wmts?tk=e95115c454a663cd052d96019fd83840',
//           tileMatrixSet: 'c',
//           subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
//           zIndex: 1,
//         }
//       ]
	  
// 或者使用WMTS方式
const layers = ref([
  {
    type: 'wmts',
    layer: 'img',
    url: 'https://t{s}.tianditu.gov.cn/img_c/wmts?tk=e95115c454a663cd052d96019fd83840',
    tileMatrixSet: 'c',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    zIndex: 99
  }
])

onMounted(() => {
  // #ifdef MP-WEIXIN
  mapCtx.value = uni.createMapContext('mapId')
  mapCtx.value.on('markerClusterClick', res => {
    console.log('markerClusterClick', res)
  })
  
  bindEvent()
  // #endif
  
  
})

 function toPage(path) {
	 uni.navigateTo({
	 	url: `/pages/tabBar/home/subPages/${path}`
	 });
 }

const bindEvent = () => {
  // #ifdef MP-WEIXIN
  mapCtx.value.initMarkerCluster({
    enableDefaultStyle: false,
    zoomOnClick: true,
    gridSize: 60,
    complete(res) {
      console.log('initMarkerCluster', res)
    }
  })
  
  addMarkers()
  
  mapCtx.value.on('markerClusterCreate', res => {
    console.log('clusterCreate', res)
    const clusters = res.clusters
    const newMarkers = clusters.map(cluster => {
      const { center, clusterId, markerIds } = cluster
      return {
        ...center,
        width: 0,
        height: 0,
        clusterId, // 必须
        label: {
          content: markerIds.length + '',
          fontSize: 20,
          width: 30,
          height: 30,
          bgColor: '#FFCB3C',
          borderRadius: 30,
          textAlign: 'center',
          anchorX: 0,
          anchorY: -30,
        }
      }
    })
    mapCtx.value.addMarkers({
      markers: newMarkers,
      clear: false,
      complete(res) {
        console.log('clusterCreate addMarkers', res)
      }
    })
  })
  // #endif
}

const addMarkers = () => {
  const marker = {
    id: 1,
    iconPath: img.value,
    width: 30,
    height: 30,
    joinCluster: true, // 指定了该参数才会参与聚合
    label: {
      width: 50,
      height: 30,
      borderWidth: 1,
      borderRadius: 4,
      bgColor: '#FFCB3C',
	  anchorX: -26,
	  anchorY: -60,
      content: ''
    }
  }

  const positions = [
    { latitude: 23.584863449735067, longitude: 113.61702297075017},
    { latitude: 23.099994, longitude: 113.324520 },
    { latitude: 23.099994, longitude: 113.322520 },
    { latitude: 23.099994, longitude: 113.326520 },
    { latitude: 23.096994, longitude: 113.329520 }
  ]
  
  const newMarkers = []
  positions.forEach((p, i) => {
    const newMarker = {...marker, ...p}
    newMarker.id = i + 1
    newMarker.label.content = `果园 ${i + 1}`
    newMarkers.push(newMarker)
  })
  
  // #ifdef MP-WEIXIN
  mapCtx.value.addMarkers({
    markers: newMarkers,
    clear: false,
    complete(res) {
      console.log('addMarkers', res)
    }
  })
  // #else
  // 非微信平台直接设置 markers
  markers.value = markers.value.concat(newMarkers)
  // 更新包含的点
  includePoints.value = markers.value.map(marker => ({
    latitude: marker.latitude,
    longitude: marker.longitude
  }))
  // #endif
}

const removeMarkers = () => {
  // #ifdef MP-WEIXIN
  mapCtx.value.addMarkers({
    clear: true,
    markers: []
  })
  // #else
  markers.value = []
  // #endif
}

const onMarkerTap = (e) => {
  console.log('@@ markertap', e)
  
  toPage('gardenMap')
}

const onCalloutTap = (e) => {
  console.log('@@ onCalloutTap', e)
}

const onLabelTap = (e) => {
  console.log('@@ labletap', e)
}
</script>