<template>
  <BasicModal
    v-bind="$attrs"
    :title="title"
    @register="registerInnerModal"
    :width="1200"
    :footer="null"
  >
    <div id="container" class="map" style="height: 800px; border-radius: 5px" />
  </BasicModal>
</template>

<script setup lang="ts">
import { BasicModal, useModalInner } from "@/components/Modal";
import AMapLoader from "@amap/amap-jsapi-loader";
import { computed, ref, unref, reactive } from "vue";
import {
  faultMessageInfo,
  faultMessageAdd,
  faultMessageUpdate,
} from "@/api/statusCheck/fault";
import { modalSchemas } from "./faultMessage.data";
import { convertNumberToString } from "@/utils/tool";

defineOptions({ name: "FaultMessageModal" });
const map = ref(null);
const emit = defineEmits(["register", "reload"]);
const showFooter = ref<boolean>(true);
const isUpdate = ref<number>(1);
const title = computed<string>(() => {
  return "查看位置";
});
const mapData = reactive({
  map: {},
  keyword: "",
  selectedLocation: {},
  selectedAddress: "",
  marker: null, // 用于存储选中位置的标记
});
const [registerInnerModal, { modalLoading, closeModal }] = useModalInner(
  async (data: { record?: Recordable; update: number }) => {
    modalLoading(true);
    const { record, update } = data;
    isUpdate.value = update;
    await loadMap(record.lng, record.lat);
    modalLoading(false);
  }
);
const loadMap = (lng, lat) => {
  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: 14,
        center: [lng, lat], // 初始化地图中心点位置

        scrollWheel: true, // 启用滚动缩放
      });
      mapData.map = mapInstance;
      // 移除之前的标记
      if (mapData.marker) {
        mapData.marker.setMap(null);
      }

      // 创建新的标记
      const marker = new AMap.Marker({
        position: [lng, lat],
        icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png", // 选中位置的图标
        offset: new AMap.Pixel(-15, -30), // 调整图标的偏移位置
      });

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

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

      // 将地图中心设置为选中位置
      mapData.map.setCenter([lng, lat]);
      setTimeout(() => {
        mapData.map.setZoom(mapData.map.getZoom() + 3, true); // 放大地图
      }, 0); // 500 毫秒的延迟，根据需要调整延迟时间
    })
    .catch((e) => {
      console.log(e);
    });
};
function handleCancle() {
  closeModal();
}
async function handleSubmit() {
  try {
    modalLoading(true);
    // const data = await validate();
    if (isUpdate.value === 1) {
      await faultMessageUpdate(data);
    } else {
      await faultMessageAdd(data);
    }
    emit("reload");
    closeModal();
  } catch (e) {
    console.warn(e);
  } finally {
    modalLoading(false);
  }
}
</script>

<style scoped></style>
