<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
})
let soilTypeLayer = null
let currentInfoWindow = null;
let surveyDataLayer = ref(null);
let selectedPolygon = ref(null); // 补充定义

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.39, 114),//前大往下，后大往左
      zoom: 9.25,
      minZoom: 8,
      //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: 30, // 图标宽度
          height: 30, // 图标高度
          anchor: { x: 12.5, y: 12.5 }, // 居中定位
          src: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cG9seWdvbiBwb2ludHM9IjEyLDIgMiwyMCAyMiwyMCIgZmlsbD0iIzFFODhFNSIvPjwvc3ZnPg=='
        })
      }
    });
    
    // 绑定标记点击事件
    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('地图初始化完成');

    // 创建样式标签并注入样式
    const style = document.createElement('style');
    style.textContent = `
      .water-info-window {
        max-width: 80vw !important;
        width: auto !important;
        overflow: visible !important;
      }
      
      .info-value {
        white-space: normal !important;
        word-wrap: break-word !important;
        max-width: none !important;
      }
    `;
    document.head.appendChild(style);

  } 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_company_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 geometries = state.excelData.map(item => {  
  //console.log(`ID: ${item.污染源序号}, 坐标: (${item.纬度}, ${item.经度})`); // 替换为新字段  
  if (!item.污染源序号 || !item.纬度 || !item.经度) return null;  
  const lat = Number(item.纬度);
  const lng = Number(item.经度);  
  if (isNaN(lat) || isNaN(lng)) return null;  

  return {
    id: item.污染源序号, // 标记 ID 设为「污染源序号」
    styleId: 'default',
    position: new TMap.value.LatLng(lat, lng), 
    properties: {
      title: item.公司 || `污染源 ${item.污染源序号}`, // 标题用「公司」名称
      sampler_id: item.污染源序号,
    }
  };
  });
  
  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: -220 },
    
  });
  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">污染源序号:</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="info-row">
      <span class="info-label">类型:</span>
      <span class="info-value">${matchedData.类型}</span>
    </div>

    <div class="info-row">
      <span class="info-label">大气颗粒物排放(t/a):</span>
      <span class="info-value">${matchedData['大气颗粒物排放(t/a)']}</span>
    </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,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cG9seWdvbiBwb2ludHM9IjEyLDIgMiwyMCAyMiwyMCIgZmlsbD0iIzFFODhFNSIvPjwvc3ZnPg=='
        })
      });
    }
    
    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;
}



.water-info-window {
  max-width: 80vw; /* 相对视口最大值，更加灵活 */
  width: auto;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0,0,0,0.15);
  background: #fff;
  border: 1px solid #e5e7eb;
  overflow: visible; /* 配合自动平移，确保内容不被裁剪 */
}

/* 标题区：增加渐变装饰线 */
.info-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e3a8a;
  text-align: center;
  margin-bottom: 14px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e5e7eb;
  position: relative; /* 为伪元素准备 */
}
.info-title::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 20px;
  right: 20px;
  height: 1px;
  background: linear-gradient(to right, 
    rgba(30, 58, 138, 0.1), 
    rgba(30, 58, 138, 0.2), 
    rgba(30, 58, 138, 0.1)
  );
}

/* 数据行：Grid 布局确保对齐 */
.info-row {
  display: grid;
  grid-template-columns: 180px 1fr; /* 标签180px，值自适应 */
  gap: 12px; /* 列间距 */
  align-items: flex-start;
  margin: 10px 0;
  margin: 10px 0;/**增加行间距，提升可读性 */
}

/* 标签：右对齐 + 深灰配色 */
.info-label {
  text-align: right;
  color: #6b7280;
  font-size: 14px;
}

/* 数据值：浅灰背景 + 智能换行 */
.info-value {
  padding: 6px 10px;
  background: #f3f4f6;
  border-radius: 6px;
  font-size: 14px;
  white-space: normal;   /* 长文本强制换行 */
  word-wrap: break-word;
  overflow: visible;/**不隐藏溢出内容 */
  text-overflow: clip;
  min-height: 24px;        /* 确保最小高度，避免内容塌陷 */
}

/* 响应式适配（小窗口自动压缩） */
@media (max-width: 480px) {
  .water-info-window {
    max-width: 90vw; /* 占满视口宽度 */
    padding: 10px;
  }
  .info-row {
    grid-template-columns: 100px 1fr; /* 缩小标签宽度 */
  }
}
</style>