<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import OriginIcon from '../image/hhh_2.png'
import L from 'leaflet'
const MapDataList = ref([])
const mapobj = ref()
const originIcon = L.icon({
  iconUrl: OriginIcon,
  iconSize: [0, 0],
  iconAnchor: [10, 20],
  popupAnchor: [0, -8]
})

let map: L.Map | null = null
const init = () => {
  if (map) {
    return
  }
  map = L.map('map', { attributionControl: false }).setView([51.505, -0.09], 3)

  L.tileLayer('https://map.kerryapex.com/osm_tiles/{z}/{x}/{y}.png', {
    attribution:
      '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
  }).addTo(map)
}

const addResetZoomButton = (center: L.LatLng, zoom: number) => {
  const ResetZoomControl = L.Control.extend({
    options: {
      position: 'topleft'
    },
    onAdd: function () {
      const container = L.DomUtil.create('div', 'reset-zoom-control leaflet-bar')

      // 创建重置缩放按钮
      const resetZoomButton = L.DomUtil.create('a', 'reset-zoom-button leaflet-bar-part', container)
      resetZoomButton.href = '#'
      resetZoomButton.title = 'Reset Zoom'
      resetZoomButton.innerHTML = `<div class="outer-ring" style="height: 100%; padding: 4px;border: 1px solid #2b2f36;border-radius: 50%;">
        <div class="inner-ring" style=" height: 100%; width: 100%; background-color: #2b2f36; border-radius: 50%;"></div>
        </div>`
      resetZoomButton.setAttribute('role', 'button')

      // 点击按钮时重置地图到首次标记后的缩放和中心
      resetZoomButton.addEventListener('click', () => {
        map!.setView(center, zoom)
      })

      return container
    }
  })

  // 添加重置按钮到地图
  new ResetZoomControl().addTo(map!)
}
// 定义首次渲染地图的中心和缩放级别
let initialCenter: L.LatLng | null = null
let initialZoomLevel: number | null = null
let isFirstRender = true // 标记是否为首次渲染

const addMarkersToMap = () => {
  if (!map) return // 确保地图已经初始化
  const latLngBounds: any = [] // 用来存储所有标记的坐标
  MapDataList.value.forEach((item: any) => {
    const marker = L.marker(item.qandl, { icon: originIcon }).addTo(map)
    const customPopupContent = `
    <div class="popup-content" style="background-color:${item.color}">
      <div class="popup-content-text">
        <p class="popup-label" style="color:${item.textcolor}">${item.name}</p>
        <p class="popup-value" style="color:${item.textcolor}">${item.value}</p>
      </div>
    </div>
  `
    marker
      .bindPopup(customPopupContent, {
        closeButton: false,
        autoClose: false,
        closeOnClick: false
      })
      .openPopup()
    latLngBounds.push([item.qandl[0], item.qandl[1]])
  })

  if (latLngBounds.length > 0) {
    const bounds = L.latLngBounds(latLngBounds)
    map!.fitBounds(bounds, { paddingTopLeft: [20, 70], paddingBottomRight: [400, 0] })
    setTimeout(() => {
      if (isFirstRender) {
        initialCenter = map!.getCenter()
        initialZoomLevel = map!.getZoom()
        isFirstRender = false
      }
      addResetZoomButton(initialCenter!, initialZoomLevel!)
    }, 0)
  }
  // 数据为空时关闭图层
  if (MapDataList.value.length == 0) {
    map.eachLayer(function (layer) {
      layer.closePopup()
    })
  }
}
onMounted(() => {
  init()
})
const getmapData = () => {
  if (Object.keys(mapobj.value).length == 0) {
    MapDataList.value = []
  } else {
    mapobj.value.forEach((item: any) => {
      MapDataList.value.push({
        color: item.color,
        name: item.name,
        qandl: item.qandl,
        textcolor: item.textcolor,
        value: item.value
      })
    })
  }
  // 请求成功后添加标记，并动态添加重置按钮
  addMarkersToMap()
}

const updataMapObj = (val: any) => {
  mapobj.value = val
  getmapData()
}

defineExpose({
  updataMapObj
})
</script>
<template>
  <div id="map" style="width: 100%; height: 272px"></div>
</template>

<style lang="scss">
@import 'leaflet/dist/leaflet.css';
#map {
  /* 隐藏默认的弹出窗口箭头 */
  .leaflet-popup-tip {
    display: none;
  }
  #map {
    .leaflet-touch {
      .leaflet-bar {
        border: 0;
        border-radius: 4px;
        overflow: hidden;
      }
    }
  }
  .leaflet-popup-content-wrapper {
    background: transparent !important;
    box-shadow: none !important;
  }
  .leaflet-popup-content {
    width: 58px;
    height: 58px;
    margin: 0;
    .popup-content {
      width: 58px;
      height: 58px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      p {
        margin: 0;
        text-align: center;
      }
      .popup-label {
        font-size: 10px;
        font-weight: 400;
      }
      .popup-value {
        font-size: 12px;
        font-weight: 700;
      }
    }
  }
}
/* 自定义重置缩放按钮控件样式 */
.reset-zoom-control {
  margin-top: 10px; /* 增加上边距，使按钮与默认缩放按钮之间有间距 */
  border-radius: 4px;
  background-color: white;
  border: 1px solid #ccc;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.3);
}

.reset-zoom-button {
  background-color: white;
  border: none;
  cursor: pointer;
  padding: 6px;
}
</style>
