<template>
  <div ref="mapContainerRef" class="map-container">
    <template v-if="map">
      <slot></slot>
    </template>
  </div>
</template>
<script>
import TileLayer from 'ol/layer/Tile'
import Map from 'ol/Map'
import XYZ from 'ol/source/XYZ'
import View from 'ol/View'

export default {
  props: {
    token: {
      type: String,
      required: true
    },
    zoom: {
      type: Number,
      default: 3
    },
    maxZoom: {
      type: Number,
      default: 16
    },
    minZoom: {
      type: Number,
      default: 3
    },
    center: {
      type: Object,
      default() {
        return {
          longitude: 116,
          latitude: 40
        }
      }
    }
  },
  data() {
    return {
      map: null,
      stationList: []
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    // 初始化地图
    initMap() {
      const { longitude, latitude } = this.center
      const layers = [
        new TileLayer({
          source: new XYZ({
            url: `https://ibasemaps-api.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}?token=${this.token}`
          })
        })
      ]

      const view = new View({
        projection: 'EPSG:900913', // 使用这个坐标系
        center: [longitude, latitude],
        zoom: this.zoom,
        maxZoom: this.maxZoom,
        minZoom: this.minZoom
      })

      this.map = new Map({
        target: this.$refs.mapContainerRef,
        layers,
        view,
        controls: []
      })
    },

    /**
     * 以下是工具方法
     */
    // 获取地图缩放级别
    getZoom() {
      return this.map.getView().getZoom()
    },

    // 设置地图缩放级别
    setZoom(zoom) {
      if (zoom < this.minZoom) {
        zoom = this.minZoom
      }
      if (zoom > this.maxZoom) {
        zoom = this.maxZoom
      }
      this.map.getView().animate({ zoom })
    },

    getMapInstance() {
      return this.map
    },

    // 获取地图中心点
    getCenter() {
      return this.map.getView().getCenter()
    },

    // 平移到某个位置
    panTo(center, duration = 1000) {
      return this.map.getView().animate({
        center,
        duration
      })
    }
  }
}
</script>
<style lang="less" scoped>
.map-container {
  height: 100%;
  position: relative;
}
</style>
