<template>
  <!-- <el-button @click="test">测试</el-button> -->
  <div
    id="tracking-map"
    ref="mapContainer"
    style="width: 100%; height: 520px"
    class="tracking-map"
  ></div>
</template>
<script setup lang="ts">
import L from 'leaflet'
import DestinationIcon from '../images/destinationIcon.png'
import OriginIcon from '../images/originIcon.png'
import TransferIcon from '../images/transferIcon.png'
import { onMounted, ref, watch } from 'vue'
import * as turf from '@turf/turf'

const props = defineProps<{
  serial_no?: string
  uncode?: string
}>()

const markerPositions = ref([])
// 创建自定义图标
const originIcon = L.icon({
  iconUrl: OriginIcon,
  iconSize: [20, 20],
  iconAnchor: [10, 20],
  popupAnchor: [0, -8]
})

const destinationIcon = L.icon({
  iconUrl: DestinationIcon,
  iconSize: [20, 20],
  iconAnchor: [10, 20],
  popupAnchor: [0, -8]
})

const transferIcon = L.icon({
  iconUrl: TransferIcon,
  iconSize: [20, 20],
  iconAnchor: [10, 20],
  popupAnchor: [0, -8]
})

let map: L.Map | null = null

// 初始化地图（不添加标记）
const initMap = () => {
  if (map) {
    return
  }

  map = L.map('tracking-map', {}).setView([51.505, -0.09], 3)

  // 添加 TileLayer
  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 fixLng = (lng: number) => {
  while (lng > 180) lng = lng - 360
  while (lng <= -180) lng = lng + 360
  return lng
}
const getBBox = () => {
  let bnd = map.getBounds()
  let ww = bnd.getEast() - bnd.getWest()
  let cent_pt = map.getCenter()
  let bbox = [
    fixLng(cent_pt.lng - ww / 2),
    bnd.getSouth(),
    fixLng(cent_pt.lng + ww / 2),
    bnd.getNorth()
  ]

  let bbox2 = []
  let bbox3 = []
  if (ww > 360) {
    bbox[0] = -180
    bbox[2] = 0

    bbox2[0] = 0
    bbox2[1] = bbox[1]
    bbox2[2] = 180
    bbox2[3] = bbox[3]
  }
  if (bbox[2] * bbox[0] < 0 || bbox[2] < bbox[0]) {
    if (bbox[0] >= 0) {
      bbox2[0] = -180
      bbox2[2] = bbox[2]
      bbox2[1] = bbox[1]
      bbox2[3] = bbox[3]
      bbox[2] = 180
    } else {
      bbox2[0] = 0
      bbox2[2] = bbox[2]
      bbox2[1] = bbox[1]
      bbox2[3] = bbox[3]
      bbox[2] = 0
    }
  }
  if (bbox2[2] * bbox2[0] < 0 || bbox2[2] < bbox2[0]) {
    if (bbox2[0] >= 0) {
      bbox3[0] = -180
      bbox3[2] = bbox2[2]
      bbox3[1] = bbox2[1]
      bbox3[3] = bbox2[3]
      bbox2[2] = 180
    } else {
      bbox3[0] = 0
      bbox3[2] = bbox2[2]
      bbox3[1] = bbox2[1]
      bbox3[3] = bbox2[3]
      bbox2[2] = 0
    }
  }
  let ll = []
  ll.push(bbox)

  if (bbox2.length > 0) ll.push(bbox2)
  if (bbox3.length > 0) ll.push(bbox3)
  return ll
}
let track_added_marker = []

const clear_marker = () => {
  track_added_marker.forEach((v) => {
    map!.removeLayer(v)
  })

  track_added_marker = []
}
const draw_marker = (dottedLine = [], solidLine = []) => {
  clear_marker()
  dottedLine.forEach((l) => {
    addMapLine(l, true, { color: '#ff7500', weight: 2 })
  })
  solidLine.forEach((l) => {
    addMapLine(l, false, { color: '#ff7500', weight: 2 })
  })
}
const addMapLine = (l, IsDash, opts) => {
  let mpts = l.pts
  if (mpts == null || mpts.length == 0) return

  let bnd = map.getBounds()
  let ww = bnd.getEast() - bnd.getWest()
  let cc = Math.ceil(ww / 360)

  let boxlist = getBBox()

  let ll = []

  for (let ii = 0; ii < mpts.length; ii++) {
    ll[ii] = [mpts[ii][1], mpts[ii][0]]
  }
  let pline = turf.lineString(ll, { name: '' })
  let level = map.getZoom()
  let options = {
    tolerance:
      Math.round(
        ((level < 8 ? 0.0005 : level < 12 ? 0.00005 : 0) / (level == 0 ? 1 : level)) * 1000000
      ) / 1000000,
    highQuality: false
  }
  let simplified = turf.simplify(pline, options)

  let lines_list = []
  let clipped: any = simplified
  boxlist.forEach((bbox) => {
    let bb = bbox
    clipped = turf.bboxClip(simplified, bb)
    if (clipped != null) {
      if (clipped.geometry.type === 'LineString') {
        let line_pts = clipped.geometry.coordinates
        let pta = []
        let jj = 0
        for (let ii = 0; ii < line_pts.length; ii++) {
          pta[jj++] = [line_pts[ii][1], line_pts[ii][0]]
        }
        lines_list.push(pta)
      } else if (clipped.geometry.type === 'MultiLineString') {
        clipped.geometry.coordinates.forEach((_pts) => {
          let line_pts = _pts
          let pta = []
          let jj = 0
          for (let ii = 0; ii < line_pts.length; ii++) {
            pta[jj++] = [line_pts[ii][1], line_pts[ii][0]]
          }
          lines_list.push(pta)
        })
      }
    }
  })

  let cc1 = Math.floor(bnd.getWest() / 360)
  let cc2 = Math.ceil(bnd.getEast() / 360)
  cc = cc2 - cc1 + 1

  let kk = cc1
  // let lines_list = [mpts]
  while (kk >= cc1 && kk <= cc2 && cc > 0) {
    lines_list.forEach((a) => {
      let ii = 0
      let jj = 0
      let pts = []
      for (ii = 0; ii < a.length; ii++) pts[jj++] = [a[ii][0], a[ii][1] + kk * 360]

      if (jj > 0) {
        if (IsDash) {
          showTrackLine(
            pts,
            jj,
            Object.assign({}, { color: '#ff7500', dashArray: '10', weight: 2 }, opts)
          )
        } else {
          showTrackLine(pts, jj, Object.assign({}, { color: '#ff7500', weight: 1 }, opts))
        }
      }
    })

    kk++
    cc--
  }
}

const showTrackLine = (pts, jj, opts) => {
  let arrow = L.polyline(pts, Object.assign({}, { color: '#ff7500', weight: 2 }, opts)).addTo(map)
  track_added_marker.push(arrow)

  // 如果线段至少有两个点，才添加箭头
  // if (pts.length >= 2) {
  //   // 获取线段的最后一个点和倒数第二个点
  //   const lastPoint = pts[pts.length - 1]
  //   const secondLastPoint = pts[pts.length - 2]

  //   // 计算线段末端的角度（以弧度为单位）
  //   const angle =
  //     Math.atan2(lastPoint[1] - secondLastPoint[1], lastPoint[0] - secondLastPoint[0]) *
  //     (180 / Math.PI)

  //   // 创建自定义箭头图标
  //   const arrowIcon = L.divIcon({
  //     html: `
  //     <div  style="transform: rotate(${angle + 270}deg);" class="container">
  //       <div class="circle"></div>
  //       <span style="color:white;border:1px solid white" class="font_family icon-icon_path_b"></span>
  //     </div>
  //     `,
  //     className: 'arrow-icon',
  //     iconSize: [50, 50],
  //     iconAnchor: [25, 25], // 箭头的中心点
  //     popupAnchor: [0, -25] // 弹出框的锚点
  //   })

  //   // 创建箭头标记，并根据计算出的角度旋转箭头
  //   const arrowMarker = L.marker(lastPoint, {
  //     icon: arrowIcon
  //   }).addTo(map)
  //   console.log(angle, '角度')
  //   // 将箭头标记也存储在 track_added_marker 数组中，以便后续管理
  //   track_added_marker.push(arrowMarker)
  // }
}

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 // 标记是否为首次渲染

let allMarkers = []
let visibleMarkers = new Set()

// 添加标记后更新中心和缩放级别
const addMarkersToMap = () => {
  // debugger
  if (!map) return // 确保地图已经初始化

  markerPositions.value.forEach((position) => {
    const marker = L.marker([position.lat, position.lng], { icon: position.icon }).addTo(map)

    const customPopupContent = `
      <div class="popup-content">
        <p class="label">${position.label}</p>
        <p>
          <span class="font_family icon-icon_location_fill_b" style="color: ${position.iconColor}"></span>
          <span>${position.city}</span>
        </p>
      </div>
    `
    marker
      .bindPopup(customPopupContent, {
        closeButton: false,
        autoClose: false,
        closeOnClick: false
      })
      .openPopup()
    allMarkers[`${position.lat},${position.lng}`] = marker
  })

  updateVisibleMarkers()

  if (viewData.value.length > 0) {
    // 根据标记的位置设置中心点以及缩放级别
    const bounds = L.latLngBounds(viewData.value)
    map!.fitBounds(bounds, { paddingTopLeft: [20, 70], paddingBottomRight: [400, 0] })
    setTimeout(() => {
      if (isFirstRender) {
        initialCenter = map!.getCenter()
        initialZoomLevel = map!.getZoom()
        isFirstRender = false
      }
      addResetZoomButton(initialCenter!, initialZoomLevel!)
    }, 0)
  }
}

// 更新可见标记
const updateVisibleMarkers = () => {
  const newVisibleMarkers = new Set()

  let bnd = map.getBounds()
  let ww = bnd.getEast() - bnd.getWest()

  let cc = Math.ceil(ww / 360)

  let cc1 = Math.floor(bnd.getWest() / 360)
  let cc2 = Math.ceil(bnd.getEast() / 360)
  cc = cc2 - cc1 + 1

  let x = cc1

  // 移除不再可见的标记
  visibleMarkers.forEach((marker: any) => {
    if (!newVisibleMarkers.has(marker)) {
      map.removeLayer(marker)
      delete allMarkers[`${marker.getLatLng().lat},${marker._lng},${marker._x}`]
    }
  })

  // 计算当前视图中的标记，包括多地球的情况
  while (x >= cc1 && x <= cc2 && cc > 0) {
    Object.values(allMarkers).forEach((marker) => {
      const latLng = marker.getLatLng()
      const key = `${latLng.lat},${latLng.lng},${x}`
      if (!allMarkers[key]) {
        const newMarker: any = L.marker([latLng.lat, latLng.lng + x * 360], {
          icon: marker.options.icon
        })
          .bindPopup(marker.getPopup().getContent(), marker.getPopup().options)
          .openPopup()
        newMarker._x = x
        // 使用原始的经度作为标记的唯一标识
        newMarker._lng = latLng.lng
        allMarkers[key] = newMarker
        map.addLayer(newMarker)
      }
      newVisibleMarkers.add(allMarkers[key])
    })
    // }
    x++
    cc--
  }

  // 更新可见标记集合
  visibleMarkers = newVisibleMarkers
}

// 处理得到的数据
const handleData = (data) => {
  let key = 0
  let curLine = []
  let resultLine = []
  data.forEach((item, index) => {
    if (item.sn === '1' && key === 0) {
      key++
      curLine.push([Number(item.lat), Number(item.lon)])
    } else if (item.sn === '1' && key !== 0) {
      resultLine.push({
        name: key,
        pts: curLine
      })
      curLine = [[Number(item.lat), Number(item.lon)]]
      key++
    }
    if (item.sn !== '1') {
      curLine.push([Number(item.lat), Number(item.lon)])
    }
    if (index === data.length - 1 && item.sn !== '1') {
      resultLine.push({
        name: key,
        pts: curLine
      })
    }
  })
  return resultLine
}

const viewData = ref([])
// 请求接口并处理标记
const getMarker = () => {
  $api
    .getTrackingDetailMapData({
      serial_no: props.serial_no,
      uncode: props.uncode
    })
    .then((res) => {
      if (res.code === 200) {
        const { data } = res

        data?.point &&
          data?.point.forEach((item) => {
            const iconColorList = {
              Destination: { color: '#24ca5a', icon: destinationIcon },
              Origin: { color: '#ED6D00', icon: originIcon },
              Transfer: { color: '#ed0000', icon: transferIcon }
            }
            markerPositions.value.push({
              lat: item.lat,
              lng: (Number(item.lng) + 360) % 360,
              city: item.infor,
              label: item.label,
              icon: iconColorList[item.label].icon,
              iconColor: iconColorList[item.label].color
            })
          })
        viewData.value = (data?.rangePoint.length > 0 ? data?.rangePoint : data?.point)?.map(
          (item) => {
            return [Number(item.lat), (Number(item.lon || item.lng) + 360) % 360]
          }
        )
        // 请求成功后添加标记，并动态添加重置按钮
        addMarkersToMap()
        if (data?.dottedLine) {
          draw_marker(handleData(data.dottedLine), handleData(data.solidLine))
          map.on('moveend', function () {
            draw_marker(handleData(data.dottedLine), handleData(data.solidLine))
            updateVisibleMarkers()
          })
          map.on('zoomend', function () {
            draw_marker(handleData(data.dottedLine), handleData(data.solidLine))
            updateVisibleMarkers()
          })
        }
      }
    })
}

// 监听 `serial_no` 变化
watch(
  () => props.serial_no,
  (val) => {
    if (val) {
      getMarker()
    }
  },
  { immediate: true }
)

// 当组件挂载时初始化地图
onMounted(() => {
  initMap() // 初始化地图，不加标记
})

onUnmounted(() => {
  map?.remove()
})

const test = () => {
  // 定义一个更复杂的 HTML 标记
  var complexIcon = L.divIcon({
    html: `
       <div class="container">
    <div class="circle"></div>
    <span class="font_family icon-icon_ocean_b"></span>
  </div>
    `,
    className: 'complex-marker',
    iconSize: [32, 50], // 考虑到额外的文字，设置更大的高度
    iconAnchor: [16, 25] // 调整锚点以适应新的布局
  })

  // 在地图上添加一个带有复杂 HTML 标记的标记
  L.marker([51.5, -0.09], { icon: complexIcon }).addTo(map)
}

const test1 = () => {
  const data = {
    point: [
      {
        lng: '101.40000000',
        lat: '3.00000000',
        label: 'Origin',
        infor: 'PORT KLANG, MALAYSIA',
        sort: '1',
        stime: null,
        ptype: 'pol'
      },
      {
        lng: '-81.09008789',
        lat: '32.08044084',
        label: 'Destination',
        infor: 'SAVANNAH, GA',
        sort: '2',
        stime: null,
        ptype: 'pod'
      },
      {
        lng: '103.81666667',
        lat: '1.26666667',
        label: 'Transfer',
        infor: 'SINGAPORE',
        sort: '3',
        stime: null,
        ptype: 'poe'
      }
    ],
    solidLine: [],
    dottedLine: [],
    rangePoint: []
  }
  data?.point &&
    data?.point.forEach((item) => {
      const iconColorList = {
        Destination: { color: '#24ca5a', icon: destinationIcon },
        Origin: { color: '#ED6D00', icon: originIcon },
        Transfer: { color: '#ed0000', icon: transferIcon }
      }
      markerPositions.value.push({
        lat: item.lat,
        lng: (Number(item.lng) + 360) % 360,
        city: item.infor,
        label: item.label,
        icon: iconColorList[item.label].icon,
        iconColor: iconColorList[item.label].color
      })
    })
  console.log(data, '这是数据')
  viewData.value = (data?.rangePoint.length > 0 ? data?.rangePoint : data?.point)?.map((item) => {
    console.log(item.lon, '这是只')
    return [Number(item.lat), (Number(item.lon || item.lng) + 360) % 360]
  })
  // 请求成功后添加标记，并动态添加重置按钮
  addMarkersToMap()
  if (data?.dottedLine) {
    draw_marker(handleData(data.dottedLine), handleData(data.solidLine))
    map.on('moveend', function () {
      draw_marker(handleData(data.dottedLine), handleData(data.solidLine))
      updateVisibleMarkers()
    })
    map.on('zoomend', function () {
      draw_marker(handleData(data.dottedLine), handleData(data.solidLine))
      updateVisibleMarkers()
    })
  }
}
</script>

<style lang="scss">
@import 'leaflet/dist/leaflet.css';
.tracking-map {
  .leaflet-popup-content-wrapper {
    border-radius: 6px;
  }
  .leaflet-popup-content {
    margin: 0;
    padding: 4px;
    .popup-content {
      p {
        height: 15px;
        margin: 0;
        white-space: nowrap;
        span {
          margin-left: -2px;
          font-size: 12px;
          font-weight: 700;
        }
      }
      .label {
        margin-bottom: 4px;
        font-size: 12px;
        color: let(--color-neutral-2);
      }
    }
  }

  /* 隐藏默认的弹出窗口箭头 */
  .leaflet-popup-tip {
    display: none;
  }
  .transport-map {
    .leaflet-touch {
      .leaflet-bar {
        border: 0;
        border-radius: 4px;
        overflow: hidden;
      }
    }
  }
}
/* 自定义重置缩放按钮控件样式 */
.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>

<style lang="scss">
.tracking-map {
  .container {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    width: 50px;
    /* background-color: #d9dddf; */
    .font_family {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: flex;
      justify-content: center;
      align-items: center;
      width: 24px;
      height: 24px;
      padding: 4px;
      font-size: 9px;
      color: white;
      background-color: rgba(255, 117, 0, 1);
      border-radius: 50%;
      font-size: 18px;
      border: 1px solid white;
    }
  }
  .circle {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    background-color: rgba(255, 117, 0, 1);
    border-radius: 50%;
    position: relative;
    animation: expandAndFade 1.3s linear infinite;
    overflow: hidden; /* 确保子元素不会溢出 */

    opacity: 0.9;
  }

  @keyframes expandAndFade {
    0% {
      transform: scale(1);
      opacity: 0.9;
    }

    50% {
      transform: scale(1.5); /* 从 18px 扩展到 24px (18 * 1.33 = 24) */
      opacity: 0.7;
    }

    100% {
      transform: scale(2); /* 从 18px 扩展到 30px (18 * 1.67 ≈ 30) */
      opacity: 0.2;
    }
  }
}
</style>
