<template>
  <div id="container">
    <div class="checkbox" style="z-index: 999999">
      <div class="checkboxItem">
        <a-checkbox
          style="margin-right: 10px"
          v-model:checked="state.checkAll"
          :indeterminate="state.indeterminate"
          @change="onCheckAllChange"
        >
          全部
        </a-checkbox>
        <a-checkbox-group
          v-model:value="state.checkedList"
          :options="plainOptions"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="tsx">
import { onMounted, onUnmounted, reactive, ref, watch } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import IconAssets from "@/assets/images/point.png";
let maps: any = null;
let loadedAMap: any;
let cluster: any = null;
let deviceInfoWindow = ref<any>();
const wristbandIcon = ref<any>();

const plainOptions = [
  "保安",
  "警察",
  "移动设备",
  "手持设备",
  "AI设备",
  "固定设备",
];
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkedList: plainOptions,
});

var points = [
  {
    weight: 8,
    lnglat: ["116.506647", "39.795337"],
    name: "北京",
    id: 0,
    age: 15,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.843352", "40.377362"],
    name: "上海",
    id: 1,
    age: 18,
    phone: "13575452134",
    address: "长沙市开福区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.637122", "40.324272"],
    name: "成都",
    id: 2,
    age: 25,
    phone: "13575452134",
    address: "长沙市雨花区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.105381", "39.937183"],
    name: "天津",
    id: 3,
    age: 45,
    phone: "13575452134",
    address: "衡阳市石鼓区",
    units: "衡阳市石鼓区牛逼有限公司",
  },
  {
    weight: 1,
    lnglat: ["116.653525", "40.128936"],
    name: "南京",
    id: 4,
    age: 45,
    phone: "13575452134",
    address: "岳阳市镜湖区",
  },
  {
    weight: 1,
    lnglat: ["116.486409", "39.921489"],
    name: "长沙",
    id: 5,
    age: 65,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.658603", "39.902486"],
    name: "衡阳",
    id: 6,
    age: 55,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.338033", "39.728908"],
    name: "北京1",
    id: 7,
    age: 35,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.235906", "40.218085"],
    name: "北京2",
    id: 8,
    age: 65,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.366794", "39.915309"],
    name: "北京3",
    id: 9,
    age: 12,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.418757", "39.917544"],
    name: "北京4",
    id: 10,
    age: 12,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.139157", "39.735535"],
    name: "北京5",
    id: 11,
    age: 12,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.195445", "39.914601"],
    name: "北京6",
    id: 12,
    age: 12,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.310316", "39.956074"],
    name: "北京7",
    id: 13,
    age: 12,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
  {
    weight: 1,
    lnglat: ["116.286968", "39.863642"],
    name: "北京8",
    id: 14,
    age: 12,
    phone: "13575452134",
    address: "长沙市岳麓区麓谷街道芜湖",
  },
];

const count = points.length;
window._AMapSecurityConfig = {
  securityJsCode: "35be6bbf6cd521a1f17a9e455e52ffe9",
};
const initMap = () => {
  AMapLoader.load({
    key: "b886c3f67152803e081f0b0f5594a55e",
    version: "2.0",
    plugins: ["AMap.MarkerCluster"],
  }).then((AMap) => {
    loadedAMap = AMap;
    maps = new AMap.Map("container", {
      // 设置地图容器id
      resizeEnable: true,
      viewMode: "3D", // 是否为3D地图模式
      zoom: 10, // 初始化地图级别
      center: [116.407387, 39.904179], // 初始化地图中心点位置
    });
    wristbandIcon.value = new AMap.Icon({
      image: IconAssets, //Icon 的图像
      imageOffset: new AMap.Pixel(-9, -3), //图像相对展示区域的偏移量，适于雪碧图等
      imageSize: new AMap.Size(40, 40), //根据所设置的大小拉伸或压缩图片
    });
    createCluster();
    mapZoom();
    console.log(1111);
    maps.on("zoomend", function () {
      clearMarkers();
      let zoom = maps.getZoom();
      if (zoom > 10) {
        addNewMarkers();
        cluster?.setMap(null); // 清除聚合点，避免默认聚合样式覆盖
      } else {
        createCluster(); // 缩小时重新创建点聚合
        mapZoom();
      }
    });
  });
};

const addNewMarkers = () => {
  points.forEach((item: any) => {
    const marker = new loadedAMap.Marker({
      position: item.lnglat,
      icon: new loadedAMap.Icon({
        image: IconAssets,
        size: new loadedAMap.Size(40, 46.5),
        imageSize: new loadedAMap.Size(30, 30),
      }),
    });
    marker.on("click", function () {
      deviceInfoWindow.value = new loadedAMap.InfoWindow({
        isCustom: true,
        content: content.value,
        offset: new loadedAMap.Pixel(5, -13),
      });
      deviceInfoWindow.value.open(maps, item.lnglat);
    });
    contents(item);
    maps.add(marker);
  });
};

const content = ref();
const contents = (item: any) => {
  content.value = `<div class="comments" style="width: 300px;">
                <ul class="commentUl" style="list-style: none">
                   <li><h2 style="color: skyblue">${item.name}</h2></li>
                   <li>年龄：<span>${item.age}</span></li>
                   <li>电话：<span>${item.phone}</span></li>
                   <li>地址：<span>${item.address}</span></li>
                </ul>
                 </div>`;
};
const mapZoom = () => {
  cluster.on("click", (e: any) => {
    const { clusterData, lnglat } = e;
    let currentZoom = maps.getZoom();
    // 若当前缩放层级 <= 12，点击聚合点时放大到更高层级以展开
    if (currentZoom < 10) {
      maps.setZoomAndCenter(currentZoom + 1, lnglat); // 放大2级，聚焦到点击位置
    }
    clearMarkers(); // 先清除地图上已有的 Marker，保留点聚合
    let markers: any[] = [];
    clusterData.forEach((item: any) => {
      const marker = new loadedAMap.Marker({
        position: item.lnglat,
        offset: new loadedAMap.Pixel(-15, -15),
        icon: new loadedAMap.Icon({
          image: IconAssets,
          size: new loadedAMap.Size(40, 46.5),
          imageSize: new loadedAMap.Size(30, 30),
        }),
      });
      marker.on("click", function () {
        deviceInfoWindow.value = new loadedAMap.InfoWindow({
          isCustom: true,
          content: content.value,
          offset: new loadedAMap.Pixel(5, -13),
        });
        deviceInfoWindow.value.open(maps, item.lnglat);
      });
      markers.push(marker);
      maps.add(marker);
    });
    // 自动调整视角，保证所有 Marker 可见
    maps.setFitView(markers);
  });
};

const createCluster = () => {
  if (cluster) cluster.setMap(null); // 避免重复创建
  // @ts-ignore
  cluster = new loadedAMap.MarkerCluster(maps, points, {
    gridSize: 80,
    maxZoom: 12,
    renderClusterMarker: _renderClusterMarker,
  });
};
// 清除 Marker 函数（避免重复）
function clearMarkers() {
  const overlays = maps.getAllOverlays("marker");
  overlays.forEach((marker: any) => {
    if (!marker.isCluster) {
      maps.remove(marker); // 仅移除非聚合 Marker
    }
  });
}

const _renderClusterMarker = function (context: any) {
  var factor = Math.pow(context.count / count, 1 / 18);
  var div = document.createElement("div");
  var Hue = 180 - factor * 180;
  var bgColor = "hsla(" + Hue + ",100%,40%,0.7)";
  var fontColor = "hsla(" + Hue + ",100%,90%,1)";
  var borderColor = "hsla(" + Hue + ",100%,40%,1)";
  var shadowColor = "hsla(" + Hue + ",100%,90%,1)";
  div.style.backgroundColor = bgColor;
  var size = Math.round(30 + Math.pow(context.count / count, 1 / 5) * 20);
  div.style.width = div.style.height = size + "px";
  div.style.border = "solid 1px " + borderColor;
  div.style.borderRadius = size / 2 + "px";
  div.style.boxShadow = "0 0 5px " + shadowColor;
  div.innerHTML = context.count;
  div.style.lineHeight = size + "px";
  div.style.color = fontColor;
  div.style.fontSize = "14px";
  div.style.textAlign = "center";
  context.marker.setOffset(new loadedAMap.Pixel(-size / 2, -size / 2));
  context.marker.setContent(div);
};
// const _renderMarker = (context: any) => {
//   const content =
//     '<div style="background-color: hsla(180, 100%, 50%, 0.3); height: 18px; width: 18px; border: 1px solid hsl(180, 100%, 40%); border-radius: 12px; box-shadow: hsl(180, 100%, 50%) 0px 0px 3px;"></div>';
//   const offset = new loadedAMap.Pixel(-9, -9);
//   context.marker.setContent(content);
//   context.marker.setOffset(offset);
//   context.on("click", () => {
//     console.log(121);
//   });
// };

const onCheckAllChange = (e: any) => {
  console.log(e);
  Object.assign(state, {
    checkedList: e.target.checked ? plainOptions : [],
    indeterminate: true,
  });
};
watch(
  () => state.checkedList,
  (val) => {
    console.log(val);
    if (val[0] !== plainOptions[0]) {
      clearMarkers();
    } else {
      addNewMarkers();
    }
    state.indeterminate = !!val.length && val.length < plainOptions.length;
    state.checkAll = val.length === plainOptions.length;
  }
);
onMounted(() => {
  initMap();
});
onUnmounted(() => {
  maps?.destroy();
});
</script>

<style scoped lang="scss">
#container {
  width: 100vw;
  height: 100vh;
  position: relative;
  .comments {
    width: 300px !important;
    box-shadow: 0 4px 8px #0003;
  }
  .checkbox {
    width: 100vw;
    height: 50px;
    background-color: #ffffffb3;
    box-sizing: border-box;
    position: absolute;
    top: 0;
    //left: 40%;
    .checkboxItem {
      text-align: center;
      line-height: 50px;
    }
  }
}
</style>
