<template>
  <div class="tourism">
    <div id="container"></div>
  </div>
</template>
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import { nextTick, onMounted, reactive, ref } from "vue";
import gansuLine from "./newLine.json";
let map = null;
window._AMapSecurityConfig = {
  securityJsCode: "75a8291a9e8f7c838fc5e4dd0d538f30",
};
// 初始化地图
const handleInitMap = () => {
  let selectName = sessionStorage.getItem("selectedContentBtn");
  AMapLoader.load({
    key: "c691971f068b92c897fb908c4ddef6d4", // 申请好的Web端开发者Key
    version: "2.0",
    plugins: ["AMap.DistrictSearch", "AMap.GeoJSON"],
  })
    .then((AMap) => {
      map = new AMap.Map("container", {
        //设置地图容器id
        viewMode: "2D",
        zoom: 4, //初始化地图级别
        center: [100.808299, 35.791787], //初始化地图中心点位置
        expandZoomRange: true, // 开启显示范围设置
        mapStyle: "amap://styles/2d017848d08f94f20b6e50aaae661148",
        rotateEnable: false, // 是否可以旋转
        copyrightControl: false,
        logoControl: false,
      });
      const mapSize = map.getSize();
      mapSize.width < 780 ? map.setZoom(3.5) : map.setZoom(4);
      const minZoom = 4;
      // map.on("zoomchange", function (e) {
      //   map.getZoom() < 2 ? map.setZoom(minZoom) : map.setZoom(15);
      // });
      handleDistrict();
      addPolylines();
      handleAddMarket(selectName);
    })
    .catch((e) => {
      // console.log(e);
    });
};
// 高亮和描边
const handleDistrict = () => {
  let districtSearch = new AMap.DistrictSearch({
    subdistrict: 0, //获取边界不需要返回下级行政区
    extensions: "all", //返回行政区边界坐标组等具体信息
    level: "province", //查询行政级别为 市 province-省 district-市
  });
  let polygons = [];
  let arr = ["中华人民共和国"]; //此处为高亮的市名
  // arr.forEach((item) => {
  districtSearch.search("中华人民共和国", function (status, result) {
    // 查询成功时，result即为对应的行政区信息
    // map.remove(polygons); //清除上次结果
    let bounds = result.districtList[0].boundaries;
    // if (bounds) {
    //   for (let i = 0, l = bounds.length; i < l; i++) {
    //     //生成行政区划polygon
    //     let polygon = new AMap.Polygon({
    //       strokeWeight: 1,
    //       path: bounds[i],
    //       fillOpacity: 0.4,
    //       fillColor: "#80d8ff",
    //       strokeColor: "#0091ea",
    //     });
    //     polygons.push(polygon);
    //   }
    // }
    // 描边
    for (let i = 0; i < bounds.length; i++) {
      let outerPolyline = new AMap.Polyline({
        path: bounds[i],
        strokeColor: "#72A8FF",
        strokeWeight: 3,
        map: map,
      });
      map.add(outerPolyline);
    }
    map.add(polygons);
    map.setFitView(polygons); //视口自适应
  });
  // });
};
// 添加新路线
const addPolylines = () => {
  let geojsonObj = new AMap.GeoJSON({
    geoJSON: gansuLine,
    getPolyline: function (geojson, lnglats) {
      // 生成路线
      let polylineObj = new AMap.Polyline({
        path: lnglats,
        strokeWeight: 4,
        strokeColor: "#F0E82A",
        extData: geojson.properties, // 自定义属性数据
      });
      // 生成新的路线，用于覆盖旧的
      const newPolyline = new AMap.Polyline({
        path: lnglats,
        strokeWeight: 4,
        strokeColor: "#00DDEB",
        isOutline: true,
        borderWeight: 2,
        outlineColor: "rgba(0, 221, 235, 1)",
        cursor: "pointer",
      });
      map.add(newPolyline);
      newPolyline.hide();

      // 获取路线数据
      const properties = polylineObj.getExtData();
      // 填报内容
      let content = `
          <div class="infoWindow-title">项目OOI</div>
          <div class="infoWindow-content">
              <p>
                <span class="infoWindow-content-title">数据01:</span>
                <span class="infoWindow-content-value">${properties.amount}<span class="infoWindow-unit">单位</span></span>
              </p>
              <p>
                <span class="infoWindow-content-title">数据02:</span>
                <span class="infoWindow-content-value">${properties.amount}<span class="infoWindow-unit">单位</span></span>
              </p>
              <p>
                <span class="infoWindow-content-title">数据03:</span>
                <span class="infoWindow-content-value">${properties.amount}<span class="infoWindow-unit">单位</span></span>
              </p>
            </div>
          <div class="infoWindow-bottom"></div>
        `;
      // 创建 infoWindow 实例
      let infoWindow = new AMap.InfoWindow({
        isCustom: true, // 使用自定义窗体
        autoMove: true, // 是否自动调整窗体到视野内
        closeWhenClickMap: true, // 控制是否在鼠标点击地图后关闭信息窗体
        content: content, // 传入 dom 对象，或者 html 字符串
        offset: new AMap.Pixel(120, 100),
      });

      // 鼠标经过
      polylineObj.on("mouseover", function (e) {
        newPolyline.show();
        infoWindow.open(map, [`${e.lnglat.getLng()}`, `${e.lnglat.getLat()}`]);
      });
      // 鼠标移出
      polylineObj.on("mouseout", function (e) {
        newPolyline.hide();
        infoWindow.close();
      });

      // 鼠标双击
      polylineObj.on("dblclick", function (e) {
        const data = polylineObj.getExtData();
        // showProject(data);
      });
      return polylineObj;
    },
  });
  map.add(geojsonObj);
};
// 添加标记
let currentMarkers = []; // 存储当前显示的标记
const handleAddMarket = (selectName) => {
  // 清除之前的所有标记
  if (currentMarkers.length > 0) {
    map.remove(currentMarkers);
    currentMarkers = [];
  }

  // 额外确保清除所有标记（防止其他地方创建的标记）
  if (map) {
    map.getAllOverlays("marker").forEach((marker) => {
      map.remove(marker);
    });
  }

  // 根据不同状态定义标记数据
  const markerData = {
    建设: [
      // 安徽
      { number: 1, position: [117.27, 31.86] },
      // 广东
      { number: 1, position: [113.2806, 23.1252] },
      // 陕西
      { number: 2, position: [112.5492, 37.857] },
      // 广西
      { number: 2, position: [108.3664, 22.8177] },
      // 山东
      { number: 2, position: [121.6167, 38.9167] },
      // 河北
      { number: 1, position: [114.52, 38.05] },
    ],
    试运营: [
      // 四川
      { number: 2, position: [117.27, 31.86] },
      // 山东
      { number: 3, position: [121.6167, 38.9167] },
      // 云南
      { number: 1, position: [102.7333, 25.05] },
      // 陕西
      { number: 3, position: [112.5492, 37.857] },
      // 广西
      { number: 1, position: [108.3664, 22.8177] },
      // 湖北
      { number: 1, position: [114.3052, 30.5929] },
    ],
    运营: [
      // 四川
      { number: 1, position: [117.27, 31.86] },
      // 山东
      { number: 1, position: [121.6167, 38.9167] },
      // 湖北
      { number: 1, position: [114.3052, 30.5929] },
    ],
    退出: [
      // 河南
      { number: 3, position: [113.65, 34.7667] },
    ],
    立项: [], // 立项没有标记
  };

  const positionsList = markerData[selectName] || [];

  // 如果是"立项"或者没有数据，直接返回，不创建任何标记
  if (!positionsList || positionsList.length === 0) {
    return;
  }

  // 创建新的标记
  for (var i = 0; i < positionsList.length; i++) {
    const marker = new AMap.Marker({
      map: map,
      position: positionsList[i].position,
      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="anchorPoint">${positionsList[i].number}</div>` +
        "</div>",
    });
    currentMarkers.push(marker);
  }
};
// 暴露更新标记的方法给父组件
const updateMarkers = (selectName) => {
  handleAddMarket(selectName);
};

// 暴露方法给父组件
defineExpose({
  updateMarkers,
});
onMounted(() => {
  handleInitMap();
});
</script>

<style scoped lang="less">
.tourism {
  width: 100%;
  .vh(height, 709);
}
.custom-content-marker {
  position: relative;
  width: 25px;
  height: 34px;
}
:deep(.infoWindow-title) {
  background-image: url("../assets/images/标题.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  width: 299px;
  line-height: 56px;
  padding-left: 10px;
  font-weight: 700;
}
:deep(.infoWindow-content) {
  background-image: url("../assets/images/信息文本.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  width: 299px;
  height: 100x;
  padding-left: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
}
:deep(.infoWindow-bottom) {
  background-image: url("../assets/images/下标.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  margin-top: 1px;
  height: 22px;
}
:deep(.infoWindow-content-title) {
  font-size: 18px;
  color: #fff;
  font-weight: 400;
}
:deep(.infoWindow-content-value) {
  font-weight: 400;
  font-size: 24px;
  color: #93d2ff;
}
:deep(.infoWindow-unit) {
  font-size: 20px;
  color: #93d2ff;
  display: inline-block;
  margin-left: 3px;
}
:deep(.anchorPoint) {
  position: absolute;
  color: #fff;
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
}

:deep(.amap-logo) {
  display: none;
  opacity: 0 !important;
}
:deep(.amap-copyright) {
  opacity: 0;
}
</style>
