<template>
  <div class="Vbox">
    <div class="container">
      <div class="center">
        <div ref="mapContainer" class="allmap"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watchEffect } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import request from "@/utils/request.js";

// 1. 常量集中管理
const MAP_CONFIG = {
  center: new BMapGL.Point(112.863449, 28.178476),
  zoom: 19,
  minZoom: 15,
  maxZoom: 22,
  styleId: "62ce43ad2a1362c23e612b783d7406e7",
  tilt: 50,
};

const ICON_MAP = {
  0: new URL("@/assets/visualizationimg/all.png", import.meta.url).href,
  1: new URL("@/assets/visualizationimg/FZ.png", import.meta.url).href,
};

// 2. 组件状态管理
const mapContainer = ref(null);
const mapInstance = ref(null);
const markers = ref([]);
const searchParams = ref({
  deviceName: "",
  currentPage: 1,
  pageSize: 10,
});

// 3. 地图生命周期管理
onMounted(initializeMap);
onUnmounted(cleanupMap);

async function initializeMap() {
  try {
    mapInstance.value = new BMapGL.Map(mapContainer.value);
    setupMapConfig(mapInstance.value);
    await fetchDeviceData();
  } catch (error) {
    console.error("地图初始化失败:", error);
    ElMessage.error("地图加载失败");
  }
}

function setupMapConfig(map) {
  map.centerAndZoom(MAP_CONFIG.center, MAP_CONFIG.zoom);
  map.enableScrollWheelZoom(true);
  map.setMinZoom(MAP_CONFIG.minZoom);
  map.setMaxZoom(MAP_CONFIG.maxZoom);
  map.setMapStyleV2({ styleId: MAP_CONFIG.styleId });
  map.setTilt(MAP_CONFIG.tilt);
  map.disableInertialDragging();
}

function cleanupMap() {
  if (mapInstance.value) {
    mapInstance.value.destroy();
    markers.value.forEach((marker) => mapInstance.value.removeOverlay(marker));
  }
}

// 4. 数据监听自动更新
watchEffect(() => {
  fetchDeviceData();
});

// 5. 拆分数据获取逻辑
async function fetchDeviceData() {
  try {
    const params = buildRequestParams();
    const res = await request.get("/base/devices/findByPage", { params });

    if (res.code !== 200) throw new Error(res.msg);

    clearMarkers();
    createMarkers(res.data.records);
  } catch (error) {
    handleDataError(error);
  }
}

function buildRequestParams() {
  const conditions = [
    {
      column: "type",
      type: "eq",
      value: "1",
    },
  ];

  if (searchParams.value.deviceName) {
    conditions.push({
      column: "device_name",
      type: "like",
      value: searchParams.value.deviceName,
    });
  }

  return {
    conditionJson: encodeURIComponent(JSON.stringify(conditions)),
    pageNum: searchParams.value.currentPage,
    pageSize: searchParams.value.pageSize,
  };
}

// 6. 标记管理优化
function createMarkers(points) {
  markers.value = points.map((pointData) => {
    const [lng, lat] = parseLocation(pointData.location);
    const marker = createMarker(lng, lat, pointData);
    addMarkerEvents(marker, pointData);
    return marker;
  });
}

function parseLocation(location) {
  const [lng, lat] = location.split("-").map(Number);
  if (isNaN(lng) || isNaN(lat)) {
    console.warn("Invalid location format:", location);
    return [MAP_CONFIG.center.lng, MAP_CONFIG.center.lat];
  }
  return [lng, lat];
}

function createMarker(lng, lat, pointData) {
  const point = new BMapGL.Point(lng, lat);
  const icon = createCustomIcon(pointData.alarmStatus);
  const marker = new BMapGL.Marker(point, { icon });
  mapInstance.value.addOverlay(marker);
  return marker;
}

function createCustomIcon(status) {
  return new BMapGL.Icon(ICON_MAP[status] || ICON_MAP["0"], new BMapGL.Size(23, 25), {
    anchor: new BMapGL.Size(10, 25),
  });
}

function addMarkerEvents(marker, pointData) {
  marker.addEventListener("click", async (e) => {
    const infoContent = await fetchDeviceInfo(pointData.id);
    showInfoWindow(e.target.getPosition(), infoContent);
  });
}

// 7. 信息窗口 管理
async function fetchDeviceInfo(deviceId) {
  try {
    const loading = ElLoading.service({ text: "正在获取设备信息..." });
    const res = await request.get(
      `/base/devices/getById/${encodeURIComponent(deviceId)}`
    );
    loading.close();

    if (res.code !== 200) throw new Error(res.msg);
    return generateInfoContent(res.data);
  } catch (error) {
    ElMessage.error(error.message || "设备信息获取失败");
    return null;
  }
}

function generateInfoContent(deviceData) {
  return `
    <div class="device-info">
      <p>设备名称：${escapeHtml(deviceData.deviceName)}</p>
      <p>设备编号：${escapeHtml(deviceData.deviceNumber)}</p>
      <p>设备型号：${escapeHtml(deviceData.model)}</p>
      <p>设备类型：${escapeHtml(deviceData.type)}</p>
      <p>位置信息：${escapeHtml(deviceData.location)}</p>
      <p>备注信息：${escapeHtml(deviceData.remarks)}</p>
    </div>
  `;
}

function showInfoWindow(position, content) {
  if (!content) return;

  mapInstance.value.closeInfoWindow();
  const infoWindow = new BMapGL.InfoWindow(content, {
    width: 300,
    title: "设备详细信息",
  });
  mapInstance.value.openInfoWindow(infoWindow, position);
}

// 8. 工具函数
function escapeHtml(unsafe) {
  return (
    unsafe
      ?.toString()
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#039;") || ""
  );
}

function clearMarkers() {
  markers.value.forEach((marker) => mapInstance.value.removeOverlay(marker));
  markers.value = [];
}

function handleDataError(error) {
  console.error("数据获取失败:", error);
  ElMessage.error(error.message || "设备数据获取失败");
}
</script>

<style lang="scss">
.BMap_bubble_pop {
  border: 0px !important;
  border-radius: 0 !important;
  background-image: url("../../../../assets/visualizationimg/eject.png");
  background-size: 100% 100%;
  background-color: rgba(0, 0, 0, 0) !important;
  padding: 0 20px !important;

  .BMap_bubble_top {
    margin-top: 30px !important;

    .BMap_bubble_title {
      color: white !important;
      font-size: 20px;
    }

    .BMap_bubble_buttons {
      top: 10px !important;
    }
  }

  .BMap_bubble_center {
    margin-bottom: 10px !important;

    .BMap_bubble_content {
      color: white !important;
    }
  }

  img {
    display: none !important;
  }
}
</style>

<style lang="scss">
.Vbox {
  height: 100vh;
  overflow: hidden;

  .container {
    height: 100%;
    position: relative;

    .boxBottom {
      position: absolute;
      z-index: 999;
      // bottom: 0;
      width: 45vw;
      left: 20vw;
      display: flex;
      align-items: center;
      justify-content: center;

      .Vgradation {
        display: flex;

        .tab {
          width: 150px;
          height: 60px;
          margin: 0 10px;
          text-align: center;
          line-height: 60px;
          color: white;
          font-weight: 500;
          font-size: 0.9vw;
          background-image: url("../../../../assets/visualizationimg/headg.png");
          background-size: 100% 100%;
        }

        .active {
          background-image: url("../../../../assets/visualizationimg/headgactive.png");
          background-size: 100% 100%;
        }
      }
    }

    .center {
      float: left;
      height: 100%;
      width: 100%;
      background-color: green;

      .allmap {
        /* // 注意给dom宽高，不然地图不出来 */
        width: 100vw;
        height: 100%;
        margin: auto;
        padding: 0;
      }
    }
  }
}
</style>
