<template>
  <view
    id="mapContainer"
    :deviceList="deviceList"
    :landList="landList"
    :blockList="blockList"
    :deviceTypeMapData="deviceTypeMapData"
    :projectLocation="projectLocation"
    :mapRenderTypes="mapRenderTypes"
    :isShowSatellite="isShowSatellite"
    :inputValue="inputValue"
    :inputType="inputType"
    :deviceStatusCheckedList="deviceStatusCheckedList"
    :change:projectLocation="tianditu.onChange"
    :change:deviceList="tianditu.onChange"
    :change:landList="tianditu.onChange"
    :change:blockList="tianditu.onChange"
    :change:deviceTypeMapData="tianditu.onChange"
    :change:mapRenderTypes="tianditu.onChange"
    :change:isShowSatellite="tianditu.onChange"
    :change:deviceStatusCheckedList="tianditu.onChange"
    :change:inputValue="tianditu.searchChange"
    :change:inputType="tianditu.searchChange"
    :change:inputTag="tianditu.searchChange"
    class="map-container"
  ></view>
</template>
<script>
import { normalize } from '@/util/helpers.js';

// 地块数据示例（全部为[lng, lat]顺序，符合真实地理数据标准）
const plots = [
  {
    blockId: '001',
    name: '001地块',
    type: '早田',
    area: 117.9,
    coords: [
      [117.123, 39.123],
      [117.125, 39.124],
      [117.124, 39.125],
      [117.123, 39.123]
    ],
    crops: [
      'https://yunfei-agm.oss-cn-hangzhou.aliyuncs.com/tenant/YF10001/a34f7574-c675-45de-95d8-65fa9283170f/agmp/crop/20250625/微信截图_20230914151200_3cd33701018b1000e0019450c0a801dd_f5542b08844842a19494821115ad3284.jpg'
    ] // 示例：多种作物
  },
  {
    blockId: '002',
    name: '002地块',
    type: '早田',
    area: 56.96,
    coords: [
      [117.128, 39.126],
      [117.129, 39.127],
      [117.127, 39.128],
      [117.128, 39.126]
    ],
    crops: [
      'https://yunfei-agm.oss-cn-hangzhou.aliyuncs.com/tenant/YF10001/a34f7574-c675-45de-95d8-65fa9283170f/agmp/crop/20250625/微信截图_20230914151200_3cd33701018b1000e0019450c0a801dd_f5542b08844842a19494821115ad3284.jpg'
    ] // 示例：单种作物
  },
  {
    blockId: '003',
    name: '003地块',
    type: '早田',
    area: 117.9,
    coords: [
      [113.905846, 33.937994],
      [113.909481, 33.938236],
      [113.909674, 33.936224],
      [113.905888, 33.935903]
    ],
    crops: [
      'https://yunfei-agm.oss-cn-hangzhou.aliyuncs.com/tenant/YF10001/a34f7574-c675-45de-95d8-65fa9283170f/agmp/crop/20250625/微信截图_20230914151200_3cd33701018b1000e0019450c0a801dd_f5542b08844842a19494821115ad3284.jpg'
    ]
  },
  {
    blockId: '004',
    name: '004地块',
    type: '早田',
    area: 117.9,
    coords: [
      [113.905846, 33.937994, 0],
      [113.909481, 33.938236, 0],
      [113.909674, 33.936224, 0],
      [113.905888, 33.935903, 0]
    ],
    crops: [
      'https://yunfei-agm.oss-cn-hangzhou.aliyuncs.com/tenant/YF10001/a34f7574-c675-45de-95d8-65fa9283170f/agmp/crop/20250625/微信截图_20230914151200_3cd33701018b1000e0019450c0a801dd_f5542b08844842a19494821115ad3284.jpg'
    ]
  },
  {
    blockId: '005',
    name: '005地块',
    type: '早田',
    area: 117.9,
    coords: [
      [113.9033, 33.937873, 0],
      [113.905815, 33.937989, 0],
      [113.905839, 33.935906, 0],
      [113.904849, 33.935828, 0]
    ],
    crops: [
      'https://yunfei-agm.oss-cn-hangzhou.aliyuncs.com/tenant/YF10001/a34f7574-c675-45de-95d8-65fa9283170f/agmp/crop/20250625/微信截图_20230914151200_3cd33701018b1000e0019450c0a801dd_f5542b08844842a19494821115ad3284.jpg'
    ]
  },
  {
    blockId: '006',
    name: '006地块',
    type: '早田',
    area: 117.9,
    coords: [
      [113.905619, 33.94116, 0],
      [113.909302, 33.941068, 0],
      [113.909465, 33.93828, 0],
      [113.905848, 33.938069, 0]
    ],
    crops: [
      'https://yunfei-agm.oss-cn-hangzhou.aliyuncs.com/tenant/YF10001/a34f7574-c675-45de-95d8-65fa9283170f/agmp/crop/20250625/微信截图_20230914151200_3cd33701018b1000e0019450c0a801dd_f5542b08844842a19494821115ad3284.jpg'
    ]
  }
  // 可继续添加更多地块
];

export default {
  name: 'Map',
  props: {
    deviceList: {
      type: Array,
      default: () => []
    },
    landList: {
      type: Array,
      default: () => []
    },
    blockList: {
      type: Array,
      default: () => []
    },
    mapRenderTypes: {
      type: Array,
      default: () => []
    },
    deviceStatusCheckedList: {
      type: Array,
      default: () => ['0', '1', '3']
    },
    isShowSatellite: {
      type: Boolean,
      default: true
    },
    inputValue: {
      type: String,
      default: ''
    },
    inputType: {
      type: String,
      default: ''
    },
    inputTag: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dataPending: false,
      deviceTypeList: [],
      projectLocation: {}
      // blockList: plots
    };
  },
  computed: {
    deviceTypeMapData() {
      return normalize(this.deviceTypeList, 'devtypeBid');
    }
  },
  watch: {
    deviceList: {
      handler(newVal) {
        if (newVal.length > 0) {
          if (this.myMap) {
            this.dataPending = false;
            this.initDeviceMarkers();
          } else {
            this.dataPending = true;
          }
        }
      },
      deep: true
    },
    landList(newVal) {
      if (newVal.length > 0) {
        if (this.myMap) {
          this.dataPending = false;
          this.initLandMarkers();
        } else {
          this.dataPending = true;
        }
      }
    }
  },
  mounted() {
    this.getDeviceTypeList();
    this.getProjectLocation();
  },
  methods: {
    handleMarkerClick(item) {
      this.$emit('deviceClick', item);
    },
    handleLandMarkerClick(item) {
      this.$emit('landClick', item);
    },
    handlePlotClick(item) {
      this.$emit('plotClick', item);
    },
    getDeviceTypeList() {
     
    },
    getProjectLocation() {
     
    },
    showToast() {
      uni.showToast({
        title: '未查询到数据',
        icon: 'none'
      });
    }
  }
};
</script>

<script module="tianditu" lang="renderjs">
import { convertToGrayscale } from '@/util/helpers';
import {debounce} from 'lodash-es'

let lay = null;
let cluster = null;
let originalMarkers = [];
let timer = null;
let currentDeviceMarkers = [];
let currentDeviceLabelMarkers = [];
let currentLandMarkers = [];
let currentLandLabelMarkers = [];
let currentPlotPolygons = [];
let currentPlotCropMarkers = [];
let currentPlotLabels = [];
let deviceMarkerIndexMap = {};
let landMarkerIndexMap = {};
let plotMarkerIndexMap = {};
let isShowLabel = false;
let currentZoom = 5;

export default {
	mounted() {
		window.wx = undefined
		if (typeof window.T === 'function') {
			this.initMap()
		} else {
			// 动态引入较大类库避免影响页面展示
			const script = document.createElement('script')
			// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
			script.src = 'https://api.tianditu.gov.cn/api?v=4.0&tk=bfe366f1af60602bd0e51853af6d23d2'
			script.onload = this.initMap.bind(this)
			document.head.appendChild(script)
		}
	},
	methods: {
		initMap() {
      console.log('initMap', this.deviceList, this.landList,this.dataPending);
			var imageURL =
				'https://t0.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=bfe366f1af60602bd0e51853af6d23d2';

			//创建自定义图层对象
			lay = new T.TileLayer(imageURL, {
				minZoom: 2,
				maxZoom: 18
			});

			this.myMap = new T.Map('mapContainer', {
				// layers: [lay],
			});

      // 监听地图事件
      this.myMap.addEventListener('zoomend', this.zoomend);
      // this.myMap.addEventListener('moveend', this.updateLabels);

      const {lng, lat} = this.projectLocation || {};

      console.log(lng,lat)
			this.myMap.centerAndZoom(new T.LngLat(lng || 116.40769, lat || 39.89945), 12);

      // this.myMap.setMaxBounds(new T.LngLatBounds(new T.LngLat(116.10249, 39.84677), new T.LngLat(116.71291, 39.95212)));

      // indigo black default
      this.myMap.setStyle('default');

      if(this.dataPending) {
        this.initDeviceMarkers();
        this.initLandMarkers();
        this.dataPending = false;
      }

      // 初始化地块polygon
      this.initPlotPolygons();

      this.onChange();
		},
    searchChange(){

      currentDeviceLabelMarkers.forEach(marker => {
        const labelDom = marker.getElement();

        labelDom.classList.remove('active');
      });

       currentLandLabelMarkers.forEach(marker => {
          const labelDom = marker.getElement();

          labelDom.classList.remove('active');
        });

       currentPlotLabels.forEach(marker => {
          const labelDom = marker.getElement();

          labelDom.classList.remove('active');
        });

      if(this.inputType){
        if(this.inputType === 'device'){
          if(this.inputValue){
            const deviceData = this.deviceList && this.deviceList.find(item=>{
              const lng = item.devLngalign || item.devLng;
              const lat = item.devLatalign || item.devLat;
              return (item.devCode.includes(this.inputValue) || item.devName.includes(this.inputValue)) && lng && lat
            })
            if(deviceData){
              const deviceMarker = currentDeviceMarkers[deviceMarkerIndexMap[deviceData.devBid]];
              const labelMarker = currentDeviceLabelMarkers[deviceMarkerIndexMap[deviceData.devBid]];
              console.log(deviceData.devBid,deviceMarkerIndexMap,'deviceMarkerdeviceMarkerdeviceMarkerdeviceMarkerdeviceMarker')
              const lnglat = deviceMarker?.getLngLat()
              labelMarker && labelMarker.show()
              currentDeviceLabelMarkers && currentDeviceLabelMarkers.forEach(marker => {
                const labelDom = marker.getElement();
                labelDom.classList.remove('active');
              });
              if(labelMarker){
                const currentlabelDom = labelMarker && labelMarker.getElement();
                console.log(labelMarker,'-----------------2342342342---- label dom',currentlabelDom)

                currentlabelDom.classList.add('active');
              }
              if(lnglat){
                this.myMap && this.myMap.centerAndZoom(lnglat,18)
              }
            }else{
              this.$ownerInstance.callMethod('showToast')
            }
          }
        }else if(this.inputType === 'land'){
          if(this.inputValue){
            const landData = this.landList.find(item=>{
              return item.landId.includes(this.inputValue) || item.landName.includes(this.inputValue)
            })



            if(landData){
              const landMarker = currentLandMarkers[landMarkerIndexMap[landData.landId]];
             const lnglat = landMarker?.getLngLat();

             const labelMarker = currentLandLabelMarkers[landMarkerIndexMap[landData.landId]];

              labelMarker && labelMarker.show()
              currentLandLabelMarkers.forEach(marker => {
                const labelDom = marker.getElement();
                console.log(marker,'--------------------- label dom',labelDom)
                labelDom.classList.remove('active');
              });
              if(labelMarker){
                const currentlabelDom = labelMarker.getElement();
                console.log(labelMarker,'--------------------- label dom',currentlabelDom)

                currentlabelDom.classList.add('active');
              }
             if(lnglat){
               this.myMap && this.myMap.centerAndZoom(lnglat,18)
             }
            }else{
              this.$ownerInstance.callMethod('showToast')
            }
          }
        }else if(this.inputType === 'block' || this.inputType === 'crop'){
          if(this.inputValue){
            // 查找所有匹配的地块数据
            const matchedPlots = this.blockList && this.blockList.filter(item=>{
              const cropData = item.fmsPlanCropResVoList && item.fmsPlanCropResVoList.find(crop=>{
                return crop.cropName.includes(this.inputValue)
              })
              return item.blockName.includes(this.inputValue) || cropData
            })

            if(matchedPlots && matchedPlots.length > 0){
              // 清除所有标签的高亮状态
              currentPlotLabels.forEach(marker => {
                const labelDom = marker.getElement();
                labelDom.classList.remove('active');
              });

              const allCoordinates = [];
              const matchedLabels = [];

              // 处理所有匹配的地块
              matchedPlots.forEach(plotData => {
                const plotIndex = plotMarkerIndexMap[plotData.blockId];
                const plotPolygon = currentPlotPolygons[plotIndex];
                const plotLabel = currentPlotLabels[plotIndex];

                if(plotPolygon && plotLabel){
                  const blockLngrange =
                    typeof plotData.blockLngrange === 'string' && plotData.blockLngrange ? JSON.parse(plotData.blockLngrange) : plotData.blockLngrange || {};
                  const coordinates = blockLngrange?.geometry?.coordinates || [];
                  const coords = coordinates[0] || []

                  // 收集所有坐标点用于计算视窗
                  coords.forEach(coord => {
                    allCoordinates.push(new T.LngLat(coord[0], coord[1]));
                  });

                  // 收集匹配的标签
                  matchedLabels.push(plotLabel);
                }
              });

              // 高亮显示所有匹配的标签
              if(this.mapRenderTypes.includes('block')){
                matchedLabels.forEach(label => {
                  label.show();
                  const labelDom = label.getElement();
                  labelDom.classList.add('active');
                });
              }

              // 计算包含所有匹配地块的视窗
              if(allCoordinates.length > 0){
                if(allCoordinates.length === 1){
                  // 只有一个点，直接居中缩放
                  this.myMap && this.myMap.centerAndZoom(allCoordinates[0], 16);
                } else {
                  // 多个点，设置视窗包含所有点
                  this.myMap && this.myMap.setViewport(allCoordinates);
                }
              }
            }else{
              this.$ownerInstance.callMethod('showToast')
            }
          }
        }
      }
    },
    zoomend(){
      console.log(this.myMap.getZoom(),'----------------------- zoom end')
      currentZoom = this.myMap.getZoom();

      isShowLabel = currentZoom >= 15;

      this.onChange();
    },
		onChange:debounce(function (){
      console.log('onChange',isShowLabel, this.mapRenderTypes);
      const mapRenderTypes = this.mapRenderTypes || ['device','land','plot']
      const deviceStatusList = this.deviceStatusCheckedList || ['0','1', '3']

      clearTimeout(timer);
      timer = setTimeout(() => {
        if(!this.myMap){
          return;
        }

        if(mapRenderTypes.includes('device')){
          if(currentDeviceMarkers && currentDeviceMarkers.length > 0){
            currentDeviceMarkers.forEach(marker => {
              console.log(marker.customData,deviceStatusList)
              const isShow = deviceStatusList.includes(marker.customData.status);

              if(isShow){
                marker.show()
              }else{
                marker.hide()
              }
            });

            currentDeviceLabelMarkers.forEach(marker => {
              const isShow = deviceStatusList.includes(marker.customData.status);
              if(isShowLabel && isShow){
                marker.show()
              }else{
                marker.hide()
              }
            });
          }else{
            this.initDeviceMarkers();
          }
        }else{
          if(currentDeviceMarkers && currentDeviceMarkers.length > 0){
            currentDeviceMarkers.forEach(marker => {
              marker.hide()
            });

            currentDeviceLabelMarkers.forEach(marker => {
              marker.hide()
            });
          }
        }

        if(mapRenderTypes.includes('land')){
          if(currentLandMarkers && currentLandMarkers.length > 0){
            currentLandMarkers.forEach(marker => {
              marker.show()
            });

            currentLandLabelMarkers.forEach(marker => {
              if(isShowLabel){
                marker.show()
              }else{
                marker.hide()
              }
            });
          }else{
            this.initLandMarkers();
          }
        }else{
          if(currentLandMarkers && currentLandMarkers.length > 0){
            currentLandMarkers.forEach(marker => {
              marker.hide()
            });

            currentLandLabelMarkers.forEach(marker => {
              marker.hide()
            });
          }
        }

        // 处理地块polygon显示
        if(mapRenderTypes.includes('block') || mapRenderTypes.includes('crop')){
          const isShowBlock = mapRenderTypes.includes('block');
          const isShowCrop = mapRenderTypes.includes('crop');

          if(currentPlotPolygons && currentPlotPolygons.length > 0){
            currentPlotPolygons.forEach(polygon => {
              if(!isShowBlock){
                polygon.hide()
              }else{
                polygon.show()
              }
            });

            currentPlotCropMarkers.forEach(marker => {
              if(!isShowCrop){
                marker.hide()
              }else{
                marker.show()
              }
            });

            currentPlotLabels.forEach(label => {
              if(!isShowBlock){
                label.hide()
              }else {
                label.show()
              }
            });
          }else{
            this.initPlotPolygons();
          }
        }else{
          if(currentPlotPolygons && currentPlotPolygons.length > 0){
            currentPlotPolygons.forEach(polygon => {
              polygon.hide()
            });
            currentPlotCropMarkers.forEach(marker => {
              marker.hide()
            });
            currentPlotLabels.forEach(label => {
              label.hide()
            });
          }
        }

        this.toggleTileLayer(this.isShowSatellite);
      }, 500);
		},500),
    initDeviceMarkers() {
      console.log('init device markers ',this.deviceList)
      if(!this.deviceList){
        return
      }

      // 设备标记
      const markers = []
      const bounds = new T.LngLatBounds();
      const lnglatList = [];
      const labels = [];
      let index = 0;
      const len = this.deviceList && this.deviceList.length || 0;
      this.deviceList.forEach((item) => {
        const lng = item.devLngalign || item.devLng;
        const lat = item.devLatalign || item.devLat;
        if (!lng || !lat) {
          return;
        }

        let img = this.deviceTypeMapData[item.devtypeBid] ? this.deviceTypeMapData[item.devtypeBid].devtypeMapicon : '';
        // img 转base64图片地址
        var icon = new T.Icon({
            iconUrl: img || 'http://api.tianditu.gov.cn/v4.0/image/marker-icon.png',
            iconSize: new T.Point(25, 35),
            iconAnchor: new T.Point(0, 25)
        });

        const lngLat = new T.LngLat(lng, lat);
        const marker = new T.Marker(lngLat,{icon: icon,className: item.devStatus == '1' ?'tdt-online' : 'tdt-offline' });
        markers.push(marker);
        bounds.extend(lngLat);
        lnglatList.push(lngLat);

        const label = new T.Label({
          text: `<div class="device-label">${item.devName}</div>`,
          position: marker.getLngLat(),
          offset: new T.Point(0, -40)
        });

        marker.addEventListener("click", () => {
          this.$ownerInstance.callMethod('handleMarkerClick',item)
        });

        label.addEventListener("click",()=>{
          this.$ownerInstance.callMethod('handleMarkerClick',item)
        });

        labels.push(label);

        deviceMarkerIndexMap[item.devBid] = index;
        index++;

        marker.customData = {
          id:item.devBid,
          status:item.devStatus
        }

        label.customData = {
          id:item.devBid,
          status:item.devStatus
        }

        this.myMap && this.myMap.addOverLay(label);
        this.myMap && this.myMap.addOverLay(marker);

        if(!isShowLabel && len > 1){
          label.hide();
        }

        const iconDom = marker.getIcon().img;
        iconDom.classList.remove('tdt-online', 'tdt-offline');
        iconDom.classList.add(`${item.devStatus === '1' ? 'tdt-online' : 'tdt-offline'  }`);
      });

      originalMarkers=[...markers];
      currentDeviceMarkers=[...markers];
      currentDeviceLabelMarkers=[...labels];

      if(this.myMap){

        // cluster = new T.MarkerClusterer(this.myMap, {markers});

        setTimeout(() => {
          this.myMap && this.myMap.setViewport(lnglatList);
        }, 1000);
      }
    },
    initLandMarkers() {
      console.log('initLandMarkers', this.landList);
      if(!this.landList){
        return
      }

      // 设备标记
      const markers = [];
      const labels = [];
      let index = 0;
      this.landList.forEach((item) => {
        const lng = item.landLongitude || '';
        const lat = item.landLatitude || '';
        if (!lng || !lat) {
          return;
        }

        //创建图片对象
        var icon = new T.Icon({
            iconUrl: "./static/images/home/base.png",
            iconSize: new T.Point(70, 60),
            iconAnchor: new T.Point(10, 25)
        });

        const marker = new T.Marker(new T.LngLat(lng, lat), {icon: icon});
        markers.push(marker);

        this.myMap && this.myMap.addOverLay(marker);

        const label = new T.Label({
          text: `<div class="land-label">${item.landName}</div>`,
          position: marker.getLngLat(),
          offset: new T.Point(0, -40)
        });

        labels.push(label);

        this.myMap && this.myMap.addOverLay(label);

        landMarkerIndexMap[item.landId] = index;
        index++;

        marker.addEventListener("click", () => {
          this.$ownerInstance.callMethod('handleLandMarkerClick',item)
        });

        label.addEventListener("click",()=>{
          this.$ownerInstance.callMethod('handleLandMarkerClick',item)
        });

        if(!isShowLabel){
          label.hide()
        }
      });

      currentLandMarkers=[...markers];
      currentLandLabelMarkers=[...labels];
    },
    initPlotPolygons() {
      console.log('initPlotPolygons', this.blockList);
	  if(!this.blockList){
		  return
	  }

      const polygons = [];
      const cropMarkers = [];
      const labels = [];
      let index = 0;

      this.blockList.forEach((plot,index) => {

        const blockLngrange =
          typeof plot.blockLngrange === 'string' && plot.blockLngrange ? JSON.parse(plot.blockLngrange) : plot.blockLngrange || {};
        const coordinates = blockLngrange?.geometry?.coordinates || [];

        if (!coordinates[0] || coordinates[0].length < 3) {
          return;
        }

        // 创建地块polygon的坐标点数组
        const points = coordinates[0].map(coord => {
          // 处理可能包含高度信息的坐标 [lng, lat, height] 或 [lng, lat]
          const lng = coord[0];
          const lat = coord[1];
          return new T.LngLat(lng, lat);
        });

        // 创建polygon
        const polygon = new T.Polygon(points, {
          color: plot.blockColor || '#1890ff',
          weight: 2,
          opacity: 1,
          fillColor: plot.blockColor || '#1890ff',
          fillOpacity: 0.7
        });

        polygons.push(polygon);
        this.myMap && this.myMap.addOverLay(polygon);

        // 计算地块中心点用于放置作物图片
        const center = this.calculatePolygonCenter(points);

        const plotLabel = new T.Label({
          text: `<div class="plot-label">${plot.blockName}</div>`,
          position: center,
          offset: new T.Point(0, 10)
        });

        labels.push(plotLabel);
        this.myMap && this.myMap.addOverLay(plotLabel);

        // 添加点击事件
        polygon.addEventListener("click", () => {
          this.$ownerInstance.callMethod('handlePlotClick', plot);
        });


        plotLabel.addEventListener("click", () => {
          this.$ownerInstance.callMethod('handlePlotClick', plot);
        });

        // 为每个作物创建标记
        if (plot.fmsPlanCropResVoList && plot.fmsPlanCropResVoList.length > 0) {
          plot.fmsPlanCropResVoList.forEach((cropItem, cropIndex) => {

            const cropUrl = cropItem.cropPreview || ''

            if(cropUrl){
               // 如果有多个作物，稍微偏移位置
              const offsetX = cropIndex * 30 - (plot.fmsPlanCropResVoList.length - 1) * 15;
              const offsetY = 0;

              const cropIcon = new T.Icon({
                iconUrl: cropUrl,
                iconSize: new T.Point(20, 20),
                iconAnchor: new T.Point(20, 20),
                className: 'crop-icon-rounded'
              });

              const cropMarker = new T.Marker(center, {icon: cropIcon});
              cropMarkers.push(cropMarker);
              this.myMap && this.myMap.addOverLay(cropMarker);

              cropMarker.addEventListener("click", () => {
                  this.$ownerInstance.callMethod('handlePlotClick', plot);
                });
            }

          });
        }

        plotMarkerIndexMap[plot.blockId] = index;
        index++;
      });

      currentPlotPolygons = [...polygons];
      currentPlotCropMarkers = [...cropMarkers];
      currentPlotLabels = [...labels];
    },
    calculatePolygonCenter(points) {
      // 计算polygon的中心点
      let totalLng = 0;
      let totalLat = 0;

      points.forEach(point => {
        totalLng += point.lng;
        totalLat += point.lat;
      });

      return new T.LngLat(totalLng / points.length, totalLat / points.length);
    },
    toggleTileLayer(isShowSatelliteLayer=true) {
      console.log('toggleTileLayer',isShowSatelliteLayer);
      if (!this.myMap) {
        return
      }

      if(isShowSatelliteLayer){
        this.myMap.addLayer(lay);
      }else{
        this.myMap.removeLayer(lay);
      }

    },
    // 更新Label可见性
    updateLabels() {


      setTimeout(() => {
        console.log('updateLabels',cluster);
      console.log('updateLabels origin markers',originalMarkers);
      // console.log('updateLabels origin markers',cluster && cluster.getClustersCount());
      }, 1000);
      // cluster.getMarkers().forEach(marker => {
      //   marker.getLabel().hide();
      // });

      // originalMarkers.forEach(marker => {
      //   if (!this.isMarkerInAnyCluster(marker)) {
      //     marker.getLabel().show();
      //   }
      // });
    },
    isMarkerInAnyCluster(marker) {
      // return cluster.getMarkers().some(markers =>{

      // }
        // cluster.markers.includes(marker)
      // );
    }
	}
}
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 100vh;
}

::v-deep .tdt-label {
  background: transparent;
  border-color: transparent;
  border-radius: 999px;
  min-width: 30px;
  padding: 0;
  line-height: 20px;
  text-align: center;
  box-shadow: none;

  .land-label {
    background: rgba(0, 0, 0, 0.5);
    border-color: rgba(255, 199, 0, 0.18);
    border-radius: 999px;
    padding: 0 10px;
    color: #ffc701;
    min-width: 30px;
    line-height: 20px;
    transform: translateX(-50%);
  }

  .device-label {
    background: rgba(0, 0, 0, 0.5);
    border: 1px solid #1890ff;
    border-radius: 4px;
    color: #fff;
    min-width: 30px;
    padding: 0 10px;
    line-height: 20px;
    transform: translateX(-50%);
  }

  .plot-label {
    border: none;
    border-radius: 4px;
    color: #fff;
    min-width: 40px;
    padding: 2px 8px;
    line-height: 18px;
    transform: translateX(-50%);
    text-align: center;
    font-size: 14px;
    font-weight: normal;
  }

  &.active {
    .device-label,
    .land-label {
      border: 2px solid gold;
      box-shadow: 0 0 10px rgba(255, 215, 0, 0.6),
        /* 金色阴影 */ 0 0 20px rgba(255, 215, 0, 0.4),
        /* 较淡的金色阴影 */ 0 0 30px rgba(255, 215, 0, 0.2);
    }

    .plot-label {
      background: rgba(255, 255, 255, 1);
      border: 1px solid #1890ff;
      color: #1890ff;
      font-weight: 500;
    }
  }
}

::v-deep .tdt-marker-icon {
  /* 在线状态 */
  &.tdt-online {
    filter: grayscale(0%) brightness(1.2);
  }

  /* 离线状态 */
  &.tdt-offline {
    filter: grayscale(100%) opacity(0.6);
  }
}

::v-deep .tdt-bottom {
  display: none;
}

/* 作物图片圆角样式 */
::v-deep img.crop-icon-rounded {
  border-radius: 50%;
  border: 1px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
