<template>
  <div class="map-page">
    <div ref="mapContainer" class="map-container"></div>
    <!-- 错误提示 -->
    <div v-if="error" class="error-message">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
const isMapReady = ref(false)
const mapContainer = ref(null)
const error = ref(null)
const TMap = ref(null);
let activeTempMarker = ref(null)
let infoWindow = ref(null)
let map = null
let markersLayer = null
let soilTypeVectorLayer = null; // 土壤类型多边形图层
let overlay = null
const state = reactive({
  showOverlay: false,
  showSoilTypes: true,
  showSurveyData: true,
  shoeWaterSystem: true,
  excelData: [], // 用于存储从接口获取的数据
  lastTapTime: 0
})

const tMapConfig = reactive({
  key: import.meta.env.VITE_TMAP_KEY, // 请替换为你的开发者密钥
  geocoderURL: 'https://apis.map.qq.com/ws/geocoder/v1/'
})

// 加载SDK的代码保持不变...
const loadSDK = () => {
  return new Promise((resolve, reject) => {
    if (window.TMap?.service?.Geocoder) {
      console.log('SDK已缓存，直接使用');
      TMap.value = window.TMap
      return resolve(window.TMap)
    }

    const script = document.createElement('script')
    script.src = `https://map.qq.com/api/gljs?v=2.exp&libraries=basic,service,vector&key=${tMapConfig.key}&callback=initTMap`
    window.initTMap = () => {
      if (!window.TMap?.service?.Geocoder) {
        console.error('SDK加载后仍无效');
        reject(new Error('地图SDK加载失败'))
        return
      }
      console.log('SDK动态加载完毕');
      TMap.value = window.TMap
      resolve(window.TMap)
    }

    script.onerror = (err) => {
      console.error('SDK加载报错', err);
      reject(`地图资源加载失败: ${err.message}`)
      document.head.removeChild(script)
    }

    document.head.appendChild(script)
  })
}

// 初始化地图 - 保持大部分不变，增加数据加载
const initMap = async () => {
  try {
    await loadSDK()
    console.log('开始创建地图实例');
    
    map = new TMap.value.Map(mapContainer.value, {
      center: new TMap.value.LatLng(24.9, 113.9),//前大往下，后大往左
      zoom: 10,
      minZoom: 9.25,
      maxZoom: 11,
      renderOptions: {
        antialias: true
      },
    })
    console.log('地图实例创建成功');
    
    // 创建标记点向量图层
    markersLayer = new TMap.value.MultiMarker({
      map: map,
      zIndex: 1000,
      collision:false,
      styles: {
        default: new TMap.value.MarkerStyle({
          width: 15, // 图标宽度
          height: 15, // 图标高度
          anchor: { x: 12.5, y: 12.5 }, // 居中定位
          src: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMCIgaGVpZ2h0PSIzMCI+PGNpcmNsZSBjeD0iMTUiIGN5PSIxNSIgcj0iMTAiIGZpbGw9InJlZCIvPjwvc3ZnPg=='
        })
      }
    });
    
    // 绑定标记点击事件
    markersLayer.on('click', handleMarkerClick);
    
    // 创建土壤类型多边形图层
    soilTypeVectorLayer = new TMap.value.MultiPolygon({
      map: map,
      styles: {
        default: new TMap.value.PolygonStyle({
          fillColor: '#cccccc',
          fillOpacity: 0.4,
          strokeColor: '#333',
          strokeWidth: 1
        })
      }    
    });  
   
    // 先加载数据，再更新标记
    await fetchData(); // 新增：获取数据
    if(state.excelData.length > 0) {
    const first = state.excelData[0];
    console.log('第一条数据坐标:', 
      first.纬度 || first.latitude, 
      first.经度 || first.longitude
    );
  }
    updateMarkers();   // 更新标记点
    
    // 标记地图就绪
    isMapReady.value = true;
    console.log('地图初始化完成');

  } catch (err) {
    isMapReady.value = true;
    console.error('initMap执行异常：', err);
    error.value = err.message
  }
}

// 新增：从接口获取数据
const fetchData = async () => {
  try {
    const response = await axios.get('http://localhost:3000/table/Atmosphere_summary_data', {
      timeout: 100000
    });

    state.excelData = response.data.filter(item => {
      // 检查数据完整性
      if(!item['样品编码'] || !item.纬度 || !item.经度) {
        console.warn(`数据不完整，已跳过: ${item.样品编码 || '未知编码'}`);
        return false;
      }
      
      const lat = Number(item.纬度);
      const lng = Number(item.经度);
      
      // 验证数值范围
      const isValid = !isNaN(lat) && !isNaN(lng) && 
                     lat >= -90 && lat <= 90 && 
                     lng >= -180 && lng <= 180;
      
      if(!isValid) {
        console.error(`无效经纬度: ${item.样品编码} (${item.纬度}, ${item.经度})`);
      }
      return isValid;
    });
    
    console.log('有效数据记录:', state.excelData.length);
  } catch (err) {
    console.error('数据请求失败详情:', err.response?.data || err.message);
    error.value = `数据加载失败: ${err.message}`;
    
  }
}

// 更新标记点 - 保持不变
const updateMarkers = () => {
  const coordCount = new Map();
  const geometries = state.excelData.map(item => {
    console.log(`ID: ${item.样品编码}, 坐标: (${item.纬度}, ${item.经度})`); // 替换字段名
    if (!item.样品编码 || !item.纬度 || !item.经度) {
      console.error(`无效数据项: ${JSON.stringify(item)}`);
      return null;
    }
    const lat = Number(item.纬度);
    const lng = Number(item.经度);

    if (isNaN(lat) || isNaN(lng)) {
      console.error(`坐标值非数字: ${item.样品编码} (${item.纬度}, ${item.经度})`);
      return null;
    }

    const coordKey = `${lat}_${lng}`;
    const count = coordCount.get(coordKey) || 0;
    coordCount.set(coordKey, count + 1);

    let finalLat = lat;
    let finalLng = lng;
    
    // 重复坐标添加偏移
    if (count > 0) {
      const latOffset = count * 0.01;  // 南北方向偏移（约11米）
      const lngOffset = count * 0.02;
      finalLat = lat + latOffset;
      finalLng = lng + lngOffset;
      
      console.log(`偏移点 ${item.样品编码}: ${lat},${lng} → ${finalLat},${finalLng}`);
    }

    const position = new TMap.value.LatLng(finalLat, finalLng);

    return {
      id: item.样品名称,
      styleId: 'default',
      position:position, // 替换字段名
      properties: {
        title: item.采样 || `采样点 ${item.样品名称}`, 
        sampler_id: item.样品编码,
        originalPosition: { lat, lng }
      }
    };
  })
  
  markersLayer.setGeometries(geometries);
  console.log('成功添加标记点数量:', geometries.length);
};

// Marker点击事件处理 - 保持不变
const handleMarkerClick = async (e) => {
  console.log('点击标记点');
  
  const marker = e.geometry;
  if (!marker) {
    console.error('未获取到标记点对象');
    return;
  }

  // 关闭之前的信息窗口
  if (infoWindow.value) {
    infoWindow.value.close();
    infoWindow.value = null;
  }
  
  // 显示加载中
  infoWindow.value = new TMap.value.InfoWindow({
    map: map,
    position: marker.position,
    content: '<div style="padding:12px;text-align:center">加载数据中...</div>',
    //offset: { x: 0, y: -32 }
  });
  infoWindow.value.open();

  try {
    const markerId = marker.id.trim();
    console.log('点击标记点样品名称:', markerId);
    
    // 直接从本地数据查找，无需二次请求
    const matchedData = state.excelData.find(item => 
      item.样品名称.trim() === markerId
    );

    if (!matchedData) {
      console.error("无法匹配的数据列表:", state.excelData.map(i => i.样品名称));
      throw new Error(`未找到样品名称为 ${markerId} 的监测数据`);
    }

    // 创建信息窗口内容
    const content = `
      <div class="water-info-window">
        <h3 class="info-title">${matchedData.采样}</h3>
        <div class="info-row">
          <span class="info-label">采样点ID:</span>
          <span class="info-value">${matchedData.样品名称}</span>
        </div>

        <div class="info-row">
          <span class="info-label">样品编号:</span>
          <span class="info-value">${matchedData.样品编号}</span>
        </div>
  
        <div class="contaminant-grid" style="grid-template-columns: repeat(2, 1fr); gap: 8px;">

          <div class="contaminant-item">
            <span class="contaminant-name">Cr mg/kg:</span>
            <span class="contaminant-value">${matchedData['Cr mg/kg']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">Cr ug/m3:</span>
            <span class="contaminant-value">${matchedData['Cr ug/m3']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">As mg/kg:</span>
            <span class="contaminant-value">${matchedData['As mg/kg']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">As ug/m3:</span>
            <span class="contaminant-value">${matchedData['As ug/m3']}</span>
          </div>
          
          <div class="contaminant-item">
            <span class="contaminant-name">Cd mg/kg:</span>
            <span class="contaminant-value">${matchedData['Cd mg/kg']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">Cd ug/m3:</span>
            <span class="contaminant-value">${matchedData['Cd ug/m3']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">Hg mg/kg:</span>
            <span class="contaminant-value">${matchedData['Hg mg/kg']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">Hg ug/m3:</span>
            <span class="contaminant-value">${matchedData['Hg ug/m3']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">Pb mg/kg:</span>
            <span class="contaminant-value">${matchedData['Pb mg/kg']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">Pb ug/m3:</span>
            <span class="contaminant-value">${matchedData['Pb ug/m3']}</span>
          </div>
          
          <div class="contaminant-item">
            <span class="contaminant-name">颗粒物的重量 mg:</span>
            <span class="contaminant-value">${matchedData['颗粒物的重量 mg']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">标准体积 m3:</span>
            <span class="contaminant-value">${matchedData['标准体积 m3']}</span>
          </div>

          <div class="contaminant-item">
            <span class="contaminant-name">颗粒物浓度ug/m3:</span>
            <span class="contaminant-value">${matchedData['颗粒物浓度ug/m3']}</span>
          </div>

        </div>
      </div>
    `;
    
    // 更新信息窗口
    infoWindow.value.setContent(content);
    
  } catch (error) {
    console.error('API请求失败:', error);
    
    // 显示错误信息
    const errorContent = `
      <div style="padding:12px;color:red">
        <h3>${marker.properties.title}</h3>
        <p>获取数据失败: ${error.message}</p>
      </div>
    `;
    
    infoWindow.value.setContent(errorContent);
  }
}

// 其余函数保持不变...
const manageTempMarker = {
  add: (lat, lng, phValue) => {
    if (activeTempMarker.value) {
      markersLayer.remove("-999")
    }
    
    // 确保已添加临时样式
    if (!markersLayer.getStyles().temp) {
      markersLayer.setStyles({
        temp: new TMap.value.MarkerStyle({
          width: 30,
          height: 30,
          anchor: { x: 12.5, y: 12.5 },
          src: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBkPSJNMTIgMkg2Yy0xLjEgMC0yIC45LTIgMnYxNmMwIDEuMS45IDIgMiAyaDEyYzEuMSAwIDIgLS45IDItMnYtNGMwLTEuMS0uOS0yLTItMmgtMnY0aC00di00SDEyVjJ6bTAgMTZINnYtOEgxOFYxOHoiIGZpbGw9IiNGRjAwMDAiLz48L3N2Zz4='
        })
      });
    }
    
    const tempMarker = markersLayer.add({
      id: "-999",
      position: new TMap.value.LatLng(lat, lng),
      styleId: 'temp',
      properties: {
        title: '克里金插值',
        phValue: parseFloat(phValue).toFixed(2),
        isTemp: true
      }
    })
    activeTempMarker.value = tempMarker
  },
  remove: () => {
    if (activeTempMarker.value) {
      markersLayer.remove("-999")
      activeTempMarker.value = null
    }
  }
}

onMounted(async () => {
  console.log('开始执行 onMounted');
  
  try {
    await initMap()
    console.log('地图初始化完成');
  } catch (err) {
    console.error('onMounted执行异常', err);
    error.value = err.message
  }
})

onBeforeUnmount(() => {
  if (activeTempMarker.value) {
    manageTempMarker.remove()
  }
  if (markersLayer) markersLayer.setMap(null)
  if (overlay) overlay.setMap(null)
  if (infoWindow.value) {
    infoWindow.value.close()
    infoWindow.value = null
  }
  if (soilTypeVectorLayer) soilTypeVectorLayer.setMap(null)
})
</script>

<style>
/* 原有样式保持不变，修改以下部分 */
.error-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  background-color: #ff4444;
  color: white;
  border-radius: 4px;
  z-index: 9999;
  box-shadow: 0 2px 8px rgba(0,0,0,0.2);
  animation: fadein 0.5s, fadeout 0.5s 4.5s;
}

@keyframes fadein {
  from { top: 0; opacity: 0; }
  to { top: 20px; opacity: 1; }
}

@keyframes fadeout {
  from { top: 20px; opacity: 1; }
  to { top: 0; opacity: 0; }
}

.map-page {
  position: relative;
  width: 100vw;
  height: 100vh;
}

.map-container {
  width: 100%;
  height: 100vh ;
  min-height: 600px;
  pointer-events: all;
}

.contaminants {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2px;
}

/* 窗口容器：精准控制尺寸 */
.water-info-window {
  max-width: 340px !important;
  width: 100%;
  height: auto;
  padding: 8px;
  box-sizing: border-box;
  background: #FFFFFF;
  border-radius: 8px;
  box-shadow: 0 3px 12px rgba(0, 32, 71, 0.1);
  border: 1px solid #e5e7eb;
  overflow: hidden !important;
}

/* 标题区样式 */
.info-title {
  font-size: 0.9rem;
  padding: 6px 8px;
  letter-spacing: 0.2px;
  border-bottom: 1px solid #f1f2f6;
  margin: 0 0 8px 0;
}

/* 基础数据行 */
.info-row {
  display: flex;
  align-items: center;
  margin: 4px 0;
  padding-left: 8px;
}

.info-label {
  font-size: 0.8rem;
  padding-right: 6px;
  flex: 0 0 80px;
}

.info-value {
  font-size: 0.8rem;
  padding: 2px 6px;
  border-left: 2px solid #e5e7eb;
}

/* 污染物网格：优化布局使名称和数值在同一行并放大字体 */
.contaminant-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 4px; /* 减小间距以补偿字体增大 */
  margin: 4px 0;
}

/* 污染物项：确保名称和数值在同一行 */
.contaminant-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 3px 5px; /* 减小内边距 */
  background: #f9fafb;
  border-radius: 4px;
}

/* 增大字体大小，保持在同一行 */
.contaminant-name {
  font-size: 0.8rem; /* 增大字体 */
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
  margin-right: 5px;
}

.contaminant-value {
  font-size: 0.8rem; /* 增大字体 */
  background: #e5e7eb;
  padding: 2px 6px;
  border-radius: 3px;
  min-width: 40px;
  text-align: center;
  flex-shrink: 0;
}
</style>