<!--
 * @Author: chris
 * @Date: 2025-01-13 16:31:10
 * @LastEditors: chris
 * @LastEditTime: 2026-01-19 15:07:11
-->
<script setup>
import { BmMarker, BmInfoWindow } from 'vue-baidu-map-3x'

const props = defineProps({
  deviceList: {
    type: Array,
    default: () => []
  },
  currentDevice: {
    type: Object,
    default: () => null
  }
})

const Map = ref(null)
const pestMap = ref(null)
const baiduMapConfig = {
  center: '汕头市潮南区雷岭镇',
  zoom: 12,
}
const winInfo = ref({
  open: false,
  lat: 0,
  lng: 0,
  content: ''
})

const mapDevices = computed(() => {
  if (!Map.value) return []
  return props.deviceList.map(item => {
    const [lng, lat] = item.installPointDes.split(',')
    return Object.assign({}, item, {
      point: new Map.value.Point(lng, lat),
      open: false
    })
  })
})

watch(() => props.currentDevice, (newVal) => {
  if(!pestMap.value || !props.currentDevice) return
  const device = mapDevices.value.find(item => item.deviceAddr === newVal.deviceAddr)
  device && pestMap.value.flyTo(device.point, 16)
})

function mapReady({BMap, map}) {
  console.log(BMap, map)
    pestMap.value = map;
    Map.value = BMap;
    map.enableScrollWheelZoom(true)
    
    // const overlays = map.getOverlays()
    // const points = overlays.map(item => item.latLng)
    // const viewport = map.getViewport(points)
    // map.setViewport(viewport)
}

function mapZoomEnd({target}) {
  target.setTilt(45)
}

function markerClick(e, item) {
  console.log(item, e)
  const deviceType = item.deviceType === '1' ? '虫情监测' : item.deviceType === '2' ? '土壤墒情监测' : '气象视频监测'
  // 类型 1: 虫情检测 2:土壤墒情监测 3:气象视频监测
  winInfo.value = {
    open: true,
    lat: e.latLng.lat,
    lng: e.latLng.lng, 
    content: `<p style="font-size: 16px; margin-bottom: 10px;font-weight: bold; color: #333;">${deviceType}设备</p>
    <p style="font-size: 14px; color: #666;">设备编号：${item.deviceNo}</p>
    <p style="font-size: 14px;">设备状态：<span style="color: ${item.status === '1' ? 'green' : 'red'};">${item.status === '1' ? '在线' : '离线'}</span></p>`
  }
}
</script>

<template>
  <div class="device-map" >
    <baidu-map class="map" :center="baiduMapConfig.center" :zoom="baiduMapConfig.zoom" @ready="mapReady" @zoomend="mapZoomEnd">
      <bm-marker v-for="item in mapDevices" :key="item.deviceAddr" :position="{lng: item.point.lng, lat: item.point.lat}" @click="markerClick($event, item)" >
      </bm-marker>
      <bm-info-window :show="winInfo.open" :position="{lng: winInfo.lng, lat: winInfo.lat}" :offset="{width: -20, height: -25}">
        <div class="device-info" v-html="winInfo.content || '暂无数据'"></div>
      </bm-info-window>
    </baidu-map>
  </div>
</template>

<style lang="scss" scoped>
.device-map {
  // @apply mx-[-19px] my-[-15px];
  @apply p-18px;
}

.device-map, .map {
  @apply w-full h-full;
}

.map {
  @apply rounded-8px overflow-hidden;
}

:deep(.anchorBL)  {
  display: none;
}

.device-info {
  @apply p-12px;
}
</style>
