<template>
  <view>
    <map
      id="mapId"
      :latitude="latitude"
      :longitude="longitude"
	  :layers="layers"
      @markertap="onMarkerTap"
      @callouttap="onCalloutTap"
      @labeltap="onLabelTap"
      :markers="markers"
      :include-points="includePoints"
	  :enable-satellite="true"
	  theme="satellite"
      show-location
      style="width: 100%; height: 100vh;"
    ></map>
  </view>
</template>

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

const latitude = ref(26.870355)
const longitude = ref(100.239704)
// 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 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,
        }
      ]

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

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)
      }
    })
  })
  // let xyz = "https://birdseye-img.sysuimars.com/map/lby/{z}/{x}/{y}.png";
  //    mapCtx.value.addCustomLayer({
  //      id: 'custom-tile-layer',
  //      type: 'raster',
  //      source: {
  //        type: 'raster',
  //        tiles: [xyz],  // 替换为你的瓦片 URL
  //        tileSize: 256,
  //      },
  //      paint: {},
	 //   zIndex: 99
  //    });
	 
	 // const mapCtx2 = uni.createMapContext('mapId', this);
	     const xyz = "https://birdseye-img.sysuimars.com/map/lby/z/x/y.png";
		 const demoLayer = 'https://3gimg.qq.com/visual/lbs_gl_demo/image_tiles_layers/z/x_y.png'
	     
	   //   mapCtx.value.addCustomLayer({
			 // layerId: 'cunstom',
	   //     id: 'custom-tile-layer',
	   //     type: 'raster',
	   //     source: {
	   //       type: 'raster',
	   //       tiles: [demoLayer],
	   //       tileSize: 256,
	   //     },
	   //     paint: {},
	   //     success: (res) => console.log("图层添加成功", res),
	   //     fail: (err) => console.error("图层添加失败", err)
	   //   });
		 
		 
		   mapCtx.value.addGroundOverlay({
		     id: 'gaode-tiles',
		     type: 'raster',
		     source: {
		       type: 'raster',
		       tiles: [
		         'https://webst01.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'
		       ],
		       tileSize: 256,
		     },
		     paint: {},
		     success: (res) => {
		       console.log("高德瓦片加载成功");
		     },
		     fail: (err) => {
		       console.error("加载失败", err);
		     }
		   });
  // #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: '#FFCB3C88',
	  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)
}

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

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