<template>
  <div class="HomeMap">
    <div class="zoom-level" @click="soundAndMenu">
      <img :src="zoomLevelImage" alt="" />
    </div>
    <div id="map" ref="olMap" class="map-container"></div>
    <div class="pointingNorth" @click="mapNorth">
      <img src="@/assets/img/user.png" alt="" />
      <img src="@/assets/img/setup.png" alt="" />
      <img src="@/assets/img/query.png" alt="" />
    </div>
    <div class="configuration">
      <div class="refresh" @click="refreshClick">
        <img src="@/assets/img/refresh.png" alt="" />
      </div>
      <div class="refresh" @click="positionClick">
        <img src="@/assets/img/icon_postions.png" alt="" />
      </div>
      <div class="refresh" @click="modelClick">
        <img src="@/assets/img/icon_model.png" alt="" />
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import { fromLonLat } from "ol/proj";
import XYZ from "ol/source/XYZ";

import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import LineString from "ol/geom/LineString";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import Stroke from "ol/style/Stroke";
import Fill from "ol/style/Fill";
import Text from "ol/style/Text";
import CircleStyle from "ol/style/Circle";
import Static from "ol/source/ImageStatic.js";

import uaImg from "@/assets/img/icon_uav.png";

export default {
  name: "HomeMap",
  data() {
    return {
      map: null,
      zoomLevel: null,
      isZoomedIn: true,
      isZoomedOut: false,
      showPermissionPrompt: false
    };
  },
  created() {
    // 清空控制台（可选）
    // console.clear();
  },
  mounted() {
    this.initMap();
  },
  computed: {
    ...mapGetters(["statePage", "cityCode"]),
    zoomLevelImage() {
      return this.isZoomedIn
        ? require("@/assets/img/sound.png")
        : require("@/assets/img/mute.png");
    }
  },
  methods: {
    refreshClick() {
      // 刷新页面
      window.location.reload();
    },
    positionClick() {
      console.log("位置点击");
      this.$store.commit("SET_POSITIONPOINT", true);
    },
    modelClick() {
      // 切换底图
      const newBaseMap = this.currentBaseMap === "gaode" ? "tianditu" : "gaode";
      this.map.getLayers().forEach((layer) => {
        const name = layer.get("name");
        if (name === "gaode" || name === "tianditu") {
          layer.setVisible(name === newBaseMap);
        }
      });
      this.currentBaseMap = newBaseMap;
    },
    soundAndMenu() {
      this.isZoomedIn = !this.isZoomedIn;
      this.$store.commit("SET_ISZOOMEDIN", this.isZoomedIn);
      // const media = document.getElementById("uavAudio");
      // if (media) {
      //   media.muted = !this.isZoomedIn; // isZoomedIn为true时静音
      //   if (!this.isZoomedIn) {
      //     // 取消静音时尝试播放
      //     media.play().catch((error) => {
      //       console.log("播放失败，可能需要用户交互:", error);
      //     });
      //   }
      // }
    },
    initMap() {
      // 初始化 OpenLayers 地图
      this.map = new Map({
        target: this.$refs.olMap,
        layers: [
          new TileLayer({
            name: "gaode", // 图层名称
            visible: true,
            source: new XYZ({
              visible: true,
              url: "http://webrd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=2&scale=1&style=8"
            })
          }),
          new TileLayer({
            name: "tianditu",
            source: new XYZ({
              url: "https://{a-d}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png"
            }),
            visible: false
          })
        ],
        view: new View({
          projection: "EPSG:3857",
          center: fromLonLat([117.337103, 39.040924]), // 经纬度转投影坐标
          zoom: 10,
          minZoom: 3,
          maxZoom: 18,
          constrainRotation: false // 允许旋转
        })
      });

      // 保存地图实例到全局（与 Mars3D 的 window.marsMap 类似）
      window.olMap = this.map;

      // 处理地图加载完成后的逻辑
      this.onMapLoad(this.map);

      // 绑定点击事件
      this.map.on("click", this.mapClickHandler);

      // 绑定缩放/移动结束事件
      this.map.getView().on("change:resolution", this.mapZoomHandler);
      this.map.getView().on("change:center", this.mapZoomHandler);
    },
    mapClickHandler(event) {
      // 处理地图点击事件
      console.log("地图点击:", event);
    },
    mapZoomHandler() {
      // 获取当前缩放等级
      this.zoomLevel = Math.round(this.map.getView().getZoom());
    },
    onMapLoad(map) {
      // 地图加载完成后的处理
      const camera = window.mapConfig || {};
      if (camera.isCamera) {
        // 设置视角约束
        map
          .getView()
          .setCenter(
            fromLonLat([camera.cameraLon || 0, camera.cameraLat || 0])
          );
        map.getView().setMinZoom(3); // 最小缩放等级
        map.getView().setMaxZoom(18); // 最大缩放等级
      }
    },
    mapNorth() {
      // 指北：将地图旋转角度重置为 0
      const view = this.map.getView();
      const currentCenter = view.getCenter();
      const currentZoom = view.getZoom();
      view.animate({
        center: currentCenter,
        zoom: currentZoom < 3 ? 10 : currentZoom, // 确保最小缩放等级
        rotation: 0, // 指北
        duration: 500 // 动画持续时间
      });
    }
  }
};
</script>

<style scoped lang="scss">
.HomeMap {
  width: 100%;
  height: 100%;
  position: relative;

  .zoom-level {
    position: absolute;
    top: 60px;
    right: 40px;
    z-index: 1000;
    color: #fff;
    img {
      width: 48px;
      height: 48px;
    }
  }
  .configuration {
    position: absolute;
    bottom: 32px;
    right: 40px;
    z-index: 1000;
    color: #fff;
    width: 29px;
    height: 174px;
    background-color: rgba(209, 242, 255, 0.9);
    padding: 19px 8px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    .refresh {
      width: 32px;
      height: 32px;
      img {
        width: 32px;
        height: 32px;
      }
    }
  }

  .map-container {
    width: 100%;
    height: 100%;
  }

  .pointingNorth {
    width: 236px;
    height: 52px;
    position: absolute;
    bottom: 37px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    img {
      width: 52px;
      height: 52px;
    }
  }
}
</style>
