<template>
  <div id="mapContainer" />
</template>

<script>
const {SMap, Plugins, GeoTask} = window
export default {
  name: 'MonitorMap',
  data() {
    return {
      map: null,
      identifytask: null,
    }
  },
  mounted() {
    this.$nextTick(this.initMap)
  },
  computed: {
    sizeRate() {
      return Math.floor(screen.height * 1.48 / 100 / 11)
    },
  },
  methods: {
    initMap() {
      new SMap.Network().setNet(this.$api.MAP_NET)
      this.map = new SMap.Map('mapContainer', {
        viewMode: '2D',
        // center: [0, 0],
        // zoom: 4,
        // zooms: [1, 12],
        mapStyle: 'smap://styles/dark',
        appKey: 'ACF69EDK17LON63GHPF081',
      }).on(SMap.MapEvent.maploaded, () => {
        // this.map.hideXQ_Poly()
        // this.map.hideXQ_Point()
        // this.map.hideMPZ()
        // this.addGridListener()
        this.identifytask = new GeoTask.Identify(this.map.view)
        this.addListener()
        this.$emit('complete')
      })
    },
    addListener() { // 触发地图点击事件
      this.map.on(SMap.MapEvent.click, (view, eventParamter) => {
        view.hitTest(eventParamter).then(res => {
          // const {x, y} = res.results[0].graphic.geometry.centroid
          // console.log([x, y])
          if (res.results && res.results.length > 0) {
            this.$emit('event', res.results[0].graphic.attributes)
          }
        })
        const param = {
          layerUniqueId: 'GridLayer',
          url: 'http://10.81.71.243:23456/hmfmstest/gisshare/C/rest/services/YPZRWG/MapServer',
          displayed: false, //查询接口是否在地图上显示
          tolerance: 5,
          geometry: eventParamter.mapPoint
        }
        this.identifytask.MapService(param).then(res => {
          if (res.results && res.results.length > 0) {
            this.$emit('grid', res.results[0].feature)
          }
        })
      })
    },
    // addGridListener() {
    //   // this.identifytask = new GeoTask.Identify(this.map.view)
    //   // this.identifytask.on(SMap.MapEvent.pointermove, (result, geometry) => {
    //   //   console.log('----', result, geometry)
    //   //   if (geometry) {
    //   //     this.map.view.popup.defaultPopupTemplateEnabled = true
    //   //     this.map.view.popup.autoOpenEnabled = false
    //   //     this.map.view.popup.open({
    //   //       location: geometry,
    //   //       title: result.attributes.name,
    //   //       content: createContentpopup(result.attributes),
    //   //     })
    //   //   }
    //   // })
    // },
    addGrid(name) {
      return SMap.load([
        'esri/Map',
        'esri/layers/FeatureLayer',
        'esri/renderers/SimpleRenderer',
        'esri/symbols/SimpleMarkerSymbol'
      ]).then(([, FeatureLayer]) => {
        const gridLayer = new FeatureLayer({
          url: 'http://10.81.71.243:23456/hmfmstest/gisshare/C/rest/services/YPZRWG/MapServer/0',
          renderer: {
            type: 'simple',
            symbol: {
              type: 'simple-fill',
              color: 'rgba(51,145,255,.3)',
              outline: {
                // color: [128, 128, 128, 0.5],
                color: [255, 235, 59, 1],
                width: 2
              }
            }
          },
          definitionExpression: `所属街 = '${name}'`,
          id: 'ThisIsGridID'
        })
        this.map.view.map.add(gridLayer)
        return gridLayer
      })
    },
    removeGrid() {
      this.map.removeLayer('ThisIsGridID')
    },
    // 添加点
    addPoint({key, data, labelKey = null, icon = 'test.png', size = 14, color}) {
      if (!this.map) return
      const points = this.getMapPoints({data, key, labelKey, icon, size, color})
      this.map.add(points)
      return points
      // const overlayGroup = new SMap.OverlayGroup(points)
      // this.map.add(overlayGroup)
      // return overlayGroup
    },

    // 删除图层 点或线等
    remove(layer) {
      if (!layer) return
      this.map.remove(layer)
    },
    // 将数据转换为符合地图的点数组
    getMapPoints({data = [], key, labelKey, icon, size, color = '#47B3FF'}) {
      return data.map(item => {
        const result = {
          icon: new SMap.Icon({
            size: Array.isArray(size) ? new SMap.Size(size[0], size[1]) : new SMap.Size(size, size),
            image: require(`@/assets/images/${item.icon || icon}`),
          }),
          attributes: {key, ...item},
          position: [item.communityMinx || item.X || item.x || item.gpsx, item.communityMiny || item.Y || item.y || item.gpsy, 0],
        }
        if (labelKey) {
          result.label = new SMap.Label({
            text: (item[labelKey] || item[key]) + '',
            size,
            color,
          })
        }
        return new SMap.Marker(result)
      })
    },

    /**
     * ------  聚焦点位 -------
     * @param {String} x [必填 - x坐标]
     * @param {String} y [必填 - y坐标]
     * @param {Number} zoom [可选 - 放大比例（默认为6）]
     */
    focus(x, y, zoom = 6) {
      if (!this.map || !x || !y ) {
        console.error('传入的坐标点不能为空')
        return
      }
      this.map.setZoomAndCenter(zoom, [x, y])
    },

    /**
     * ------  放大 -------
     */
    zoomIn() {
      this.map.zoomIn()
    },

    /**
     * ------  缩小 -------
     */
    zoomOut() {
      this.map.zoomOut()
    },
    // 添加面
    addPolygon({paths, fillColor = 'rgba(255,255,255,1)', strokeColor = 'transparent', attributes = {}, style = 'solid', strokeWeight = 1, label = null}) {
      const polygon = new SMap.Polygon({
        paths: paths.map(item => new SMap.LngLat(item[0], item[1])),
        attributes,
        fillColor,
        style,
        strokeColor,
        strokeStyle: style,
        strokeWeight,
        label,
      })
      this.map.add(polygon)
      return polygon
    },
    // 添加线状覆盖物
    addPolyLine({paths, attributes = {}, strokeColor = 'rgba(51,145,255,.6)', width = 2}) {
      const polyline = new SMap.Polyline({
        path: paths.map(item => new SMap.LngLat(item[0], item[1])),
        attributes,
        cap: 'square',
        strokeColor,
        style: 'solid',
        lineJoin: 'round',
        width,
      })
      this.map.add(polyline)
      return polyline
    },
    // 添加边界
    addBoundary({name, weight = 10, count = 10, color = 'rgba(51,145,255,.6)', maskColor = [0, 0, 0, 0]}) {
      const boundary = {
        boundaryType: 'jd_boundary',
        boundaryDefinition: `name like '%${name}%'`,
        boundarydistance: weight,
        bounarycount: count,
        boundaryColor: color,
        maskColor: maskColor,
      }
      const Boundary = new Plugins.MaskBoundary(this.map.view)
      Boundary.add(boundary)
    },
  },
}
</script>

<style lang="stylus">
  .esri-component.esri-attribution.esri-widget
    display none !important
</style>
<style lang="stylus" scoped>
#mapContainer
  width 100%
  height 100vh
  background-color #001021
  position fixed
  top 0
  left 0
  right 0
  bottom 0
</style>
