<template>
  <div ref="windowInfo" :class="className">
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "AInfoWindow",
  inject: ["map"],
  props: {
    // see complete options documentation https://lbs.amap.com/api/javascript-api-v2/documentation#infowindow
    infoWindowOptions: {
      type: Object,
    },
    className: {
      type: [String, Array],
    },
  },
  data() {
    return {
      infoWindow: null,
    };
  },
  watch: {
    infoWindowOptions: {
      handler(value) {
        if (value) {
          const { position, offset } = value;
          if (position) {
            if (this.infoWindow) {
              this.infoWindow.setOffset(offset);
              this.infoWindow.open(this.map.map, position);
            } else {
              this.init();
              this.infoWindow.open(this.map.map, position);
            }
          } else {
            this.infoWindow.close();
          }
        }
      },
      deep: true,
      immediate: false,
    },
  },
  methods: {
    init() {
      this.infoWindow = new this.map.AMap.InfoWindow({
        content: this.$refs.windowInfo,
        ...this.infoWindowOptions,
      });
      this.infoWindow.on("open", () => {
        this.$emit("open");
      });
      this.infoWindow.on("close", () => {
        this.$emit("close");
      });
      // 鼠标移入弹框移除地图滚轮监听，避免两者滚轮事件冲突；移除弹框后恢复。
      this.infoWindow.on("mouseover", () => {
        this.map.map.setStatus({ scrollWheel: false });
      });
      this.infoWindow.on("mouseout", () => {
        this.map.map.setStatus({ scrollWheel: true });
      });
      this.infoWindow.on("click", () => {
        this.$emit("click");
      });
      // console.log(this.infoWindow);
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style scoped></style>
