<template>
  <div class="map-container">
    <div id="container" ref="mapRef"></div>
    <div v-if="loading" class="loading">地图加载中...</div>
    <div v-if="error" class="error">{{ error }}</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";

const mapRef = ref(null);
const loading = ref(true);
const error = ref("");

let map = null;
let polylines = [];

window._AMapSecurityConfig = {
  securityJsCode: "75a8291a9e8f7c838fc5e4dd0d538f30",
};
// 高德地图API密钥（请替换为您的实际密钥）
const AMAP_KEY = "c691971f068b92c897fb908c4ddef6d4";

// 折线数据 - 覆盖全国各省的不同线路
const polylineData = [
  // 省内连接线
  {
    name: "丽江鹤峰到邬阳路线（从国道出发）",
    type: "national",
    path: [
      [100.23, 26.88], // 丽江（云南省丽江市）
      [101.5, 27.2], // 大理
      [102.8, 27.8], // 攀枝花
      [104.0, 28.5], // 宜宾
      [105.0, 29.5], // 泸州
      [106.5, 29.8], // 重庆
      [108.0, 30.5], // 恩施
      [109.8, 30.2], // 建始
      [110.43, 29.87], // 鹤峰（恩施州鹤峰县）
      [110.2, 30.0], // 走马镇
      [110.1, 30.1], // 太平镇
      [110.05, 30.15], // 邬阳乡
    ],
  },
  {
    name: "广水鹤峰到邬阳路线",
    type: "provincial",
    path: [
      [113.85, 31.62], // 广水（随州市广水市）
      [112.5, 31.2], // 安陆
      [111.8, 31.0], // 京山
      [111.2, 30.8], // 钟祥
      [110.8, 30.5], // 荆门
      [110.6, 30.2], // 当阳
      [110.43, 29.87], // 鹤峰（恩施州鹤峰县）
      [110.2, 30.0], // 走马镇
      [110.1, 30.1], // 太平镇
      [110.05, 30.15], // 邬阳乡
    ],
  },
  {
    name: "恩施到武汉路线",
    type: "provincial",
    path: [
      [109.48, 30.28], // 恩施
      [110.2, 30.5], // 宜昌
      [111.3, 30.7], // 荆州
      [112.3, 30.6], // 潜江
      [113.0, 30.8], // 仙桃
      [114.27, 30.58], // 武汉
    ],
  },
  {
    name: "临沂到威海路线",
    type: "national",
    path: [
      [118.35, 35.05], // 临沂
      [118.8, 35.5], // 沂水
      [119.2, 36.0], // 潍坊
      [119.8, 36.8], // 烟台
      [121.38, 37.52], // 威海
    ],
  },
  {
    name: "丹东到齐齐哈尔路线",
    type: "provincial",
    path: [
      [124.38, 40.13], // 丹东
      [123.8, 40.5], // 凤城
      [123.5, 41.0], // 本溪
      [123.38, 41.8], // 沈阳
      [122.8, 42.2], // 铁岭
      [122.5, 43.0], // 四平
      [123.9, 44.5], // 大庆
      [123.97, 47.35], // 齐齐哈尔
    ],
  },
  {
    name: "华山到兵马俑路线",
    type: "provincial",
    path: [
      [110.09, 34.45], // 华山
      [109.8, 34.4], // 华阴
      [109.5, 34.35], // 渭南
      [109.27, 34.38], // 临潼
      [109.28, 34.38], // 兵马俑
    ],
  },
  {
    name: "吉安到南昌路线",
    type: "provincial",
    path: [
      [114.98, 27.12], // 吉安
      [115.2, 27.5], // 吉水
      [115.5, 28.0], // 樟树
      [115.8, 28.4], // 丰城
      [115.89, 28.68], // 南昌
    ],
  },
];

// 加载高德地图API
const loadAmapScript = () => {
  return new Promise((resolve, reject) => {
    if (window.AMap) {
      resolve();
      return;
    }

    const script = document.createElement("script");
    script.type = "text/javascript";
    script.async = true;

    // 使用您的高德地图API密钥
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${AMAP_KEY}&plugins=AMap.PolylineEditor`;

    script.onerror = () => {
      reject(new Error("高德地图API加载失败，请检查网络连接"));
    };

    script.onload = () => {
      if (window.AMap) {
        resolve();
      } else {
        reject(new Error("高德地图API初始化失败"));
      }
    };

    document.head.appendChild(script);
  });
};

// 初始化地图
const initMap = async () => {
  try {
    loading.value = true;
    error.value = "";

    // 加载高德地图API
    await loadAmapScript();
    // 创建地图实例
    map = new AMap.Map("container", {
      zoom: 3.9,
      center: [108.95, 34.27], // 中国中心点
      viewMode: "2D",
      mapStyle: "amap://styles/2d017848d08f94f20b6e50aaae661148",
      minZoom: 4,
    });
    // 标记
    const markers = [];
    const positionsList = [
      {
        number: 1,
        position: [116.405467, 39.907761],
      },
      {
        number: 5,
        position: [114.298569, 30.584354],
      },
      {
        number: 6,
        position: [117.190186, 39.125595],
      },
      {
        number: 4,
        position: [112.549248, 37.857014],
      },
      {
        number: 8,
        position: [123.429092, 41.796768],
      },
      {
        number: 2,
        position: [121.472641, 31.231707],
      },
      {
        number: 7,
        position: [119.306236, 26.075302],
      },
      {
        number: 9,
        position: [106.504959, 29.533155],
      },
      {
        number: 6,
        position: [91.1145, 29.64415],
      },
      {
        number: 3,
        position: [101.77782, 36.61729],
      },
      {
        number: 8,
        position: [87.61688, 43.82663],
      },
      {
        number: 10,
        position: [111.75199, 40.84149],
      },
      {
        number: 9,
        position: [126.642464, 45.756966],
      },
    ];

    for (var i = 0, marker; i < positionsList.length; i++) {
      marker = new AMap.Marker({
        map: map,
        position: positionsList[i].position,
        // icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
        offset: new AMap.Pixel(-13, -30),
        content:
          "" +
          '<div class="custom-content-marker">' +
          '<img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png">' +
          `<div class="close-btn"">${positionsList[i].number}</div>` +
          "</div>",
      });
      markers.push(marker);
    }
    map.add([markers]);

    // const viaMarker = new AMap.Marker({
    //   position: new AMap.LngLat(116.38, 39.92),
    //   content: markerContent,
    //   // 将一张图片的地址设置为 icon
    //   // icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-via-marker.png",
    //   // 设置了 icon 以后，设置 icon 的偏移量，以 icon 的 [center bottom] 为原点
    //   offset: new AMap.Pixel(-31, -30),
    //   size: new AMap.Size(45, 65),
    //   // imageSize: new AMap.Size(135, 40),
    //   // imageOffset: new AMap.Pixel(-95, -3),
    // });
    // map.add([viaMarker]);

    // 地图初始化完成后自动添加路线
    addPolylines();

    loading.value = false;
  } catch (err) {
    console.error("地图初始化失败:", err);
    error.value = `地图加载失败: ${err.message}`;
    loading.value = false;
  }
};

// 添加所有折线到地图
const addPolylines = () => {
  if (!map) return;

  // 清除之前的折线
  clearPolylines();

  // 添加折线
  polylineData.forEach((data, index) => {
    // 所有线路统一使用黄色
    const polyline = new AMap.Polyline({
      path: data.path,
      strokeColor: "#FFD700", // 黄色
      strokeWeight: 4,
      strokeOpacity: 0.8,
      strokeStyle: "solid",
      cursor: "pointer",
    });

    // 添加鼠标悬停事件
    polyline.on("mouseover", (e) => {
      // 获取道路类型中文名
      const getTypeName = (type) => {
        const typeNames = {
          highway: "高速公路",
          national: "国道",
          provincial: "省道",
          urban: "城市快速路",
          railway: "铁路",
        };
        return typeNames[type] || "其他道路";
      };

      // 创建信息窗体
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div style="padding: 12px; min-width: 200px;">
            <h4 style="margin: 0 0 8px 0; color: #333; font-size: 14px; font-weight: bold;">${
              data.name
            }</h4>
            <p style="margin: 4px 0; color: #666; font-size: 12px;">
              <strong>类型:</strong> ${getTypeName(data.type)}
            </p>
            <p style="margin: 4px 0; color: #666; font-size: 12px;">
              <strong>起点:</strong> ${data.path[0][0].toFixed(
                2
              )}, ${data.path[0][1].toFixed(2)}
            </p>
            <p style="margin: 4px 0; color: #666; font-size: 12px;">
              <strong>终点:</strong> ${data.path[
                data.path.length - 1
              ][0].toFixed(2)}, ${data.path[data.path.length - 1][1].toFixed(2)}
            </p>
            <p style="margin: 4px 0; color: #666; font-size: 12px;">
              <strong>途经点数:</strong> ${data.path.length}个
            </p>
          </div>
        `,
        offset: new AMap.Pixel(0, -30),
      });

      infoWindow.open(map, e.lnglat);

      // 鼠标离开时关闭信息窗体
      polyline.on("mouseout", () => {
        infoWindow.close();
      });
    });

    // 添加点击事件
    polyline.on("click", (e) => {
      console.log(`点击了折线: ${data.name}`);
    });

    map.add(polyline);
    polylines.push(polyline);
  });
};

// 清除所有折线
const clearPolylines = () => {
  if (map && polylines.length > 0) {
    map.remove(polylines);
    polylines = [];
  }
};

onMounted(() => {
  initMap();
});

onUnmounted(() => {
  if (map) {
    map.destroy();
  }
});
</script>

<style scoped lang="less">
.map-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;

  #container {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 20px;
    border-radius: 8px;
    font-size: 16px;
    z-index: 1000;
  }

  .error {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: rgba(255, 0, 0, 0.1);
    color: #ff0000;
    padding: 20px;
    border-radius: 8px;
    font-size: 14px;
    border: 1px solid #ff0000;
    z-index: 1000;
    max-width: 80%;
    text-align: center;
  }
}
.custom-content-marker {
  position: relative;
  width: 25px;
  height: 34px;
}
/deep/.close-btn {
  position: absolute;
  color: #fff;
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
