<template>
  <div
    id="container"
    v-loading="mapLoading"
    element-loading-background="rgba(122, 122, 122, 0)"
  ></div>
</template>
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import {
  nextTick,
  onMounted,
  reactive,
  ref,
  onUnmounted,
  onActivated,
  defineEmits,
  watch,
} from "vue";

const props = defineProps({
  tabKey: {
    type: String,
    default: () => "",
  },
});
watch(
  () => props.tabKey,
  (newVal) => {
    // 根据页面内容，调整地图显示位置
    const center = ["lixiang", "tuichu"].includes(props.tabKey)
      ? [100.808299, 35.791787]
      : [127.808299, 35.791787];
    map && map.setCenter(center);
    map.setZoom(4);
    handleAddMarket();
  }
);

// 定义事件
const emit = defineEmits(["province-selected"]);
import gansuLine from "./newLine.json";
let map = null;
window._AMapSecurityConfig = {
  securityJsCode: "7aee6d6553ba9a8178e0c57b60a51481",
};
let geojsonObj = null;
let currentMarkers = [];
let provincePolylines = [];
let mapLoading = ref(true);

// 初始化地图
const handleInitMap = () => {
  map = new AMap.Map("container", {
    //设置地图容器id
    // mask: mask,
    viewMode: "2D",
    zoom: 4, //根据屏幕宽度设置初始化地图级别
    zooms: [4, 8],
    center: ["lixiang", "tuichu"].includes(props.tabKey)
      ? [100.808299, 35.791787]
      : [127.808299, 35.791787], //初始化地图中心点位置
    expandZoomRange: true, // 开启显示范围设置
    mapStyle: "amap://styles/d9cd35cfbd75e272e528a7fde0bcfc53",
    rotateEnable: false, // 是否可以旋转
    copyrightControl: false,
    logoControl: false,
    // features: ['bg', 'road'], // 只显示必要的图层
    pitchEnable: false, // 禁用俯仰角调整（降低计算）
    rotateEnable: false, // 禁用旋转（降低计算）
    buildingAnimation: false, // 禁用建筑动画
    showIndoorMap: false, // 不显示室内地图
    showBuildingBlock: false, // 不显示建筑群
    showBuilding: false, // 显示单个建筑
    terrain: false, // 不显示地形
  });
  map.on("complete", function () {
    setTimeout(() => {
      mapLoading.value = false;
      // map.setViewMode('3D');
    }, 500);
  });
  handleDistrict();
  // 监听地图缩放
  map.on("zoomend", () => {
    let zoom = map.getZoom();
    if (zoom >= 7) {
      addPolylines();
      if (currentMarkers.length) {
        map.remove(currentMarkers);
        currentMarkers = [];
      }
    } else if (zoom < 7) {
      geojsonObj && map.remove(geojsonObj);
      geojsonObj = null;
      handleAddMarket();
      provincePolylines.forEach((provincePolyline) => {
        map.remove(provincePolyline);
      });
    }
  });
};
let bounds = [];
let mask = [];
const searchDistrict = () => {
  AMapLoader.load({
    key: "9a22433229a51dc5114d4bbf92f687ee", // 申请好的Web端开发者Key
    // version: "2.0",
    plugins: ["AMap.DistrictSearch", "AMap.GeoJSON"],
  }).then((AMap) => {
    let districtSearch = new AMap.DistrictSearch({
      subdistrict: 1, //获取边界不需要返回下级行政区
      extensions: "all", //返回行政区边界坐标组等具体信息
      level: "country", //查询行政级别为 市 province-省 district-
    });
    districtSearch.search("中国", function (status, result) {
      bounds = result.districtList[0].boundaries;
      for (let i = 0; i < bounds.length; i++) {
        mask.push([bounds[i]]);
      }
      handleInitMap();
      handleDistrict();
    });
  });
};
// 高亮和描边
const handleDistrict = () => {
  // 描边
  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);
    // const chinaBg = new AMap.Polygon({
    //     path: bounds[i],
    //     fillColor: "#026CB7",      // 背景色
    //     fillOpacity: 0.5,          // 透明度
    //     strokeColor: "#026CB7", // 浅蓝色边框
    //     strokeWeight: 1,
    //     strokeOpacity: 1,
    //     zIndex: 10,
    //     bubble: false
    // });
    // map.add(chinaBg);
  }
};
// 添加新路线
const addPolylines = () => {
  if (!geojsonObj) {
    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 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 字符串
        });

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

        // 鼠标双击
        polylineObj.on("dblclick", function (e) {});
        return polylineObj;
      },
    });
    map.add(geojsonObj);
  }
};
// 添加标记
const handleAddMarket = () => {
  // 清除之前的所有标记
  if (currentMarkers.length) {
    map.remove(currentMarkers);
    currentMarkers = [];
  }
  // 清除所有标记
  // if (map) {
  //   map.getAllOverlays("marker").forEach((marker) => {
  //     map.remove(marker);
  //   });
  // }

  // 根据不同状态定义标记数据
  const markerData = {
    jianshe: [
      // 安徽
      { number: 1, position: [117.27, 31.86], province: "安徽省" },
      // 广东
      { number: 1, position: [113.2644, 23.1291], province: "广东省" },
      // 陕西
      { number: 2, position: [108.948, 34.2632], province: "陕西省" },
      // 广西
      { number: 2, position: [108.32, 22.824], province: "广西壮族自治区" },
      // 山东
      { number: 2, position: [117.0009, 36.6758], province: "山东省" },
      // 河北
      { number: 1, position: [114.5025, 38.0455], province: "河北省" },
      // 甘肃
      { number: 1, position: [103.8236, 36.058], province: "甘肃省" },
    ],
    shiyunying: [
      // 四川
      { number: 1, position: [104.066, 30.5728], province: "四川省" },
      // 山东
      { number: 3, position: [117.0009, 36.6758], province: "山东省" },
      // 陕西
      { number: 3, position: [108.948, 34.2632], province: "陕西省" },
      // 广西
      { number: 1, position: [108.32, 22.824], province: "广西壮族自治区" },
      // 湖北
      { number: 1, position: [114.2986, 30.5844], province: "湖北省" },
    ],
    yunying: [
      { number: 1, position: [102.7123, 25.0406], province: "云南省" },
      // 湖北
      { number: 1, position: [114.2986, 30.5844], province: "湖北省" },
    ],
    tuichu: [
      // 河南
      { number: 3, position: [113.6654, 34.757], province: "河南省" },
    ],
    // 立项: [],
  };

  const positionsList = markerData[props.tabKey] || [];

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

  // 创建新的标记
  for (var i = 0; i < positionsList.length; i++) {
    const markerData = positionsList[i];

    // 创建悬浮窗口内容
    let infoContent = `
            <div class="infoWindow-title">${markerData.province}</div>
            <div class="infoWindow-content">
                <p>
                  <span class="infoWindow-content-title">路线数量:</span>
                  <span class="infoWindow-content-value">${markerData.number}<span class="infoWindow-unit">条</span></span>
                </p>
              </div>
            <div class="infoWindow-bottom"></div>
          `;

    // 创建信息窗口实例
    const infoWindow = new AMap.InfoWindow({
      isCustom: true,
      content: infoContent,
      offset: new AMap.Pixel(5, 0),
      closeWhenClickMap: true,
    });

    const marker = new AMap.Marker({
      map: map,
      position: markerData.position,
      offset: new AMap.Pixel(-12.5, -34),
      content:
        '<div class="custom-content-marker">' +
        '<img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png" style="width: 40px;height: 40px;">' +
        `<div class="anchorPoint">${markerData.number}</div>` +
        "</div>",
      zIndex: 100,
    });

    // 鼠标悬浮事件
    marker.on("mouseover", function (e) {
      infoWindow.open(map, markerData.position);
    });

    // 鼠标移出事件
    marker.on("mouseout", function () {
      // infoWindow.close();
    });

    // 点击事件：聚焦到对应省份并显示省份地图
    marker.on("click", function (e) {
      // map.remove(provincePolylines);
      provincePolylines.forEach((provincePolyline) => {
        map.remove(provincePolyline);
      });
      provincePolylines = [];
      const provinceName = markerData.province; // 例如：甘肃省
      emit("province-selected", true);

      // 创建省份搜索
      let districtSearch = new AMap.DistrictSearch({
        subdistrict: 0,
        extensions: "all",
        level: "province",
      });

      // 搜索并定位到省份
      districtSearch.search(provinceName, function (status, result) {
        if (status === "complete") {
          let bounds = result.districtList[0]?.boundaries;
          if (bounds && bounds.length > 0) {
            // 清除所有边界线（中国地图边界）
            // map.getAllOverlays("polyline").forEach((polyline) => {
            //   map.remove(polyline);
            // });

            // 清除所有标记点
            // map.getAllOverlays("marker").forEach((marker) => {
            //   map.remove(marker);
            // });

            // 清除所有覆盖物
            // map.getAllOverlays("polygon").forEach((polygon) => {
            //   map.remove(polygon);
            // });

            // 绘制省份边界线
            for (let i = 0; i < bounds.length; i++) {
              let provincePolyline = new AMap.Polyline({
                path: bounds[i],
                strokeColor: "#72A8FF",
                strokeWeight: 3,
                map: map,
              });
              map.add(provincePolyline);
              provincePolylines.push(provincePolyline);
            }

            // 绘制省份填充区域（可选）
            // let provincePolygon = new AMap.Polygon({
            //   path: bounds[0],
            //   strokeColor: "#72A8FF",
            //   strokeWeight: 2,
            //   fillColor: "rgba(114, 168, 255, 0.7)",
            //   fillOpacity: 0.3,
            // });
            // map.add(provincePolygon);

            // 重新添加新路线（确保新路线显示在地图上）
            // addPolylines();

            // 设置地图视图到该省份
            // map.setFitView([provincePolygon]);
            let center = result.districtList[0]?.center;
            map.setCenter([center.lng, center.lat]);
            map.setZoom(8);
          }
        }
      });
    });
    currentMarkers.push(marker);
  }
};
// 暴露更新标记的方法给父组件
const updateMarkers = (selectName) => {
  handleAddMarket(selectName);
};

// 重置地图到初始状态
const resetMap = () => {
  if (map) {
    // 清除所有边界线（包括省份边界线）
    map.getAllOverlays("polyline").forEach((polyline) => {
      map.remove(polyline);
    });

    // 清除所有标记点
    map.getAllOverlays("marker").forEach((marker) => {
      map.remove(marker);
    });

    // 清除所有覆盖物
    map.getAllOverlays("polygon").forEach((polygon) => {
      map.remove(polygon);
    });

    // 重新绘制全国边界
    handleDistrict();

    // 恢复当前阶段的标记点
    let selectName = sessionStorage.getItem("selectedContentBtn");
    handleAddMarket(selectName);

    // 设置地图视图
    map.setZoom(4);
    map.setCenter([100.808299, 35.791787]);
  }
};

// 返回全国地图视图
const backToCountry = () => {
  resetMap();
};

// 暴露方法给父组件
defineExpose({
  updateMarkers,
  resetMap,
  backToCountry,
});
onMounted(() => {
  searchDistrict();
  // 监听窗口大小变化
  // window.addEventListener("resize", handleResize);
});

// 处理窗口大小变化
const handleResize = () => {
  if (map) {
    map.resize();
  }
};

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener("resize", handleResize);
});

onActivated(() => {});
</script>

<style scoped lang="less">
.tourism {
  width: 100%;
  height: 100%;
}
#container {
  width: 100%;
  height: 100%;
  background-color: transparent !important;
}
.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: 260px;
  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: 260px;
  // height: 100x;
  padding-left: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
  p {
    height: 51px;
    line-height: 51px;
    display: flex;
    align-items: center;
    &:not(:last-child) {
      position: relative;
      &::after {
        content: "";
        height: 1px;
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        background: radial-gradient(
          rgba(255, 255, 255, 0) 0%,
          #3b71fa 50%,
          rgba(255, 255, 255, 0) 100%
        );
      }
    }
  }
}
: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: 16px;
  color: #fff;
  font-weight: 400;
  margin-right: 10px;
}
:deep(.infoWindow-content-value) {
  font-weight: 400;
  font-size: 20px;
  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(.marker-info-window) {
  background: #04427e;
  border: 1px solid #00ddeb;
  border-radius: 6px;
  padding: 8px 12px;
  box-shadow: 0 2px 8px rgba(0, 221, 235, 0.3);
  backdrop-filter: blur(4px);
  min-width: 120px;
}

:deep(.marker-info-title) {
  font-size: 14px;
  font-weight: 600;
  color: #fff;
  margin-bottom: 4px;
  border-bottom: 1px solid rgba(0, 221, 235, 0.3);
  padding-bottom: 2px;
}

:deep(.marker-info-content) {
  display: flex;
  align-items: center;
  gap: 4px;
}

:deep(.marker-info-label) {
  font-size: 12px;
  color: #93d2ff;
  font-weight: 400;
}

:deep(.marker-info-value) {
  font-size: 16px;
  font-weight: 600;
  color: #00ddeb;
}

:deep(.marker-info-unit) {
  font-size: 12px;
  color: #93d2ff;
  margin-left: 2px;
}
.amap-container {
  background: none;
}

:deep(.amap-logo) {
  display: none;
  opacity: 0 !important;
}
:deep(.amap-copyright) {
  opacity: 0;
}
</style>
<style lang="less">
.amap-info {
  z-index: 2;
  pointer-events: none;
}
</style>
