<template>
  <div class="amap-container">
    <div v-if="mapDisplay" class="map-wrapper">
      <div class="map-header">
        <span class="map-title">位置信息</span>
        <button 
          v-if="!map" 
          @click="initMap" 
          class="test-btn"
          title="测试地图加载"
        >
          加载地图
        </button>
      <!--   <button 
          v-if="map && polylines && polylines.length > 0" 
          @click="drawRoute" 
          class="route-btn"
          title="绘制路线"
        >
          绘制路线
        </button>
        <button 
          v-if="map && currentPolyline" 
          @click="clearRoute" 
          class="clear-btn"
          title="清除路线"
        >
          清除路线
        </button> -->
      </div>
      <div id="amap-container" class="map-content"></div>
      <div v-if="routeInfo" class="route-info">
        <div class="route-summary">
          <span class="route-distance">总距离: {{ routeInfo.distance }}km</span>
          <span class="route-points">途经点: {{ routeInfo.points }}个</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';

const props = defineProps({
  mapDisplay: {
    type: [Boolean, Object],
    default: false
  },
  center: {
    type: Object,
    default: () => ({ lng: 121.265276, lat: 31.375566 })
  },
  polylines: {
    type: Array,
    default: () => []
  }
});

const map = ref(null);
const marker = ref(null);
const startMarker = ref(null);
const endMarker = ref(null);
const currentPolyline = ref(null);
const routeInfo = ref(null);

// 初始化地图
const initMap = () => {
  if (!props.mapDisplay || !window.AMap) {
    console.warn('地图未启用或高德地图SDK未加载');
    return;
  }

  try {
    // 创建地图实例
    map.value = new window.AMap.Map('amap-container', {
      zoom: 10,
      center: [props.center.lng, props.center.lat],
      mapStyle: 'amap://styles/normal'
    });

    // 添加标记点
    marker.value = new window.AMap.Marker({
      position: [props.center.lng, props.center.lat],
      title: '当前位置',
      icon: new window.AMap.Icon({
        size: new window.AMap.Size(32, 32),
      })
    });

    // 将标记添加到地图
    map.value.add(marker.value);

    // 添加缩放控件
    map.value.addControl(new window.AMap.Scale());
    map.value.addControl(new window.AMap.ToolBar());

    // 添加信息窗体
    const infoWindow = new window.AMap.InfoWindow({
      content: `
        <div style="padding: 10px;">
          <h4>位置信息</h4>
          <p>经度: ${props.center.lng}</p>
          <p>纬度: ${props.center.lat}</p>
        </div>
      `,
      offset: new window.AMap.Pixel(0, -30)
    });

    // 点击标记显示信息窗体
    marker.value.on('click', () => {
      infoWindow.open(map.value, marker.value.getPosition());
    });

    // 如果有路线数据，自动绘制
    if (props.polylines && props.polylines.length > 0) {
      nextTick(() => {
        drawRoute();
      });
    }

  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

// 绘制路线
const drawRoute = () => {
  if (!map.value || !props.polylines || props.polylines.length === 0) {
    return;
  }

  // 清除之前的路线
  clearRoute();

  try {
    props.polylines.forEach((polylineData, index) => {
      if (polylineData.path && polylineData.path.length > 0) {
        // 转换坐标格式
        const path = polylineData.path.map(point => [point.lng, point.lat]);
        
        // 创建折线
        const polyline = new window.AMap.Polyline({
          path: path,
          strokeColor: polylineData.strokeColor || '#FF0000',
          strokeWeight: polylineData.strokeWeight || 5,
          strokeOpacity: 0.8
        });

        // 添加到地图
        map.value.add(polyline);
        currentPolyline.value = polyline;

        // 添加起点标记
        if (path.length > 0) {
          startMarker.value = new window.AMap.Marker({
            position: path[0],
            title: '起点',
            icon: new window.AMap.Icon({
              size: new window.AMap.Size(24, 24),
              image: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEyIDJDNi40OCAyIDIgNi40OCAyIDEyQzIgMTcuNTIgNi40OCAyMiAxMiAyMkMxNy41MiAyMiAyMiAxNy41MiAyMiAxMkMyMiA2LjQ4IDE3LjUyIDIgMTIgMloiIGZpbGw9IiM1MkM0MUEiLz4KPHBhdGggZD0iTTEyIDZDNi40OCA2IDIgMTAuNDggMiAxNkMyIDE5LjUyIDQuNDggMjIgOCAyMkMxMS41MiAyMiAxNSAxOS41MiAxNSAxNkMxNSAxMi40OCAxMS41MiA5IDggOUM0LjQ4IDkgMSAxMi40OCAxIDE2QzEgMTkuNTIgNC40OCAyMyA4IDIzQzExLjUyIDIzIDE1IDE5LjUyIDE1IDE2QzE1IDEyLjQ4IDExLjUyIDkgOCA5WiIgZmlsbD0iI0ZGRiIvPgo8L3N2Zz4K'
            })
          });
          map.value.add(startMarker.value);
        }

        // 添加终点标记
        if (path.length > 1) {
          endMarker.value = new window.AMap.Marker({
            position: path[path.length - 1],
            title: '终点',
            icon: new window.AMap.Icon({
              size: new window.AMap.Size(24, 24),
              image: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTEyIDJDNi40OCAyIDIgNi40OCAyIDEyQzIgMTcuNTIgNi40OCAyMiAxMiAyMkMxNy41MiAyMiAyMiAxNy41MiAyMiAxMkMyMiA2LjQ4IDE3LjUyIDIgMTIgMloiIGZpbGw9IiNGRjRENEYiLz4KPHBhdGggZD0iTTEyIDZDNi40OCA2IDIgMTAuNDggMiAxNkMyIDE5LjUyIDQuNDggMjIgOCAyMkMxMS41MiAyMiAxNSAxOS41MiAxNSAxNkMxNSAxMi40OCAxMS41MiA5IDggOUM0LjQ4IDkgMSAxMi40OCAxIDE2QzEgMTkuNTIgNC40OCAyMyA4IDIzQzExLjUyIDIzIDE1IDE5LjUyIDE1IDE2QzE1IDEyLjQ4IDExLjUyIDkgOCA5WiIgZmlsbD0iI0ZGRiIvPgo8L3N2Zz4K'
            })
          });
          map.value.add(endMarker.value);
        }

        // 计算路线信息
        calculateRouteInfo(path);

        // 调整地图视野以包含整个路线
        map.value.setFitView([polyline, startMarker.value, endMarker.value], false, [50, 50, 50, 50]);
      }
    });

  } catch (error) {
    console.error('路线绘制失败:', error);
  }
};

// 清除路线
const clearRoute = () => {
  if (currentPolyline.value) {
    map.value.remove(currentPolyline.value);
    currentPolyline.value = null;
  }
  if (startMarker.value) {
    map.value.remove(startMarker.value);
    startMarker.value = null;
  }
  if (endMarker.value) {
    map.value.remove(endMarker.value);
    endMarker.value = null;
  }
  routeInfo.value = null;
};

// 计算路线信息
const calculateRouteInfo = (path) => {
  if (!path || path.length < 2) return;

  let totalDistance = 0;
  
  // 计算总距离（简化计算，使用直线距离）
  for (let i = 0; i < path.length - 1; i++) {
    const p1 = path[i];
    const p2 = path[i + 1];
    const distance = calculateDistance(p1[1], p1[0], p2[1], p2[0]);
    totalDistance += distance;
  }

  routeInfo.value = {
    distance: totalDistance.toFixed(2),
    points: path.length
  };
};

// 计算两点间距离（公里）
const calculateDistance = (lat1, lng1, lat2, lng2) => {
  const R = 6371; // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180;
  const dLng = (lng2 - lng1) * Math.PI / 180;
  const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  return R * c;
};

// 销毁地图
const destroyMap = () => {
  clearRoute();
  if (map.value) {
    map.value.destroy();
    map.value = null;
    marker.value = null;
  }
};

// 更新地图中心点
const updateMapCenter = () => {
  if (map.value && props.center) {
    map.value.setCenter([props.center.lng, props.center.lat]);
    if (marker.value) {
      marker.value.setPosition([props.center.lng, props.center.lat]);
    }
  }
};

// 监听props变化
watch(() => props.mapDisplay, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initMap();
    });
  } else {
    destroyMap();
  }
});

watch(() => props.center, (newCenter) => {
  if (newCenter && map.value) {
    updateMapCenter();
  }
}, { deep: true });

watch(() => props.polylines, (newPolylines) => {
  if (newPolylines && newPolylines.length > 0 && map.value) {
    nextTick(() => {
      drawRoute();
    });
  }
}, { deep: true });

// 组件挂载时初始化地图
onMounted(() => {
  // 检查是否已加载高德地图SDK
  if (window.AMap && props.mapDisplay) {
    nextTick(() => {
      initMap();
    });
  }
});

// 组件卸载时销毁地图
onUnmounted(() => {
  destroyMap();
});
</script>

<style scoped>
.amap-container {
  width: 100%;
  height: 100%;
}

.map-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e9ecef;
  margin: 16px 0;
}

.map-header {
  padding: 12px 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  display: flex;
  align-items: center;
  gap: 8px;
}

.map-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  flex: 1;
}

.test-btn, .route-btn, .clear-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.test-btn {
  background: #1890ff;
  color: white;
}

.test-btn:hover {
  background: #40a9ff;
}

.route-btn {
  background: #52c41a;
  color: white;
}

.route-btn:hover {
  background: #73d13d;
}

.clear-btn {
  background: #ff4d4f;
  color: white;
}

.clear-btn:hover {
  background: #ff7875;
}

.route-info {
  padding: 8px 16px;
  background: #f0f8ff;
  border-top: 1px solid #e9ecef;
}

.route-summary {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #666;
}

.route-distance, .route-points {
  display: flex;
  align-items: center;
}

/* 深色主题适配 */
:deep(.dark-theme) .map-wrapper {
  background: #1f1f1f;
  border-color: #404040;
}

:deep(.dark-theme) .map-header {
  background: #2d2d2d;
  border-color: #404040;
}

:deep(.dark-theme) .map-title {
  color: #e0e0e0;
}

:deep(.dark-theme) .route-info {
  background: #1a1a1a;
  border-color: #404040;
}

:deep(.dark-theme) .route-summary {
  color: #b0b0b0;
}

.map-content {
  flex: 1;
  min-height: 300px;
  background: #f5f5f5;
}

#amap-container {
  width: 100%;
  height: 100%;
}
</style>
