<template>
  <div class="map-container">
    <nav>
      <map-selector :default-val="formData.mapId" @setMapInfo="handleSelectMap" />
    </nav>
    <div class="layout-map">
      <div id="vmap" class="layout-map" />
      <div id="marker-tip" :style="marker_tip_style">
        <div class="head">基本信息</div>
        <div class="item">
          <p class="title">巡检任务统计(20)</p>
          <p><span>未完成：8</span><span>已完成：8</span></p>
        </div>
        <div class="item">
          <p class="title">传感器统计(21)</p>
          <p><span>在线：8</span><span>离线：8</span></p>
          <p><span class="warn">预警：8</span></p>
        </div>
      </div>
    </div>
    <MapLayerDetail ref="layer-detail" />
  </div>
</template>

<script>
import * as L from 'leaflet'
import '@geoman-io/leaflet-geoman-free'
import MapSelector from '@/components/MapSelector'
import MapLayerDetail from './components/table'

import { getMapLayerById } from '@/api/goaf/layer'
import { getMapLayer, getNewSensorData } from '@/api/iiot/map'

const iconSize = [50, 50]
export default {
  name: 'GoafVisualEditor',
  components: {
    MapSelector,
    MapLayerDetail
  },
  data() {
    return {
      viewData: {},
      formData: {
        mapId: undefined,
        layerId: undefined,
        layerVector: ''
      },
      map: undefined,
      geoLayer: undefined,
      conditions: {
        layerId: undefined
      },
      layer: {
        containerPoint: {
          x: '',
          y: ''
        }
      },
      marker_tip_style: '',
      layers: [],
      layerGroup: [],
      mapList: [],
      imageOverlay: undefined
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.initMap()
    },
    // 初始化
    getData() {
      getMapLayerById(this.conditions.layerId).then((resp) => {
        const { data } = resp
        this.viewData = data
        this.setRasterLayer()
      })
    },

    // 初始化地图
    initMap() {
      var yx = L.latLng
      var xy = function xy(x, y) {
        if (L.Util.isArray(x)) {
          return yx(x[1], x[0])
        }
        return yx(y, x)
      }
      var bounds = [xy(-600, -600), xy(300, 300)]
      this.map = L.map('vmap', {
        crs: L.CRS.Simple, // 一个简单的CRS，可将经度和纬度直接映射到x其中y。可用于平面地图（例如游戏地图）
        minZoom: 0,
        maxZoom: 1,
        zoom: 1,
        maxBounds: bounds, // 地图拖动到边界后自动弹回
        maxBoundsViscosity: 0.2,
        attributionControl: true,
        zoomControl: true // zoomControl（缩放控制）：确定缩放控制是否默认加载在地图上。
      })
      this.layerGroup = L.layerGroup().addTo(this.map)
      this.geoLayer = L.geoJson(null, { pmIgnore: false })
      this.geoLayer.addTo(this.map)
      if (!this.viewData.layerVector) return
      this.geoLayer.addData(this.viewData.layerVector)
    },

    // 设置地图背景图
    setRasterLayer() {
      var yx = L.latLng
      var xy = function xy(x, y) {
        if (L.Util.isArray(x)) {
          return yx(x[1], x[0])
        }
        return yx(y, x)
      }
      var bounds = [xy(-600, -600), xy(300, 300)]
      if (this.imageOverlay) {
        this.imageOverlay.setUrl(this.viewData.mapRasterLayer)
      } else {
        this.imageOverlay = L.imageOverlay(this.viewData.mapRasterLayer, bounds).addTo(this.map)
      }

      this.map.fitBounds(bounds)
      this.map.scrollWheelZoom.disable()
      this.getMapLayers()
    },

    // 选择地图
    handleSelectMap(obj, mapList) {
      this.viewData.mapRasterLayer = obj.mapRasterLayer
      this.viewData.mapId = obj.mapId
      this.formData.mapId = obj.mapId
      if (mapList) {
        this.mapList = mapList
      }
      this.setRasterLayer()
      this.clearLayers()
    },
    formSuccess() {
      this.$emit('formSuccess')
    },
    // 获取地图图层数据
    getMapLayers() {
      getMapLayer({
        map: this.formData.mapId
      }).then((resp) => {
        const { code, data, msg } = resp
        if (code === 0) {
          this.mapLayerList = data
          this.initMapLayers()
        } else {
          this.$message.error(msg)
        }
      })
    },
    updateMapLayers(mapId, type = 1) {
      if (type === 1) {
        this.setRasterLayer()
        this.clearLayers()
      } else {
        /** 其他图层改变需要跳转 */
        if (this.formData.mapId === mapId) {
          this.setRasterLayer()
          this.clearLayers()
        } else {
          const obj = this.mapList.filter(item => item.mapId === mapId)[0]
          this.viewData.mapRasterLayer = obj.mapRasterLayer
          this.viewData.mapId = obj.mapId
          this.formData.mapId = obj.mapId
          this.setRasterLayer()
          this.clearLayers()
        }
      }
    },
    // 初始化地图图层
    initMapLayers() {
      const layerList = this.mapLayerList
      const feature = []
      const self = this
      if (layerList != null && layerList.length > 0) {
        layerList.forEach((item) => {
          feature.push({
            'type': 'Feature',
            'properties': item,
            'geometry': {
              'type': 'Point',
              'coordinates': [item.sensorQywzjd, item.sensorQywzwd]
            }
          })
        })
        L.geoJSON(feature, {
          pointToLayer: function(_feature, latlng) {
            const sensorLocationId = _feature.properties.sensorLocationId
            const goafSensorName = _feature.properties.goafSensorName
            const html = `<div data-layer="${sensorLocationId}-${goafSensorName}" class="goaf-icon-box" style="width:100%;height:100%;position: relative;"></div>`
            var icon = L.divIcon({
              html,
              iconSize
            })
            return L.marker(latlng, { icon })
          },
          onEachFeature: (_feature, layer) => {
            this.layerGroup.addLayer(layer)
            layer.on('click', (ev) => {
              self.showLayerDetail(ev.target.feature.properties)
            })
          }
        }).addTo(this.layerGroup)
      }
    },
    clearLayers() {
      if (this.layerGroup && this.layerGroup.clearLayers) {
        this.layerGroup.clearLayers()
      }
    },
    createGeoJson() {
      var layerArray = []
      this.map.eachLayer(function(layer) {
        if (layer.pm !== 'undefined' && layer.pm != null && layer.pm !== '') {
          if (layer.pm._enabled === false && layer.pm.options.draggable === true) {
            layerArray.push(layer)
          }
        }
      })
      var geojson = L.layerGroup(layerArray).toGeoJSON()
      for (var n = 0; n < geojson.features.length; n++) {
        var nowJson = JSON.stringify(geojson.features[n])
        for (var m = n + 1; m < geojson.features.length; m++) {
          var nextJson = JSON.stringify(geojson.features[m])
          if (nowJson === nextJson) {
            geojson.features.splice(n, 1)
          }
        }
      }
      return geojson
    },
    showLayerDetail(item) {
      getNewSensorData({
        map: item.mapId
      }).then((resp) => {
        const { data } = resp
        this.$refs['layer-detail'].loadData(data)
      })
    },
    updateLayerState(layerId = 0, type = 1) {
      // eslint-disable-next-line no-undef
      var marker = $(`.goaf-icon-box[data-layer='${layerId}']`)
      if (type === 1) {
        // 添加隐患预警
        marker.addClass('ico-warning ')
      } else if (type === 3) {
        // 修改矿坑体积
      } else {
        marker.removeClass('ico-warning ')
      }
    },
    unique(arr = [], name = 'name') {
      const res = new Map()
      return arr.filter((item) => !res.has(item[name]) && res.set(item[name], 1))
    },
    deeepClone(params) {
      return JSON.parse(JSON.stringify(params))
    }
  }
}
</script>
      <style lang="scss" scoped>
      .map-container{
          nav{
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 16px;
              box-sizing: border-box;
              background-color: #193142;
          }
          .layout-map{
              display: flex;
              justify-content: space-between;
              height: calc(100vh - 190px);
              position: relative;
              #vmap {
                  height: 100%;
                  flex: 1;
                  background: #8c939d;
                  box-sizing: border-box;
              }
              #marker-tip{
                width: 200px;
                height: 200px;
                background-image: url(./tip.png);
                background-size: 100% 100%;
                background-repeat: no-repeat;
                position: absolute;
                z-index: 99999;
                padding: 15px 20px 0 20px;
                box-sizing: border-box;
                display: none;
                .head{
                  font-size: 24px;
                  color: #fff;
                }
                .item{
                  padding-top: 15px;
                  padding-bottom: 5px;
                  &.item{
                    padding-top: 8px;
                  }
                  .title{
                    font-size: 16px;
                    color: rgba(230, 247, 255, 0.6);
                    padding-bottom: 5px;
                  }
                  span{
                    font-size: 14px;
                    padding-right: 15px;
                    color: #fff;
                    .warn{
                      color: red;
                    }
                  }
                }
              }
          }

      }
      </style>

  <style lang="scss">
  .layout-map .goaf-icon-box,.leaflet-marker-icon{
    background-color: transparent;
    border-color: transparent;
  }
  .goaf-fill-v{
      width:100%;
      position: absolute;
      bottom: 0;
      left: 0;
      background-image: url("./goaf/stone.png");
      background-size: 7px;
      &.fill{
        background-image: url("./goaf/stone.png");
      }
  }
  .goaf-icon-tag{
    width: 100%;
    display: inline-block;
    background: linear-gradient(90deg, #21649c 0.21%, #060F1E 100%);
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
    color: #fff;
    text-align: center;
    z-index: 99999;
    position: absolute;
    top: -18px;
  }
  /*动画*/
.ico-warning {
  position: relative;
  &::after{
    display: block;
    content: "";
    height: 60%;
    width: 60%;
    background-image: radial-gradient(yellow,red);
    border-radius: 50% 50% 10% 10%;
    animation: twinkle 0.5s infinite alternate;
    position: absolute;
    transform: translate(-50%,-50%);
    left: 50%;
    top: 50%;
    box-shadow: 0 0 20px red;
    z-index: 9999;
  }
}

@keyframes twinkle {
    0% {opacity: 0.9;}
    50% {opacity: 0.5;}
    100% {opacity: 0;}
}
</style>
