<template>
  <div class="map-box">
    <!-- <div style="margin-bottom: 8px">
      <a-input-search
        v-model:value="mapData.keyword"
        placeholder="请输入地点搜索"
        enter-button="搜索"
        size="large"
        @search="search"
      />
    </div> -->
    <div class="collapse-box">
      <Collapse
        v-model:activeKey="activeKey"
        :bordered="false"
        style="background: white; width: 400px"
      >
        <template #expandIcon="{ isActive }">
          <caret-right-outlined :rotate="isActive ? 90 : 0" />
        </template>
        <CollapsePanel key="1" :header="'地图信息配置'" :style="customStyle">
          <div>
            <BasicForm @register="registerForm" />
            <a-button style="width: 100%" type="primary" @click="handleSubmitRes"
              >查询</a-button
            >
          </div>
          <div>
            <BasicTable @register="registerTable">
              <template #toolbar> </template>
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'elevatorName'">
                  <div
                    @click="handleClickEva(record)"
                    style="text-decoration: underline; color: blue; cursor: pointer"
                  >
                    {{ record.elevatorName }}
                  </div>
                </template>
              </template>
            </BasicTable>
          </div>
        </CollapsePanel>
      </Collapse>
    </div>

    <div id="container" class="map" style="height: 100vh; border-radius: 5px" />
    <!-- <div>经度：{{ lng }}</div>
    <div>经度：{{ lat }}</div> -->
    <elevatorDetailModal @register="registerModal" @reload="reload"></elevatorDetailModal>
  </div>
</template>
<script setup>
import { SearchOutlined } from "@ant-design/icons-vue";
import { BasicForm, useForm } from "@/components/Form";
import { onMounted, reactive, ref, h, defineEmits, defineModel } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { CaretRightOutlined } from "@ant-design/icons-vue";
import { Collapse, CollapsePanel } from "ant-design-vue";
import { modalSchemas } from "./info.data";
import { infoList } from "@/api/basicInfo/elevator";
import { BasicTable, useTable, TableAction } from "@/components/Table";
import { columns } from "./info.data";
import { useModal } from "@/components/Modal";
import elevatorDetailModal from "./elevatorDetailModal.vue";
const activeKey = ref(["1"]);
const text = `A dog is a type of domesticated animal.Known for its loyalty and faithfulness,it can be found as a welcome guest in many households across the world.`;
const customStyle =
  "background: white;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden";
onMounted(() => {
  setTimeout(() => {
    handleSubmitRes();
  }, 200);
});
const map = ref(null);
const emit = defineEmits(["getLatLng"]);
const isUpdate = defineModel("isUpdate");
const mapData = reactive({
  map: {},
  keyword: "",
  selectedLocation: {},
  selectedAddress: "",
  marker: null, // 用于存储选中位置的标记
});
const lng = ref(0);
const lat = ref(0);

const handleSubmit = () => {
  emit("getLatLng", { lat: lat.value, lng: lng.value });
};
const [registerModal, { openModal }] = useModal();
const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
  labelWidth: 100,
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
  schemas: modalSchemas,
});
const [
  registerTable,
  { reload, multipleRemove, selected, getForm, setTableData, setPagination },
] = useTable({
  title: "",

  showIndexColumn: true,
  rowKey: "id",
  useSearchForm: false,
  columns: columns,
});
function handleClickEva(record) {
  console.log(record.lng, record.lat, "record");
  if (mapData.map.getZoom() > 11) {
    mapData.map.setZoom(mapData.map.getZoom() - 3, true); // 缩小地图
  }

  // console.log(mapData.map.getZoom(), "mapData.map.getZoom()");
  AMapLoader.load({
    key: "fbe22df4797c15ebb02de6ee7de73892",
    version: "2.0",
    plugins: ["AMap.PlaceSearch"],
  }).then((AMap) => {
    const placeSearch = new AMap.PlaceSearch({
      city: "全国", // 请根据实际情况设置城市
      map: mapData.map,
    });
    // 移除之前的标记
    // if (mapData.marker) {
    //   mapData.marker.setMap(null);
    // }
    const location = new AMap.LngLat(record.lng, record.lat);

    // 创建新的标记
    // const marker = new AMap.Marker({
    //   position: location,
    //   icon: "",
    //   offset: new AMap.Pixel(-15, -30),
    // });

    // 将标记添加到地图
    // marker.setMap(mapData.map);

    // 存储选中位置的标记
    // mapData.marker = marker;

    // 将地图中心设置为选中位置
    mapData.map.setCenter(location, 1000);
    // 延迟执行 zoomIn 方法，以确保 panTo 动画完成后再放大
    setTimeout(() => {
      mapData.map.setZoom(mapData.map.getZoom() + 3, true); // 放大地图
      // 延迟显示弹框，确保放大后弹框显示
      setTimeout(() => {
        const infoWindow = new AMap.InfoWindow({
          content: `<div style='width:200px;height:150px'><div><span style='font-weight:bolder'>电梯名称: </span><span>${record.elevatorName}</span></div><div><span style='font-weight:bolder'>电梯地址: </span><span>${record.elevatorAddress}</span></div><div><span style='font-weight:bolder'>报警名称: </span><span></span></div><div class='hover-class' id='details-link' style='text-decoration: underline; cursor: pointer;'>详情>>></div></div>`, // 弹框内容
          offset: new AMap.Pixel(0, -30), // 偏移量，确保弹框在标记上方
          width: 200,
        });

        // 在指定位置打开弹框
        infoWindow.open(mapData.map, location);
        // 监听点击事件
        document.addEventListener("click", (event) => {
          if (event.target && event.target.id === "details-link") {
            handleClickMap(record);
          }
        });
      }, 50); // 再次延迟500毫秒，确保放大动画完成后再显示弹框
    }, 0); // 500 毫秒的延迟，根据需要调整延迟时间
  });
}
function handleClickMap(record) {
  console.log(record.lng, record.lat, "record");
  openModal(true, { record, update: 3 });
}
async function handleSubmitRes() {
  try {
    const data = await validate();

    const res = await infoList({ ...data });
    console.log(res, "data");
    setTableData(res.rows);
    setPagination({ total: res.rows.length });
    loadMap(res.rows);
  } catch (e) {
    console.warn(e);
  } finally {
  }
}
const loadMap = (evaArr) => {
  window._AMapSecurityConfig = {
    securityJsCode: "f5abb0a2cae2075683e2e6d6f62dde18", // 密钥
  };

  AMapLoader.load({
    key: "fbe22df4797c15ebb02de6ee7de73892", // key值
    version: "2.0",
    plugins: ["AMap.PlaceSearch"],
  })
    .then((AMap) => {
      const mapInstance = new AMap.Map("container", {
        viewMode: "3D",
        zoom: 11,
        center: [114.266784, 30.513206], // 初始化地图中心点位置

        scrollWheel: true, // 启用滚动缩放
      });

      // 移除之前的标记
      if (mapData.marker) {
        mapData.marker.setMap(null);
      }
      const points = evaArr;
      console.log(points, "points");
      // 遍历点位数据并添加标记

      points.forEach((point) => {
        // 创建一个自定义图标的 HTML 元素
        const iconHtml = `
    <div style="position: relative;">
      <img src="https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png" style="width: 12px; height: 18px;">
      <div id='${point.id}' class='point-name' style="position: absolute; top:25px; left: -60px; width: 150px; height:20px;line-height:18px; background-color: white; border: 1px solid #000; text-align: center; color: #000; font-size:12px;z-index: 1;">
        ${point.elevatorName}
      </div>
    </div>
  `;
        const marker = new AMap.Marker({
          position: new AMap.LngLat(point.lng, point.lat),
          title: point.name, // 标记的标题

          offset: new AMap.Pixel(-15, -30),
          content: iconHtml, // 使用自定义的 HTML 作为图标
        });
        document.addEventListener("click", (event) => {
          if (event.target && event.target.className === "point-name") {
            console.log(event.target.id, "event.target");
            if (point.id === event.target.id) {
              handleClickPoint(point);
            }
          }
        });
        marker.setMap(mapInstance); // 将标记添加到地图上
        // 存储选中位置的标记

        mapData.marker = marker;
      });

      mapData.map = mapInstance;
    })
    .catch((e) => {
      console.log(e);
    });
};
function handleClickPoint(point) {
  const location = new AMap.LngLat(point.lng, point.lat);

  // 将地图中心设置为选中位置
  mapData.map.setCenter(location, 1000);
  // 延迟执行 zoomIn 方法，以确保 panTo 动画完成后再放大
  setTimeout(() => {
    mapData.map.setZoom(mapData.map.getZoom() + 3, true); // 放大地图
    // 延迟显示弹框，确保放大后弹框显示
    setTimeout(() => {
      const infoWindow = new AMap.InfoWindow({
        content: `<div style='width:200px;height:150px'><div><span style='font-weight:bolder'>电梯名称: </span><span>${point.elevatorName}</span></div><div><span style='font-weight:bolder'>电梯地址: </span><span>${point.elevatorAddress}</span></div><div><span style='font-weight:bolder'>报警名称: </span><span></span></div><div class='hover-class' id='details-link' style='text-decoration: underline; cursor: pointer;'>详情>>></div></div>`, // 弹框内容
        offset: new AMap.Pixel(0, -30), // 偏移量，确保弹框在标记上方
        width: 200,
      });

      // 在指定位置打开弹框
      infoWindow.open(mapData.map, location);
      // 监听点击事件
      document.addEventListener("click", (event) => {
        if (event.target && event.target.id === "details-link") {
          handleClickMap(point);
        }
      });
    }, 50); // 再次延迟500毫秒，确保放大动画完成后再显示弹框
  }, 0); // 500 毫秒的延迟，根据需要调整延迟时间
}
const search = () => {
  console.log(mapData.keyword);
  if (mapData.keyword) {
    AMapLoader.load({
      key: "fbe22df4797c15ebb02de6ee7de73892",
      version: "2.0",
      plugins: ["AMap.PlaceSearch"],
    })
      .then((AMap) => {
        const placeSearch = new AMap.PlaceSearch({
          city: "全国", // 请根据实际情况设置城市
          map: mapData.map,
        });
        placeSearch.search(mapData.keyword, (status, result) => {
          console.log(result); // 输出完整的搜索结果

          if (status === "complete") {
            const pois = result.poiList.pois;
            if (pois.length > 0) {
              const { location } = pois[0];

              // 移除之前的标记
              if (mapData.marker) {
                mapData.marker.setMap(null);
              }

              // 创建新的标记
              const marker = new AMap.Marker({
                position: location,
                icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
                offset: new AMap.Pixel(-15, -30),
              });

              // 将标记添加到地图
              marker.setMap(mapData.map);

              // 存储选中位置的标记
              mapData.marker = marker;

              // 将地图中心设置为选中位置
              mapData.map.setCenter(location);
            }
          } else {
            console.log("搜索失败或无结果");
          }
        });
      })
      .catch((e) => {
        console.log(e);
      });
  }
};

const zoomIn = () => {
  mapData.map.zoomIn();
};

const zoomOut = () => {
  mapData.map.zoomOut();
};
</script>
<style lang="less" scoped>
.search-btn {
  cursor: pointer;
}
.map {
  width: 100%;
}
.map-box {
  position: relative;
}
.collapse-box {
  position: absolute;
  top: 52px;
  right: 230px;
  width: 200px;
  height: 100%;
  z-index: 100;
}
.hover-class {
  &:hover {
    color: red;
  }
}
</style>
